跳转到内容

std.static_string_map

标准库Zig 0.17.0官方原文
源码std/static_string_map.zig

第 1 行

std.static_string_map.defaultEql

函数

第 13 行

类似 std.mem.eql,但利用了 a 和 b 的长度 已知相等这一条件。

pub fn defaultEql(a: []const u8, b: []const u8) bool

参数

a: []const u8
b: []const u8

std.static_string_map.eqlAsciiIgnoreCase

函数

第 23 行

类似于 std.ascii.eqlIgnoreCase,但利用了已知 a 和 b 长度相等这一条件。

pub fn eqlAsciiIgnoreCase(a: []const u8, b: []const u8) bool

参数

a: []const u8
b: []const u8

std.static_string_map.foo

常量

第 506 行

std.static_string_map.foo

常量

第 509 行

std.static_string_map.foo

常量

第 512 行

std.static_string_map.mem

别名

第 2 行

别名目标 std.mem

std.static_string_map.StaticStringMap

类型函数

第 7 行

针对小规模、不同字符串键集合优化的静态字符串映射。 初始化时按长度分组键,运行时仅比较 长度相同的字符串。

pub fn StaticStringMap(comptime V: type) type

参数

V: type

字段

kvs: *const KVs = &empty_kvs
len_indexes: [*]const u32 = &empty_len_indexes
len_indexes_len: u32 = 0
min_len: u32 = std.math.maxInt(u32)
max_len: u32 = 0

std.static_string_map.StaticStringMapWithEql

类型函数

第 35 行

StaticStringMap,但接受相等性函数(eql)。 仅当字符串长度相等时,才会调用 eql 函数判断是否相等。 长度不同的字符串绝不会传入 eql 函数比较。

pub fn StaticStringMapWithEql( comptime V: type, comptime eql: fn (a: []const u8, b: []const u8) bool, ) type

参数

V: type
eql: fn (a: []const u8, b: []const u8) bool

字段

kvs: *const KVs = &empty_kvs
len_indexes: [*]const u32 = &empty_len_indexes
len_indexes_len: u32 = 0
min_len: u32 = std.math.maxInt(u32)
max_len: u32 = 0

std.static_string_map.StaticStringMapWithEql.deinit

函数

第 180 行

此方法仅应配合 init() 使用,不应配合 initComptime() 使用。

pub fn deinit(self: Self, allocator: mem.Allocator) void

参数

self: Self
allocator: mem.Allocator

std.static_string_map.StaticStringMapWithEql.empty_keys

常量

第 63 行

std.static_string_map.StaticStringMapWithEql.empty_kvs

常量

第 57 行

std.static_string_map.StaticStringMapWithEql.empty_len_indexes

常量

第 62 行

std.static_string_map.StaticStringMapWithEql.empty_vals

常量

第 64 行

std.static_string_map.StaticStringMapWithEql.get

函数

第 237 行

若存在则返回键对应的值,否则返回 null。

pub fn get(self: Self, str: []const u8) ?V

参数

self: Self
str: []const u8

std.static_string_map.StaticStringMapWithEql.getIndex

函数

第 247 行

返回 str 在生成的 kvs 中对应的索引; 若未找到 str,则返回 null。 返回的索引与输入 kvs_list 无关。

pub fn getIndex(self: Self, str: []const u8) ?usize

参数

self: Self
str: []const u8

std.static_string_map.StaticStringMapWithEql.getLongestPrefix

函数

第 274 行

返回键为 str 最长前缀的键值对, 否则返回 null。

该算法实际上为 O(N):从 max_len 到 min_len 循环,并调用 getIndex() 检查 具有给定长度的所有键。

pub fn getLongestPrefix(self: Self, str: []const u8) ?KV

参数

self: Self
str: []const u8

std.static_string_map.StaticStringMapWithEql.getLongestPrefixIndex

函数

第 293 行

返回生成的 kvs 中某个键值对的索引, 其键为 str 的最长前缀;若未找到,则返回 null。 返回索引与输入 kvs_list 无关。

此算法实际复杂度为 O(N),从 max_len 循环到 min_len,调用 getIndex() 检查所有 指定长度的键。

pub fn getLongestPrefixIndex(self: Self, str: []const u8) ?usize

参数

self: Self
str: []const u8

std.static_string_map.StaticStringMapWithEql.has

函数

第 232 行

检查映射中是否有指定键对应的值。

pub fn has(self: Self, str: []const u8) bool

参数

self: Self
str: []const u8

std.static_string_map.StaticStringMapWithEql.init

函数

第 152 行

返回由 allocator 分配内存支持的映射。

处理 kvs_list 的方式与 initComptime() 相同。

pub fn init(kvs_list: anytype, allocator: mem.Allocator) !Self

参数

allocator: mem.Allocator

std.static_string_map.StaticStringMapWithEql.initComptime

函数

第 71 行

返回一个映射,其底层存储为编译时分配的静态内存。

kvs_list 必须是 struct { []const u8, V } (键值对)元组列表;若 V 为 void,则必须是 struct { []const u8 } (仅键)元组列表。

pub inline fn initComptime(comptime kvs_list: anytype) Self

std.static_string_map.StaticStringMapWithEql.initEnum

函数

第 106 行

返回由编译期分配的静态内存支持的映射。

V 必须为枚举。枚举标签名称将用作键。

pub inline fn initEnum() Self

std.static_string_map.StaticStringMapWithEql.initLenIndexes

函数

第 219 行

fn initLenIndexes(self: Self, len_indexes: []u32) void

参数

self: Self
len_indexes: []u32

std.static_string_map.StaticStringMapWithEql.initSortedKVs

函数

第 201 行

fn initSortedKVs( self: *Self, kvs_list: anytype, sorted_keys: [][]const u8, sorted_vals: []V, ) void

参数

self: *Self
sorted_keys: [][]const u8
sorted_vals: []V

std.static_string_map.StaticStringMapWithEql.keys

函数

第 310 行

返回生成的 kvs 中键的切片,其顺序 可能不同于输入的 kvs_list。

pub fn keys(self: Self) []const []const u8

参数

self: Self

std.static_string_map.StaticStringMapWithEql.KV

容器

第 46 行

字段

key: []const u8
value: V

std.static_string_map.StaticStringMapWithEql.KVs

容器

第 52 行

字段

keys: [*]const []const u8
values: [*]const V
len: u32

std.static_string_map.StaticStringMapWithEql.Self

别名

第 51 行

别名目标 std.static_string_map.StaticStringMapWithEql

std.static_string_map.StaticStringMapWithEql.SortContext

容器

第 187 行

字段

keys: [][]const u8
vals: []V

std.static_string_map.StaticStringMapWithEql.SortContext.lessThan

函数

第 191 行

pub fn lessThan(ctx: @This(), a: usize, b: usize) bool

参数

ctx: @This()
a: usize
b: usize

std.static_string_map.StaticStringMapWithEql.SortContext.swap

函数

第 195 行

pub fn swap(ctx: @This(), a: usize, b: usize) void

参数

ctx: @This()
a: usize
b: usize

std.static_string_map.StaticStringMapWithEql.values

函数

第 317 行

返回生成的 kvs 中值的切片, 其顺序可能与输入 kvs_list 不同。

pub fn values(self: Self) []const V

参数

self: Self

std.static_string_map.std

别名

第 1 行

别名目标 std

std.static_string_map.test_alloc

别名

第 331 行

别名目标 std.testing.allocator

std.static_string_map.TestEnum

容器

第 324 行

字段

A
B
C
D
E

std.static_string_map.testing

别名

第 330 行

别名目标 std.testing

std.static_string_map.TestKV

容器

第 326 行

字段

[]const u8
TestEnum

std.static_string_map.TestKVVoid

容器

第 328 行

字段

[]const u8

std.static_string_map.testMap

函数

第 379 行

fn testMap(map: anytype) !void

std.static_string_map.TestMap

类型

第 325 行

std.static_string_map.TestMapVoid

类型

第 327 行

std.static_string_map.TestMapWithEql

类型

第 329 行

std.static_string_map.testSet

函数

第 419 行

fn testSet(map: TestMapVoid) !void

参数

std.static_string_map.testStaticStringMapWithEql

函数

第 433 行

fn testStaticStringMapWithEql(map: TestMapWithEql) !void

参数

源码

std/static_string_map.zig

const std = @import("std.zig");
const mem = std.mem;

/// 针对小规模、不同字符串键集合优化的静态字符串映射。
/// 初始化时按长度分组键,运行时仅比较
/// 长度相同的字符串。
pub fn StaticStringMap(comptime V: type) type {
    return StaticStringMapWithEql(V, defaultEql);
}

/// 类似 `std.mem.eql`,但利用了 `a` 和 `b` 的长度
/// 已知相等这一条件。
pub fn defaultEql(a: []const u8, b: []const u8) bool {
    if (a.ptr == b.ptr) return true;
    for (a, b) |a_elem, b_elem| {
        if (a_elem != b_elem) return false;
    }
    return true;
}

/// 类似于 `std.ascii.eqlIgnoreCase`,但利用了已知 `a` 和 `b` 长度相等这一条件。
///
pub fn eqlAsciiIgnoreCase(a: []const u8, b: []const u8) bool {
    if (a.ptr == b.ptr) return true;
    for (a, b) |a_c, b_c| {
        if (std.ascii.toLower(a_c) != std.ascii.toLower(b_c)) return false;
    }
    return true;
}

/// StaticStringMap,但接受相等性函数(`eql`)。
/// 仅当字符串长度相等时,才会调用 `eql` 函数判断是否相等。
/// 长度不同的字符串绝不会传入 `eql` 函数比较。
///
pub fn StaticStringMapWithEql(
    comptime V: type,
    comptime eql: fn (a: []const u8, b: []const u8) bool,
) type {
    return struct {
        kvs: *const KVs = &empty_kvs,
        len_indexes: [*]const u32 = &empty_len_indexes,
        len_indexes_len: u32 = 0,
        min_len: u32 = std.math.maxInt(u32),
        max_len: u32 = 0,

        pub const KV = struct {
            key: []const u8,
            value: V,
        };

        const Self = @This();
        const KVs = struct {
            keys: [*]const []const u8,
            values: [*]const V,
            len: u32,
        };
        const empty_kvs = KVs{
            .keys = &empty_keys,
            .values = &empty_vals,
            .len = 0,
        };
        const empty_len_indexes = [0]u32{};
        const empty_keys = [0][]const u8{};
        const empty_vals = [0]V{};

        /// 返回一个映射,其底层存储为编译时分配的静态内存。
        ///
        /// `kvs_list` 必须是 `struct { []const u8, V }`
        /// (键值对)元组列表;若 `V` 为 `void`,则必须是 `struct { []const u8 }`
        /// (仅键)元组列表。
        pub inline fn initComptime(comptime kvs_list: anytype) Self {
            comptime {
                var self = Self{};
                if (kvs_list.len == 0)
                    return self;

                // 由于键值对已排序,线性增长的界限在极端情况下
                // 始终不足,因此按
                // N*log2(N) 的比例增长。
                @setEvalBranchQuota(10 * kvs_list.len * std.math.log2_int_ceil(usize, kvs_list.len));

                var sorted_keys: [kvs_list.len][]const u8 = undefined;
                var sorted_vals: [kvs_list.len]V = undefined;

                self.initSortedKVs(kvs_list, &sorted_keys, &sorted_vals);
                const final_keys = sorted_keys;
                const final_vals = sorted_vals;
                self.kvs = &.{
                    .keys = &final_keys,
                    .values = &final_vals,
                    .len = @intCast(kvs_list.len),
                };

                var len_indexes: [self.max_len + 1]u32 = undefined;
                self.initLenIndexes(&len_indexes);
                const final_len_indexes = len_indexes;
                self.len_indexes = &final_len_indexes;
                self.len_indexes_len = @intCast(len_indexes.len);
                return self;
            }
        }

        /// 返回由编译期分配的静态内存支持的映射。
        ///
        /// `V` 必须为枚举。枚举标签名称将用作键。
        pub inline fn initEnum() Self {
            comptime {
                var self: Self = .{};

                const field_names = @typeInfo(V).@"enum".field_names;
                if (field_names.len == 0) return self;

                // 由于键值对已排序,线性增长的界限在极端情况下
                // 始终不足,因此按
                // N*log2(N) 的比例增长。
                @setEvalBranchQuota(10 * field_names.len * std.math.log2_int_ceil(usize, field_names.len));

                var sorted_keys: [field_names.len][]const u8 = field_names[0..field_names.len].*;
                var sorted_vals: [field_names.len]V = undefined;
                for (&sorted_vals, @typeInfo(V).@"enum".field_values) |*x, i| x.* = @fromBackingInt(@intCast(i));

                for (field_names) |field_name| {
                    self.min_len = @min(self.min_len, field_name.len);
                    self.max_len = @max(self.max_len, field_name.len);
                }

                mem.sortUnstableContext(0, sorted_keys.len, SortContext{
                    .keys = &sorted_keys,
                    .vals = &sorted_vals,
                });

                const final_keys = sorted_keys;
                const final_vals = sorted_vals;
                self.kvs = &.{
                    .keys = &final_keys,
                    .values = &final_vals,
                    .len = @intCast(field_names.len),
                };

                var len_indexes: [self.max_len + 1]u32 = undefined;
                self.initLenIndexes(&len_indexes);
                const final_len_indexes = len_indexes;
                self.len_indexes = &final_len_indexes;
                self.len_indexes_len = @intCast(len_indexes.len);
                return self;
            }
        }

        /// 返回由 `allocator` 分配内存支持的映射。
        ///
        /// 处理 `kvs_list` 的方式与 `initComptime()` 相同。
        pub fn init(kvs_list: anytype, allocator: mem.Allocator) !Self {
            var self = Self{};
            if (kvs_list.len == 0)
                return self;

            const sorted_keys = try allocator.alloc([]const u8, kvs_list.len);
            errdefer allocator.free(sorted_keys);
            const sorted_vals = try allocator.alloc(V, kvs_list.len);
            errdefer allocator.free(sorted_vals);
            const kvs = try allocator.create(KVs);
            errdefer allocator.destroy(kvs);

            self.initSortedKVs(kvs_list, sorted_keys, sorted_vals);
            kvs.* = .{
                .keys = sorted_keys.ptr,
                .values = sorted_vals.ptr,
                .len = @intCast(kvs_list.len),
            };
            self.kvs = kvs;

            const len_indexes = try allocator.alloc(u32, self.max_len + 1);
            self.initLenIndexes(len_indexes);
            self.len_indexes = len_indexes.ptr;
            self.len_indexes_len = @intCast(len_indexes.len);
            return self;
        }

        /// 此方法仅应配合 init() 使用,不应配合 initComptime() 使用。
        pub fn deinit(self: Self, allocator: mem.Allocator) void {
            allocator.free(self.len_indexes[0..self.len_indexes_len]);
            allocator.free(self.kvs.keys[0..self.kvs.len]);
            allocator.free(self.kvs.values[0..self.kvs.len]);
            allocator.destroy(self.kvs);
        }

        const SortContext = struct {
            keys: [][]const u8,
            vals: []V,

            pub fn lessThan(ctx: @This(), a: usize, b: usize) bool {
                return ctx.keys[a].len < ctx.keys[b].len;
            }

            pub fn swap(ctx: @This(), a: usize, b: usize) void {
                std.mem.swap([]const u8, &ctx.keys[a], &ctx.keys[b]);
                std.mem.swap(V, &ctx.vals[a], &ctx.vals[b]);
            }
        };

        fn initSortedKVs(
            self: *Self,
            kvs_list: anytype,
            sorted_keys: [][]const u8,
            sorted_vals: []V,
        ) void {
            for (kvs_list, 0..) |kv, i| {
                sorted_keys[i] = kv.@"0";
                sorted_vals[i] = if (V == void) {} else kv.@"1";
                self.min_len = @intCast(@min(self.min_len, kv.@"0".len));
                self.max_len = @intCast(@max(self.max_len, kv.@"0".len));
            }
            mem.sortUnstableContext(0, sorted_keys.len, SortContext{
                .keys = sorted_keys,
                .vals = sorted_vals,
            });
        }

        fn initLenIndexes(self: Self, len_indexes: []u32) void {
            var len: usize = 0;
            var i: u32 = 0;
            while (len <= self.max_len) : (len += 1) {
                // 查找首个满足 len == len 的关键字
                while (len > self.kvs.keys[i].len) {
                    i += 1;
                }
                len_indexes[len] = i;
            }
        }

        /// 检查映射中是否有指定键对应的值。
        pub fn has(self: Self, str: []const u8) bool {
            return self.get(str) != null;
        }

        /// 若存在则返回键对应的值,否则返回 null。
        pub fn get(self: Self, str: []const u8) ?V {
            if (self.kvs.len == 0)
                return null;

            return self.kvs.values[self.getIndex(str) orelse return null];
        }

        /// 返回 `str` 在生成的 `kvs` 中对应的索引;
        /// 若未找到 `str`,则返回 `null`。
        /// 返回的索引与输入 `kvs_list` 无关。
        pub fn getIndex(self: Self, str: []const u8) ?usize {
            const kvs = self.kvs.*;
            if (kvs.len == 0)
                return null;

            if (str.len < self.min_len or str.len > self.max_len)
                return null;

            var i = self.len_indexes[str.len];
            while (true) {
                const key = kvs.keys[i];
                if (key.len != str.len)
                    return null;
                if (eql(key, str))
                    return i;
                i += 1;
                if (i >= kvs.len)
                    return null;
            }
        }

        /// 返回键为 `str` 最长前缀的键值对,
        /// 否则返回 null。
        ///
        /// 该算法实际上为 O(N):从 `max_len` 到
        /// `min_len` 循环,并调用 `getIndex()` 检查
        /// 具有给定长度的所有键。
        pub fn getLongestPrefix(self: Self, str: []const u8) ?KV {
            if (self.kvs.len == 0)
                return null;
            const i = self.getLongestPrefixIndex(str) orelse return null;
            const kvs = self.kvs.*;
            return .{
                .key = kvs.keys[i],
                .value = kvs.values[i],
            };
        }

        /// 返回生成的 `kvs` 中某个键值对的索引,
        /// 其键为 `str` 的最长前缀;若未找到,则返回 `null`。
        /// 返回索引与输入
        /// `kvs_list` 无关。
        ///
        /// 此算法实际复杂度为 O(N),从 `max_len` 循环到
        /// `min_len`,调用 `getIndex()` 检查所有
        /// 指定长度的键。
        pub fn getLongestPrefixIndex(self: Self, str: []const u8) ?usize {
            if (self.kvs.len == 0)
                return null;

            if (str.len < self.min_len)
                return null;

            var len = @min(self.max_len, str.len);
            while (len >= self.min_len) : (len -= 1) {
                if (self.getIndex(str[0..len])) |i|
                    return i;
            }
            return null;
        }

        /// 返回生成的 `kvs` 中键的切片,其顺序
        /// 可能不同于输入的 `kvs_list`。
        pub fn keys(self: Self) []const []const u8 {
            const kvs = self.kvs.*;
            return kvs.keys[0..kvs.len];
        }

        /// 返回生成的 `kvs` 中值的切片,
        /// 其顺序可能与输入 `kvs_list` 不同。
        pub fn values(self: Self) []const V {
            const kvs = self.kvs.*;
            return kvs.values[0..kvs.len];
        }
    };
}

const TestEnum = enum { A, B, C, D, E };
const TestMap = StaticStringMap(TestEnum);
const TestKV = struct { []const u8, TestEnum };
const TestMapVoid = StaticStringMap(void);
const TestKVVoid = struct { []const u8 };
const TestMapWithEql = StaticStringMapWithEql(TestEnum, eqlAsciiIgnoreCase);
const testing = std.testing;
const test_alloc = testing.allocator;

test "list literal of list literals" {
    const slice: []const TestKV = &.{
        .{ "these", .D },
        .{ "have", .A },
        .{ "nothing", .B },
        .{ "incommon", .C },
        .{ "samelen", .E },
    };

    const map = TestMap.initComptime(slice);
    try testMap(map);
    // 默认比较区分大小写
    try testing.expect(null == map.get("NOTHING"));

    // 运行时 init()、deinit()
    const map_rt = try TestMap.init(slice, test_alloc);
    defer map_rt.deinit(test_alloc);
    try testMap(map_rt);
    // 默认比较区分大小写
    try testing.expect(null == map_rt.get("NOTHING"));
}

test "array of structs" {
    const slice = [_]TestKV{
        .{ "these", .D },
        .{ "have", .A },
        .{ "nothing", .B },
        .{ "incommon", .C },
        .{ "samelen", .E },
    };

    try testMap(TestMap.initComptime(slice));
}

test "slice of structs" {
    const slice = [_]TestKV{
        .{ "these", .D },
        .{ "have", .A },
        .{ "nothing", .B },
        .{ "incommon", .C },
        .{ "samelen", .E },
    };

    try testMap(TestMap.initComptime(slice));
}

fn testMap(map: anytype) !void {
    try testing.expectEqual(TestEnum.A, map.get("have").?);
    try testing.expectEqual(TestEnum.B, map.get("nothing").?);
    try testing.expect(null == map.get("missing"));
    try testing.expectEqual(TestEnum.D, map.get("these").?);
    try testing.expectEqual(TestEnum.E, map.get("samelen").?);

    try testing.expect(!map.has("missing"));
    try testing.expect(map.has("these"));

    try testing.expect(null == map.get(""));
    try testing.expect(null == map.get("averylongstringthathasnomatches"));
}

test "void value type, slice of structs" {
    const slice = [_]TestKVVoid{
        .{"these"},
        .{"have"},
        .{"nothing"},
        .{"incommon"},
        .{"samelen"},
    };
    const map = TestMapVoid.initComptime(slice);
    try testSet(map);
    // 默认比较区分大小写
    try testing.expect(null == map.get("NOTHING"));
}

test "void value type, list literal of list literals" {
    const slice = [_]TestKVVoid{
        .{"these"},
        .{"have"},
        .{"nothing"},
        .{"incommon"},
        .{"samelen"},
    };

    try testSet(TestMapVoid.initComptime(slice));
}

fn testSet(map: TestMapVoid) !void {
    try testing.expectEqual({}, map.get("have").?);
    try testing.expectEqual({}, map.get("nothing").?);
    try testing.expect(null == map.get("missing"));
    try testing.expectEqual({}, map.get("these").?);
    try testing.expectEqual({}, map.get("samelen").?);

    try testing.expect(!map.has("missing"));
    try testing.expect(map.has("these"));

    try testing.expect(null == map.get(""));
    try testing.expect(null == map.get("averylongstringthathasnomatches"));
}

fn testStaticStringMapWithEql(map: TestMapWithEql) !void {
    try testMap(map);
    try testing.expectEqual(TestEnum.A, map.get("HAVE").?);
    try testing.expectEqual(TestEnum.E, map.get("SameLen").?);
    try testing.expect(null == map.get("SameLength"));
    try testing.expect(map.has("ThESe"));
}

test "StaticStringMapWithEql" {
    const slice = [_]TestKV{
        .{ "these", .D },
        .{ "have", .A },
        .{ "nothing", .B },
        .{ "incommon", .C },
        .{ "samelen", .E },
    };

    try testStaticStringMapWithEql(TestMapWithEql.initComptime(slice));
}

test "empty" {
    const m1 = StaticStringMap(usize).initComptime(.{});
    try testing.expect(null == m1.get("anything"));

    const m2 = StaticStringMapWithEql(usize, eqlAsciiIgnoreCase).initComptime(.{});
    try testing.expect(null == m2.get("anything"));

    const m3 = try StaticStringMap(usize).init(.{}, test_alloc);
    try testing.expect(null == m3.get("anything"));

    const m4 = try StaticStringMapWithEql(usize, eqlAsciiIgnoreCase).init(.{}, test_alloc);
    try testing.expect(null == m4.get("anything"));
}

test "redundant entries" {
    const slice = [_]TestKV{
        .{ "redundant", .D },
        .{ "theNeedle", .A },
        .{ "redundant", .B },
        .{ "re" ++ "dundant", .C },
        .{ "redun" ++ "dant", .E },
    };
    const map = TestMap.initComptime(slice);

    // 不保证会得到哪一个:
    try testing.expect(null != map.get("redundant"));

    // 默认映射不区分大小写:
    try testing.expect(null == map.get("REDUNDANT"));

    try testing.expectEqual(TestEnum.A, map.get("theNeedle").?);
}

test "redundant insensitive" {
    const slice = [_]TestKV{
        .{ "redundant", .D },
        .{ "theNeedle", .A },
        .{ "redundanT", .B },
        .{ "RE" ++ "dundant", .C },
        .{ "redun" ++ "DANT", .E },
    };

    const map = TestMapWithEql.initComptime(slice);

    // 不保证会得到哪个结果……
    try testing.expect(null != map.get("REDUNDANT"));
    try testing.expect(null != map.get("ReDuNdAnT"));
    try testing.expectEqual(TestEnum.A, map.get("theNeedle").?);
}

test "comptime-only value" {
    const map = StaticStringMap(type).initComptime(.{
        .{ "a", struct {
            pub const foo = 1;
        } },
        .{ "b", struct {
            pub const foo = 2;
        } },
        .{ "c", struct {
            pub const foo = 3;
        } },
    });

    try testing.expect(map.get("a").?.foo == 1);
    try testing.expect(map.get("b").?.foo == 2);
    try testing.expect(map.get("c").?.foo == 3);
    try testing.expect(map.get("d") == null);
}

test "getIndex" {
    const slice = [_]TestKV{
        .{ "longer", .A },
        .{ "short", .B },
    };
    const map = TestMap.initComptime(slice);

    // 此索引可能不同于 `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 },
        .{ "aa", .B },
        .{ "aaa", .C },
        .{ "aaaa", .D },
    };

    const map = TestMap.initComptime(slice);

    try testing.expectEqual(null, map.getLongestPrefix(""));
    try testing.expectEqual(null, map.getLongestPrefix("bar"));
    try testing.expectEqualStrings("aaaa", map.getLongestPrefix("aaaabar").?.key);
    try testing.expectEqualStrings("aaa", map.getLongestPrefix("aaabar").?.key);
}

test "getLongestPrefix2" {
    const slice = [_]struct { []const u8, u8 }{
        .{ "one", 1 },
        .{ "two", 2 },
        .{ "three", 3 },
        .{ "four", 4 },
        .{ "five", 5 },
        .{ "six", 6 },
        .{ "seven", 7 },
        .{ "eight", 8 },
        .{ "nine", 9 },
    };
    const map = StaticStringMap(u8).initComptime(slice);

    try testing.expectEqual(1, map.get("one"));
    try testing.expectEqual(null, map.get("o"));
    try testing.expectEqual(null, map.get("onexxx"));
    try testing.expectEqual(9, map.get("nine"));
    try testing.expectEqual(null, map.get("n"));
    try testing.expectEqual(null, map.get("ninexxx"));
    try testing.expectEqual(null, map.get("xxx"));

    try testing.expectEqual(1, map.getLongestPrefix("one").?.value);
    try testing.expectEqual(1, map.getLongestPrefix("onexxx").?.value);
    try testing.expectEqual(null, map.getLongestPrefix("o"));
    try testing.expectEqual(null, map.getLongestPrefix("on"));
    try testing.expectEqual(9, map.getLongestPrefix("nine").?.value);
    try testing.expectEqual(9, map.getLongestPrefix("ninexxx").?.value);
    try testing.expectEqual(null, map.getLongestPrefix("n"));
    try testing.expectEqual(null, map.getLongestPrefix("xxx"));
}

test "sorting kvs doesn't exceed eval branch quota" {
    // 来源:https://github.com/ziglang/zig/issues/19803
    const TypeToByteSizeLUT = std.StaticStringMap(u32).initComptime(.{
        .{ "bool", 0 },
        .{ "c_int", 0 },
        .{ "c_long", 0 },
        .{ "c_longdouble", 0 },
        .{ "t20", 0 },
        .{ "t19", 0 },
        .{ "t18", 0 },
        .{ "t17", 0 },
        .{ "t16", 0 },
        .{ "t15", 0 },
        .{ "t14", 0 },
        .{ "t13", 0 },
        .{ "t12", 0 },
        .{ "t11", 0 },
        .{ "t10", 0 },
        .{ "t9", 0 },
        .{ "t8", 0 },
        .{ "t7", 0 },
        .{ "t6", 0 },
        .{ "t5", 0 },
        .{ "t4", 0 },
        .{ "t3", 0 },
        .{ "t2", 0 },
        .{ "t1", 1 },
    });
    try testing.expectEqual(1, TypeToByteSizeLUT.get("t1"));
}

test "initEnum" {
    const UnsortedEnum = enum { BB, A, CCC, DDD };
    const map = StaticStringMap(UnsortedEnum).initEnum();
    try testing.expect(map.has("A"));
    try testing.expect(!map.has("a"));
    try testing.expectEqual(.BB, map.get("BB"));
    try testing.expectEqual(.A, map.get("A"));
    try testing.expectEqual(.CCC, map.get("CCC"));
    try testing.expectEqual(.DDD, map.get("DDD"));
    try testing.expectEqual(null, map.getIndex("F"));
}