Skip to content

Commit c4ad6be

Browse files
authored
Allow empty enum to be used in EnumSet/EnumMap
Moves the check for empty fields before any access to those fields.
1 parent 5996413 commit c4ad6be

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

lib/std/enums.zig

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -980,6 +980,17 @@ test "pure EnumSet fns" {
980980
try testing.expect(full.differenceWith(black).eql(red));
981981
}
982982

983+
test "std.enums.EnumSet empty" {
984+
const E = enum {};
985+
const empty = EnumSet(E).initEmpty();
986+
const full = EnumSet(E).initFull();
987+
988+
try std.testing.expect(empty.eql(full));
989+
try std.testing.expect(empty.complement().eql(full));
990+
try std.testing.expect(empty.complement().eql(full.complement()));
991+
try std.testing.expect(empty.eql(full.complement()));
992+
}
993+
983994
test "std.enums.EnumSet const iterator" {
984995
const Direction = enum { up, down, left, right };
985996
const diag_move = init: {
@@ -1296,9 +1307,8 @@ pub fn EnumIndexer(comptime E: type) type {
12961307

12971308
const const_fields = std.meta.fields(E);
12981309
var fields = const_fields[0..const_fields.len].*;
1299-
const min = fields[0].value;
1300-
const max = fields[fields.len - 1].value;
13011310
const fields_len = fields.len;
1311+
13021312
if (fields_len == 0) {
13031313
return struct {
13041314
pub const Key = E;
@@ -1314,6 +1324,9 @@ pub fn EnumIndexer(comptime E: type) type {
13141324
};
13151325
}
13161326

1327+
const min = fields[0].value;
1328+
const max = fields[fields.len - 1].value;
1329+
13171330
const SortContext = struct {
13181331
fields: []EnumField,
13191332

@@ -1424,3 +1437,11 @@ test "std.enums.EnumIndexer sparse" {
14241437
try testing.expectEqual(E.b, Indexer.keyForIndex(1));
14251438
try testing.expectEqual(E.c, Indexer.keyForIndex(2));
14261439
}
1440+
1441+
test "std.enums.EnumIndexer empty" {
1442+
const E = enum {};
1443+
const Indexer = EnumIndexer(E);
1444+
ensureIndexer(Indexer);
1445+
try testing.expectEqual(E, Indexer.Key);
1446+
try testing.expectEqual(@as(usize, 0), Indexer.count);
1447+
}

0 commit comments

Comments
 (0)