diff --git a/lib/std/meta.zig b/lib/std/meta.zig index e6ce746f19..0de51bfa68 100644 --- a/lib/std/meta.zig +++ b/lib/std/meta.zig @@ -10,6 +10,10 @@ pub const TrailerFlags = @import("meta/trailer_flags.zig").TrailerFlags; const Type = std.builtin.Type; +test "std.meta.TrailerFlags" { + _ = TrailerFlags; +} + pub fn tagName(v: anytype) []const u8 { const T = @TypeOf(v); switch (@typeInfo(T)) { diff --git a/lib/std/meta/trailer_flags.zig b/lib/std/meta/trailer_flags.zig index a128564708..212a47bc29 100644 --- a/lib/std/meta/trailer_flags.zig +++ b/lib/std/meta/trailer_flags.zig @@ -18,16 +18,14 @@ pub fn TrailerFlags(comptime Fields: type) type { pub const FieldEnum = std.meta.FieldEnum(Fields); - pub const InitStruct = blk: { + pub const ActiveFields = std.enums.EnumFieldStruct(FieldEnum, bool, false); + pub const FieldValues = blk: { comptime var fields: [bit_count]Type.StructField = undefined; inline for (@typeInfo(Fields).Struct.fields) |struct_field, i| { fields[i] = Type.StructField{ .name = struct_field.name, .field_type = ?struct_field.field_type, - .default_value = @as( - ??struct_field.field_type, - @as(?struct_field.field_type, null), - ), + .default_value = &@as(?struct_field.field_type, null), .is_comptime = false, .alignment = @alignOf(?struct_field.field_type), }; @@ -60,19 +58,18 @@ pub fn TrailerFlags(comptime Fields: type) type { self.bits |= 1 << field_index; } - /// `fields` is a struct with each field set to an optional value. - /// Only the non-null bits are observed and are used to set the flag bits. - pub fn init(fields: InitStruct) Self { + /// `fields` is a boolean struct where each active field is set to `true` + pub fn init(fields: ActiveFields) Self { var self: Self = .{ .bits = 0 }; inline for (@typeInfo(Fields).Struct.fields) |field, i| { - if (@field(fields, field.name)) |_| + if (@field(fields, field.name)) self.bits |= 1 << i; } return self; } - /// `fields` is a struct with each field set to an optional value (same as `init`). - pub fn setMany(self: Self, p: [*]align(@alignOf(Fields)) u8, fields: InitStruct) void { + /// `fields` is a struct with each field set to an optional value + pub fn setMany(self: Self, p: [*]align(@alignOf(Fields)) u8, fields: FieldValues) void { inline for (@typeInfo(Fields).Struct.fields) |field, i| { if (@field(fields, field.name)) |value| self.set(p, @intToEnum(FieldEnum, i), value); @@ -145,7 +142,7 @@ test "TrailerFlags" { var flags = Flags.init(.{ .b = true, - .c = 1234, + .c = true, }); const slice = try testing.allocator.allocAdvanced(u8, 8, flags.sizeInBytes(), .exact); defer testing.allocator.free(slice);