commit 6aa93facbf75e732b0e8691b676db351e86ad113 (tree)
parent 2153f8143d32ff47d494955e2a1924cf333033e5
Author: Ryan Liptak <squeek502@hotmail.com>
Date: Thu, 4 Jun 2026 21:41:12 -0700
StaticStringMap: reinstate pub `getIndex` with clarifying docs and test
Diffstat:
1 file changed, 30 insertions(+), 1 deletion(-)
diff --git a/lib/std/static_string_map.zig b/lib/std/static_string_map.zig
@@ -241,7 +241,10 @@ pub fn StaticStringMapWithEql(
return self.kvs.values[self.getIndex(str) orelse return null];
}
- fn getIndex(self: Self, str: []const u8) ?usize {
+ /// Returns the index corresponding to the `str` within the
+ /// generated `kvs`, or `null` if `str` was not found.
+ /// The returned index is unrelated to the input `kvs_list`.
+ pub fn getIndex(self: Self, str: []const u8) ?usize {
const kvs = self.kvs.*;
if (kvs.len == 0)
return null;
@@ -279,6 +282,14 @@ pub fn StaticStringMapWithEql(
};
}
+ /// Returns the index within the generated `kvs` corresponding to the
+ /// key-value pair where key is the longest prefix of `str`, or `null`
+ /// if no such key-value pair was found. The returned index is unrelated
+ /// to the input `kvs_list`.
+ ///
+ /// This is effectively an O(N) algorithm which loops from `max_len` to
+ /// `min_len` and calls `getIndex()` to check all keys with the given
+ /// len.
pub fn getLongestPrefixIndex(self: Self, str: []const u8) ?usize {
if (self.kvs.len == 0)
return null;
@@ -294,11 +305,15 @@ pub fn StaticStringMapWithEql(
return null;
}
+ /// Returns the slice of keys from the generated `kvs`, which may
+ /// be in a different order than the input `kvs_list`.
pub fn keys(self: Self) []const []const u8 {
const kvs = self.kvs.*;
return kvs.keys[0..kvs.len];
}
+ /// Returns the slice of values from the generated `kvs`, which may
+ /// be in a different order than the input `kvs_list`.
pub fn values(self: Self) []const V {
const kvs = self.kvs.*;
return kvs.values[0..kvs.len];
@@ -504,6 +519,20 @@ test "comptime-only value" {
try testing.expect(map.get("d") == null);
}
+test "getIndex" {
+ const slice = [_]TestKV{
+ .{ "longer", .A },
+ .{ "short", .B },
+ };
+ const map = TestMap.initComptime(slice);
+
+ // This index can be different than the index of the "short" KV in `slice`
+ const short_index = map.getIndex("short").?;
+ try testing.expectEqualStrings("short", map.keys()[short_index]);
+ try testing.expectEqual(.B, map.values()[short_index]);
+ try testing.expectEqual(null, map.getIndex("missing"));
+}
+
test "getLongestPrefix" {
const slice = [_]TestKV{
.{ "a", .A },