authorgravatar for git@scottredig.comScott Redig <git@scottredig.com> 2026-09-11 00:54:56-07:00
committergravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2026-09-12 09:28:55+02:00
log2be592bb3ca71621422428ec8874b34a77606013
treebf8afb5423abeda1651bddc24bc28d618f22d4d8
parente90365cd51fdc261d4f5ad9fc53729127ca615a8

Add EnumMap.empty, deprecate default fields


1 files changed, 16 insertions(+), 5 deletions(-)

lib/std/enums.zig+16-5
......@@ -420,6 +420,8 @@ pub fn EnumSet(comptime E: type) type {
420420/// If the enum is exhaustive but not dense, a mapping will be constructed from
421421/// enum values to dense indices. This type does no dynamic
422422/// allocation and can be copied by value.
423///
424/// Default initialization is deprecated; use .empty instead.
423425pub fn EnumMap(comptime E: type, comptime V: type) type {
424426 return struct {
425427 const Self = @This();
......@@ -441,6 +443,11 @@ pub fn EnumMap(comptime E: type, comptime V: type) type {
441443 /// bit is zero, the value is undefined.
442444 values: [Indexer.count]Value = undefined,
443445
446 pub const empty: Self = .{
447 .bits = .empty,
448 .values = undefined,
449 };
450
444451 /// Initializes the map using a sparse struct of optionals
445452 pub fn init(init_values: EnumFieldStruct(E, ?Value, @as(?Value, null))) Self {
446453 @setEvalBranchQuota(2 * @typeInfo(E).@"enum".field_names.len);
......@@ -470,12 +477,10 @@ pub fn EnumMap(comptime E: type, comptime V: type) type {
470477 /// Initializes a full mapping with all keys set to value.
471478 /// Consider using EnumArray instead if the map will remain full.
472479 pub fn initFull(value: Value) Self {
473 var result: Self = .{
480 return .{
474481 .bits = .full,
475 .values = undefined,
482 .values = @splat(value),
476483 };
477 @memset(&result.values, value);
478 return result;
479484 }
480485
481486 /// Initializes a full mapping with supplied values.
......@@ -645,7 +650,10 @@ pub fn EnumMap(comptime E: type, comptime V: type) type {
645650test EnumMap {
646651 const Ball = enum { red, green, blue };
647652
648 const some = EnumMap(Ball, u8).init(.{
653 const none: EnumMap(Ball, u8) = .empty;
654 try testing.expectEqual(0, none.count());
655
656 const some: EnumMap(Ball, u8) = .init(.{
649657 .green = 0xff,
650658 .blue = 0x80,
651659 });
......@@ -653,6 +661,9 @@ test EnumMap {
653661 try testing.expectEqual(null, some.get(.red));
654662 try testing.expectEqual(0xff, some.get(.green));
655663 try testing.expectEqual(0x80, some.get(.blue));
664
665 const all: EnumMap(Ball, u8) = .initFull(0);
666 try testing.expectEqual(3, all.count());
656667}
657668
658669/// A multiset of enum elements up to a count of usize. Backed