top | item 36620734

(no title)

cancername | 2 years ago

Yes:

    const std = @import("std");
    const expectEqual = std.testing.expectEqual;

    test "u4 is 1 byte" {
        try expectEqual(1, @sizeOf(u4));
    }

    test "u4 is 4 bits" {
        try expectEqual(4, @bitSizeOf(u4));
    }

    test "u4 is 1-byte-aligned" {
        try expectEqual(1, @alignOf(u4));
    }

    test "pointers to u4 work like any other pointer type" {
        var foo: u4 = 10;
        const foo_p = &foo;
        try expectEqual(@as(u4, 10), foo_p.*);
        foo_p.* = 7;
        try expectEqual(@as(u4, 7), foo);
    }
Packed structs are Zig's replacement for bit fields:

    const std = @import("std");
    const expectEqual = std.testing.expectEqual;
    
    test "bool has a bit size of 1 bit, a size of 1 byte, and an alignment of 1 byte" {
        try expectEqual(1, @bitSizeOf(bool));
        try expectEqual(1, @sizeOf(bool));
        try expectEqual(1, @alignOf(bool));
    }
    
    test "in a regular struct, fields are aligned to their natural alignment..." {
        const Natural = struct {
            read: bool,
            write: bool,
            exec: bool,
        };
        try expectEqual(3, @sizeOf(Natural));
        try expectEqual(1, @alignOf(Natural));
    }
    
    test "...unless otherwise specified" {
        const TwoByteAligned = struct {
            read: bool align(2),
            write: bool align(2),
            exec: bool align(2),
        };
        try expectEqual(6, @sizeOf(TwoByteAligned));
        try expectEqual(2, @alignOf(TwoByteAligned));
    }
    
    test "in a packed struct, fields occupy exactly their bit size" {
        const Packed = packed struct {
            read: bool,
            write: bool,
            exec: bool,
        };
        try expectEqual(3, @bitSizeOf(Packed));
        try expectEqual(1, @sizeOf(Packed));
        try expectEqual(1, @alignOf(Packed));
    }

discuss

order

No comments yet.