const arch = std.Target.current.cpu.arch; const bytesAsSlice = std.mem.bytesAsSlice; const expect = std.testing.expect; const sliceAsBytes = std.mem.sliceAsBytes; const std = @import("std"); test "variable alignment" { var x: i32 = 1234; const align_of_i32 = @alignOf(@TypeOf(x)); expect(@TypeOf(&x) == *i32); expect(*i32 == *align(align_of_i32) i32); if (arch == .x86_64) expect(@typeInfo(*i32).Pointer.alignment == 4); } var foo: u8 align(4) = 100; test "global variable alignment" { expect(@typeInfo(@TypeOf(&foo)).Pointer.alignment == 4); expect(@TypeOf(&foo) == *align(4) u8); const as_pointer_to_array: *[1]u8 = &foo; const as_slice: []u8 = as_pointer_to_array; expect(@TypeOf(as_slice) == []align(4) u8); } fn derp() align(@sizeOf(usize) * 2) i32 { return 1234; } fn noop1() align(1) void {} fn noop4() align(4) void {} test "function alignment" { expect(derp() == 1234); expect(@TypeOf(noop1) == fn() align(1) void); expect(@TypeOf(noop4) == fn() align(4) void); noop1(); noop4(); } test "pointer alignment safety" { var array align(4) = [_]u32{ 0x11111111, 0x11111111 }; const bytes = sliceAsBytes(array[0..]); expect(bar(bytes) == 0x11111111); } fn bar(bytes: []u8) u32 { const slice4 = bytes[1..5]; const int_slice = bytesAsSlice(u32, @alignCast(4, slice4)); return int_slice[0]; }