directEnumArrayLen
Determines the length of a direct-mapped enum array, indexed by @intCast(usize, @intFromEnum(enum_value)). If the enum is non-exhaustive, the resulting length will only be enough to hold all explicit fields. If the enum contains any fields with values that cannot be represented by usize, a compile error is issued. The max_unused_slots parameter limits the total number of items which have no matching enum key (holes in the enum numbering). So for example, if an enum has values 1, 2, 5, and 6, max_unused_slots must be at least 3, to allow unused slots 0, 3, and 4.
Function parameters
Parameters
- E:type
- max_unused_slots:comptime_int
Functions in this namespace
Functions
- EnumFieldStruct
- Returns a struct with a field matching each unique named enum element.
- valuesFromFields
- Looks up the supplied fields in the given enum type.
- values
- Returns the set of all named values in the given enum, in
- tagName
- A safe alternative to @tagName() for non-exhaustive enums that doesn't
- directEnumArrayLen
- Determines the length of a direct-mapped enum array, indexed by
- directEnumArray
- Initializes an array of Data which can be indexed by
- directEnumArrayDefault
- Initializes an array of Data which can be indexed by
- nameCast
- Deprecated: Use @field(E, @tagName(tag)) or @field(E, string)
- EnumSet
- A set of enum elements, backed by a bitfield.
- EnumMap
- A map keyed by an enum, backed by a bitfield and a dense array.
- EnumMultiset
- A multiset of enum elements up to a count of usize.
- BoundedEnumMultiset
- A multiset of enum elements up to CountSize.
- EnumArray
- An array keyed by an enum, backed by a dense array.
Source
Implementation
pub fn directEnumArrayLen(comptime E: type, comptime max_unused_slots: comptime_int) comptime_int {
var max_value: comptime_int = -1;
const max_usize: comptime_int = ~@as(usize, 0);
const fields = @typeInfo(E).@"enum".fields;
for (fields) |f| {
if (f.value < 0) {
@compileError("Cannot create a direct enum array for " ++ @typeName(E) ++ ", field ." ++ f.name ++ " has a negative value.");
}
if (f.value > max_value) {
if (f.value > max_usize) {
@compileError("Cannot create a direct enum array for " ++ @typeName(E) ++ ", field ." ++ f.name ++ " is larger than the max value of usize.");
}
max_value = f.value;
}
}
const unused_slots = max_value + 1 - fields.len;
if (unused_slots > max_unused_slots) {
const unused_str = std.fmt.comptimePrint("{d}", .{unused_slots});
const allowed_str = std.fmt.comptimePrint("{d}", .{max_unused_slots});
@compileError("Cannot create a direct enum array for " ++ @typeName(E) ++ ". It would have " ++ unused_str ++ " unused slots, but only " ++ allowed_str ++ " are allowed.");
}
return max_value + 1;
}