Merge pull request #11581 from erikarvstedt/fix-trailerflags

Fix `std.meta.TrailerFlags`
This commit is contained in:
Andrew Kelley 2022-05-19 21:15:16 -04:00 committed by GitHub
commit dd6ac9a22a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 12 deletions

View File

@ -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)) {

View File

@ -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);