authorgravatar for christofer@nolander.meChristofer Nolander <christofer@nolander.me> 2023-09-28 23:48:39+02:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-09-28 21:48:39+00:00
logc4ad6be0023ad351a59f53cab7c59fccecb6f82d
treefe2bafe86525a4ce398cf2468112d0b51b306c7e
parent599641357cda1ff86ebc515d0761f98fb8c507a8
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Allow empty `enum` to be used in `EnumSet`/`EnumMap`

Moves the check for empty fields before any access to those fields.

1 files changed, 23 insertions(+), 2 deletions(-)

lib/std/enums.zig+23-2
......@@ -980,6 +980,17 @@ test "pure EnumSet fns" {
980980 try testing.expect(full.differenceWith(black).eql(red));
981981}
982982
983test "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
983994test "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
1441test "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}