authorgravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2026-06-04 21:41:12-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-06-06 23:37:09+02:00
log6aa93facbf75e732b0e8691b676db351e86ad113
treefaf960fe391acb6f6581387e36e38fe5b408d0fd
parent2153f8143d32ff47d494955e2a1924cf333033e5

StaticStringMap: reinstate pub `getIndex` with clarifying docs and test


1 files changed, 30 insertions(+), 1 deletions(-)

lib/std/static_string_map.zig+30-1
......@@ -241,7 +241,10 @@ pub fn StaticStringMapWithEql(
241241 return self.kvs.values[self.getIndex(str) orelse return null];
242242 }
243243
244 fn getIndex(self: Self, str: []const u8) ?usize {
244 /// Returns the index corresponding to the `str` within the
245 /// generated `kvs`, or `null` if `str` was not found.
246 /// The returned index is unrelated to the input `kvs_list`.
247 pub fn getIndex(self: Self, str: []const u8) ?usize {
245248 const kvs = self.kvs.*;
246249 if (kvs.len == 0)
247250 return null;
......@@ -279,6 +282,14 @@ pub fn StaticStringMapWithEql(
279282 };
280283 }
281284
285 /// Returns the index within the generated `kvs` corresponding to the
286 /// key-value pair where key is the longest prefix of `str`, or `null`
287 /// if no such key-value pair was found. The returned index is unrelated
288 /// to the input `kvs_list`.
289 ///
290 /// This is effectively an O(N) algorithm which loops from `max_len` to
291 /// `min_len` and calls `getIndex()` to check all keys with the given
292 /// len.
282293 pub fn getLongestPrefixIndex(self: Self, str: []const u8) ?usize {
283294 if (self.kvs.len == 0)
284295 return null;
......@@ -294,11 +305,15 @@ pub fn StaticStringMapWithEql(
294305 return null;
295306 }
296307
308 /// Returns the slice of keys from the generated `kvs`, which may
309 /// be in a different order than the input `kvs_list`.
297310 pub fn keys(self: Self) []const []const u8 {
298311 const kvs = self.kvs.*;
299312 return kvs.keys[0..kvs.len];
300313 }
301314
315 /// Returns the slice of values from the generated `kvs`, which may
316 /// be in a different order than the input `kvs_list`.
302317 pub fn values(self: Self) []const V {
303318 const kvs = self.kvs.*;
304319 return kvs.values[0..kvs.len];
......@@ -504,6 +519,20 @@ test "comptime-only value" {
504519 try testing.expect(map.get("d") == null);
505520}
506521
522test "getIndex" {
523 const slice = [_]TestKV{
524 .{ "longer", .A },
525 .{ "short", .B },
526 };
527 const map = TestMap.initComptime(slice);
528
529 // This index can be different than the index of the "short" KV in `slice`
530 const short_index = map.getIndex("short").?;
531 try testing.expectEqualStrings("short", map.keys()[short_index]);
532 try testing.expectEqual(.B, map.values()[short_index]);
533 try testing.expectEqual(null, map.getIndex("missing"));
534}
535
507536test "getLongestPrefix" {
508537 const slice = [_]TestKV{
509538 .{ "a", .A },