mirror of
https://github.com/ziglang/zig.git
synced 2026-01-20 14:25:16 +00:00
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| {}
This commit is contained in:
parent
8ff49966bc
commit
7e07df06a4
@ -13,21 +13,21 @@ const mem = std.mem;
|
||||
/// `kvs` expects a list literal containing list literals or an array/slice of structs
|
||||
/// where `.@"0"` is the `[]const u8` key and `.@"1"` is the associated value of type `V`.
|
||||
/// TODO: https://github.com/ziglang/zig/issues/4335
|
||||
pub fn ComptimeStringMap(comptime V: type, comptime kvs: anytype) type {
|
||||
pub fn ComptimeStringMap(comptime V: type, comptime kvs_list: anytype) type {
|
||||
const precomputed = comptime blk: {
|
||||
@setEvalBranchQuota(2000);
|
||||
const KV = struct {
|
||||
key: []const u8,
|
||||
value: V,
|
||||
};
|
||||
var sorted_kvs: [kvs.len]KV = undefined;
|
||||
var sorted_kvs: [kvs_list.len]KV = undefined;
|
||||
const lenAsc = (struct {
|
||||
fn lenAsc(context: void, a: KV, b: KV) bool {
|
||||
_ = context;
|
||||
return a.key.len < b.key.len;
|
||||
}
|
||||
}).lenAsc;
|
||||
for (kvs) |kv, i| {
|
||||
for (kvs_list) |kv, i| {
|
||||
if (V != void) {
|
||||
sorted_kvs[i] = .{ .key = kv.@"0", .value = kv.@"1" };
|
||||
} else {
|
||||
@ -56,6 +56,8 @@ pub fn ComptimeStringMap(comptime V: type, comptime kvs: anytype) type {
|
||||
};
|
||||
|
||||
return struct {
|
||||
pub const kvs = precomputed.sorted_kvs;
|
||||
|
||||
pub fn has(str: []const u8) bool {
|
||||
return get(str) != null;
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user