authorgravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2021-08-13 16:16:29-07:00
committergravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2021-08-13 16:22:56-07:00
log7e07df06a4f1507be216c84b034167cdee1817f7
tree4a7aa2c694cd784f5d4a3c85418621d8b1612d49
parent8ff49966bc9d6d7438640fa475e95f9a24a4b931

ComptimeStringMap: expose kvs array in returned struct

Allows for iterating over the kvs when constructing with a list literal instead of having to create a separate array to pass into ComptimeStringMap in order to maintain access to the values. For example when making a set, before in order to loop over the kvs you'd have to do something like: const MyKV = struct { @"0": []const u8 }; const kvs: []const MyKV = &[_]MyKV{ .{ @"0" = "foo"}, .{ @"0" = "bar" } }; const map = ComptimeStringMap(void, kvs); for (kvs) |kv| {} whereas now it's possible to do: const map = ComptimeStringMap(void, .{ .{"foo"}, .{"bar"} }); for (map.kvs) |kv| {}

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

lib/std/comptime_string_map.zig+5-3
......@@ -13,21 +13,21 @@ const mem = std.mem;
1313/// `kvs` expects a list literal containing list literals or an array/slice of structs
1414/// where `.@"0"` is the `[]const u8` key and `.@"1"` is the associated value of type `V`.
1515/// TODO: https://github.com/ziglang/zig/issues/4335
16pub fn ComptimeStringMap(comptime V: type, comptime kvs: anytype) type {
16pub fn ComptimeStringMap(comptime V: type, comptime kvs_list: anytype) type {
1717 const precomputed = comptime blk: {
1818 @setEvalBranchQuota(2000);
1919 const KV = struct {
2020 key: []const u8,
2121 value: V,
2222 };
23 var sorted_kvs: [kvs.len]KV = undefined;
23 var sorted_kvs: [kvs_list.len]KV = undefined;
2424 const lenAsc = (struct {
2525 fn lenAsc(context: void, a: KV, b: KV) bool {
2626 _ = context;
2727 return a.key.len < b.key.len;
2828 }
2929 }).lenAsc;
30 for (kvs) |kv, i| {
30 for (kvs_list) |kv, i| {
3131 if (V != void) {
3232 sorted_kvs[i] = .{ .key = kv.@"0", .value = kv.@"1" };
3333 } else {
......@@ -56,6 +56,8 @@ pub fn ComptimeStringMap(comptime V: type, comptime kvs: anytype) type {
5656 };
5757
5858 return struct {
59 pub const kvs = precomputed.sorted_kvs;
60
5961 pub fn has(str: []const u8) bool {
6062 return get(str) != null;
6163 }