zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

test_pointer_casting.zig (812B) - Raw


      1 const std = @import("std");
      2 const expect = std.testing.expect;
      3 
      4 test "pointer casting" {
      5     const bytes align(@alignOf(u32)) = [_]u8{ 0x12, 0x12, 0x12, 0x12 };
      6     const u32_ptr: *const u32 = @ptrCast(&bytes);
      7     try expect(u32_ptr.* == 0x12121212);
      8 
      9     // Even this example is contrived - there are better ways to do the above than
     10     // pointer casting. For example, using a slice narrowing cast:
     11     const u32_value = std.mem.bytesAsSlice(u32, bytes[0..])[0];
     12     try expect(u32_value == 0x12121212);
     13 
     14     // And even another way, the most straightforward way to do it:
     15     try expect(@as(u32, @bitCast(bytes)) == 0x12121212);
     16 }
     17 
     18 test "pointer child type" {
     19     // pointer types have a `child` field which tells you the type they point to.
     20     try expect(@typeInfo(*u32).pointer.child == u32);
     21 }
     22 
     23 // test