about summary refs log tree commit diff
path: root/lang/zig/align.zig
blob: b81740a6dd78798388af0bca8b712b0d390e744b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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];
}