stdlib enum map

This commit is contained in:
2026-07-19 13:02:36 +02:00
parent 709d977436
commit c1225f4ac2
8 changed files with 154 additions and 5 deletions
+45
View File
@@ -0,0 +1,45 @@
import "@std/meta"
EnumMap func($E, $V type) type {
match typeinfo!(E) {
.enum |info|: return struct {
present [info.fields.len]mut bool # fixme: replace with bitset
values [info.fields.len]mut V
}
else: compile_error!("EnumMap key must be an enum")
}
}
init func(
$E, $V type,
values meta.EnumFieldStruct(E, ?V, some!(none)),
) EnumMap(E, V) {
map EnumMap(E, V) = undefined
match typeinfo!(E) {
.enum |info|: expand for info.fields |field, i| {
map.present[i] = false
if field!(values, field.name) |value| {
map.present[i] = true
map.values[i] = value
}
}
else: compile_error!("EnumMap key must be an enum")
}
return map
}
get func($E, $V type, map @EnumMap(E, V), key E) ?V {
# fixme: linear lookup; implement an enum index/discriminant map for O(1) lookup
match typeinfo!(E) {
.enum |info|: expand for info.fields |field, i| {
if key == field!(E, field.name) {
if (map.present[i]) return map.values[i]
return none
}
}
else: compile_error!("EnumMap key must be an enum")
}
}
+25
View File
@@ -0,0 +1,25 @@
import "@std/mem"
import "@std/testing"
TestEnum :: enum(u8) {
ident = 3
int = 8
eof = 21
}
handles_sparse_enum_get test {
names EnumMap(TestEnum, []u8) = init({
ident = "identifier",
int = "integer",
})
ident :: get(&names, TestEnum.ident)
try testing.expect_type(?[]u8, ident)
try testing.expect(mem.eql("identifier", ident?))
eof :: get(&names, TestEnum.eof)
try testing.expect_type(?[]u8, eof)
try testing.expect_equal(none, eof)
}