跳转到内容
标准库Zig 0.17.1官方原文
源码std/enums.zig

第 1 行

此模块包含处理枚举的实用工具和数据结构。

std.enums.A

常量

第 1513 行

std.enums.assert

别名

第 4 行

别名目标 std.debug.assert

std.enums.BoundedEnumMultiset

类型函数

第 679 行

枚举元素的多重集合,计数上限为 CountSize。 底层使用 EnumArray。此类型不进行动态分配, 可以按值复制。

pub fn BoundedEnumMultiset(comptime E: type, comptime CountSize: type) type

参数

E: type
CountSize: type

字段

counts: EnumArray(E, CountSize)

std.enums.BoundedEnumMultiset.add

函数

第 736 行

按给定数量增加键计数。

pub fn add(self: *Self, key: E, c: CountSize) error{Overflow}!void

参数

self: *Self
key: E
c: CountSize

错误

Overflow

std.enums.BoundedEnumMultiset.addAssertSafe

函数

第 731 行

将键计数增加给定数量。调用方断言 操作不会溢出。

pub fn addAssertSafe(self: *Self, key: E, c: CountSize) void

参数

self: *Self
key: E
c: CountSize

std.enums.BoundedEnumMultiset.addSet

函数

第 767 行

按照给定多重集合增加所有键的计数。

pub fn addSet(self: *Self, other: Self) error{Overflow}!void

参数

self: *Self
other: Self

错误

Overflow

std.enums.BoundedEnumMultiset.addSetAssertSafe

函数

第 759 行

按照给定多重集合增加所有键的计数。 调用方断言此操作不会使任何键的计数溢出。

pub fn addSetAssertSafe(self: *Self, other: Self) void

参数

self: *Self
other: Self

std.enums.BoundedEnumMultiset.contains

函数

第 719 行

检查多重集合中是否至少有一个键。

pub fn contains(self: Self, key: E) bool

参数

self: Self
key: E

std.enums.BoundedEnumMultiset.count

函数

第 710 行

返回多重集中所有键计数之和。

pub fn count(self: Self) usize

参数

self: Self

std.enums.BoundedEnumMultiset.empty

常量

第 699 行

计数为零的多重集合。

Self

std.enums.BoundedEnumMultiset.Entry

常量

第 848 行

std.enums.BoundedEnumMultiset.eql

函数

第 786 行

当且仅当所有键的计数均与 给定多重集合相同时,返回 true。

pub fn eql(self: Self, other: Self) bool

参数

self: Self
other: Self

std.enums.BoundedEnumMultiset.getCount

函数

第 748 行

返回某个键的计数。

pub fn getCount(self: Self, key: E) CountSize

参数

self: Self
key: E

std.enums.BoundedEnumMultiset.init

函数

第 686 行

使用包含计数的结构体初始化多重集合。

pub fn init(init_counts: EnumFieldStruct(E, CountSize, 0)) Self

参数

init_counts: EnumFieldStruct(E, CountSize, 0)

std.enums.BoundedEnumMultiset.initWithCount

函数

第 703 行

初始化多重集合, 将所有键设为相同计数。

pub fn initWithCount(comptime c: CountSize) Self

参数

c: CountSize

std.enums.BoundedEnumMultiset.iterator

函数

第 855 行

返回遍历此多重集的迭代器。计数为零的键 也会包含在内。迭代过程中对集合的修改, 可能被迭代器观察到,也可能不被观察到, 但不会使迭代器失效。

pub fn iterator(self: *Self) Iterator

参数

self: *Self

std.enums.BoundedEnumMultiset.Iterator

常量

第 849 行

std.enums.BoundedEnumMultiset.minus

函数

第 842 行

返回一个多重集合,其键计数等于此多重集合 对应键的计数减去另一个多重集合中 对应键的计数。若另一个多重集合的 键计数大于本集合,则该键的 计数为零。

pub fn minus(self: Self, other: Self) Self

参数

self: Self
other: Self

std.enums.BoundedEnumMultiset.plus

函数

第 831 行

返回一个多重集合,其键总数等于此多重集合与另一多重集合的键数之和。

pub fn plus(self: Self, other: Self) error{Overflow}!Self

参数

self: Self
other: Self

错误

Overflow

std.enums.BoundedEnumMultiset.plusAssertSafe

函数

第 823 行

返回一个多重集合,其键计数为此集合与另一集合的计数之和。调用方保证此操作不会使任何键计数溢出。

pub fn plusAssertSafe(self: Self, other: Self) Self

参数

self: Self
other: Self

std.enums.BoundedEnumMultiset.remove

函数

第 743 行

将键计数减少给定数量。若该数量 大于多重集中键的数量,则将键计数 设为零。

pub fn remove(self: *Self, key: E, c: CountSize) void

参数

self: *Self
key: E
c: CountSize

std.enums.BoundedEnumMultiset.removeAll

函数

第 725 行

从多重集合中移除某键的全部实例。 等价于 setCount(key, 0)。

pub fn removeAll(self: *Self, key: E) void

参数

self: *Self
key: E

std.enums.BoundedEnumMultiset.removeSet

函数

第 777 行

按给定多重集合减少所有键的计数。 若给定多重集合中某键的计数更多,则该键的计数归零。

pub fn removeSet(self: *Self, other: Self) void

参数

self: *Self
other: Self

std.enums.BoundedEnumMultiset.Self

别名

第 681 行

别名目标 std.enums.BoundedEnumMultiset

std.enums.BoundedEnumMultiset.setCount

函数

第 753 行

设置键的计数。

pub fn setCount(self: *Self, key: E, c: CountSize) void

参数

self: *Self
key: E
c: CountSize

std.enums.BoundedEnumMultiset.subsetOf

函数

第 798 行

当且仅当所有键计数均小于或 等于给定多重集的对应计数时返回 true。

pub fn subsetOf(self: Self, other: Self) bool

参数

self: Self
other: Self

std.enums.BoundedEnumMultiset.supersetOf

函数

第 810 行

当且仅当所有键的计数均大于或等于 给定多重集合中的对应计数时,返回 true。

pub fn supersetOf(self: Self, other: Self) bool

参数

self: Self
other: Self

std.enums.directEnumArray

函数

第 126 行

初始化 Data 数组,可使用 @intCast(usize, @intFromEnum(enum_value)) 索引。 若枚举为非穷尽枚举,结果数组只保证足以容纳所有显式字段。 若任意枚举字段的值无法由 usize 表示,则产生编译错误。 max_unused_slots 参数限制没有匹配枚举键的条目总数,即枚举编号中的空洞。例如,若枚举值为 1、2、5 和 6,则 max_unused_slots 必须至少为 3,以允许未使用的槽位 0、3 和 4。 init_values 参数必须是结构体,其字段名与枚举值匹配。 若枚举中有多个字段具有相同值,必须使用第一个字段的名称。

pub fn directEnumArray( comptime E: type, comptime Data: type, comptime max_unused_slots: comptime_int, init_values: EnumFieldStruct(E, Data, null), ) [directEnumArrayLen(E, max_unused_slots)]Data

参数

E: type
Data: type
max_unused_slots: comptime_int
init_values: EnumFieldStruct(E, Data, null)

用法示例

test directEnumArray {
    const E = enum(i4) { a = 4, b = 6, c = 2 };
    var runtime_false: bool = false;
    _ = &runtime_false;
    const array = directEnumArray(E, bool, 4, .{
        .a = true,
        .b = runtime_false,
        .c = true,
    });

    try testing.expectEqual([7]bool, @TypeOf(array));
    try testing.expectEqual(true, array[4]);
    try testing.expectEqual(false, array[6]);
    try testing.expectEqual(true, array[2]);
}

std.enums.directEnumArrayDefault

函数

第 161 行

初始化 Data 数组,使其可通过 @intCast(usize, @intFromEnum(enum_value)) 索引。枚举必须穷举。 若枚举包含值不能由 usize 表示的字段, 则产生编译错误。max_unused_slots 参数限制 不存在匹配枚举键的元素总数,即枚举 编号中的空洞。例如枚举值为 1、2、5、6 时,max_unused_slots 必须至少为 3,以容纳未使用的槽位 0、3、4。 init_values 参数必须为结构体,其字段名与枚举值匹配。 若枚举的多个字段具有相同值,必须使用第一个字段 的名称。

pub fn directEnumArrayDefault( comptime E: type, comptime Data: type, comptime default: ?Data, comptime max_unused_slots: comptime_int, init_values: EnumFieldStruct(E, Data, default), ) [directEnumArrayLen(E, max_unused_slots)]Data

参数

E: type
Data: type
default: ?Data
max_unused_slots: comptime_int
init_values: EnumFieldStruct(E, Data, default)

用法示例

test directEnumArrayDefault {
    const E = enum(i4) { a = 4, b = 6, c = 2 };
    var runtime_false: bool = false;
    _ = &runtime_false;
    const array = directEnumArrayDefault(E, bool, false, 4, .{
        .a = true,
        .b = runtime_false,
    });

    try testing.expectEqual([7]bool, @TypeOf(array));
    try testing.expectEqual(true, array[4]);
    try testing.expectEqual(false, array[6]);
    try testing.expectEqual(false, array[2]);
}

std.enums.directEnumArrayLen

函数

第 88 行

确定直接映射的枚举数组的长度,其索引为 @intCast(usize, @intFromEnum(enum_value))。 如果枚举非穷尽,则结果长度只足以 容纳所有显式字段。 如果枚举中存在值无法用 usize 表示的字段,则产生编译错误。max_unused_slots 参数限制 没有对应枚举键的元素总数,即枚举编号中的空洞数。 例如,若枚举的值为 1、2、5、6,则 max_unused_slots 至少须为 3,以允许未使用的槽位 0、3、4。

pub fn directEnumArrayLen(comptime E: type, comptime max_unused_slots: comptime_int) comptime_int

参数

E: type
max_unused_slots: comptime_int

std.enums.EnumArray

类型函数

第 1069 行

以枚举为索引、以稠密数组作为底层存储的数组。 若枚举不稠密,则构造从 枚举值到稠密索引的映射。此类型不进行动态 分配,可以按值复制。

pub fn EnumArray(comptime E: type, comptime V: type) type

参数

E: type
V: type

字段

values: [Indexer.count]Value

std.enums.EnumArray.Entry

容器

第 1138 行

数组中的条目。

字段

key: Key

与此条目关联的键。 修改此键不会改变数组。

value: *Value

指向数组中与此键关联的 值的指针。通过此 指针进行修改会改变底层数据。

std.enums.EnumArray.get

函数

第 1111 行

返回数组中与指定键关联的值。

pub fn get(self: Self, key: Key) Value

参数

self: Self
key: Key

std.enums.EnumArray.getPtr

函数

第 1116 行

返回指向数组中与某个键关联槽位的指针。

pub fn getPtr(self: *Self, key: Key) *Value

参数

self: *Self
key: Key

std.enums.EnumArray.getPtrConst

函数

第 1121 行

返回指向数组中与某个键关联槽位的常量指针。

pub fn getPtrConst(self: *const Self, key: Key) *const Value

参数

self: *const Self
key: Key

std.enums.EnumArray.Indexer

类型

第 1074 行

此映射的索引映射

std.enums.EnumArray.init

函数

第 1084 行

pub fn init(init_values: EnumFieldStruct(E, Value, null)) Self

参数

init_values: EnumFieldStruct(E, Value, null)

std.enums.EnumArray.initDefault

函数

第 1089 行

使用指定默认值初始化枚举数组中的值。

pub fn initDefault(comptime default: ?Value, init_values: EnumFieldStruct(E, Value, default)) Self

参数

default: ?Value
init_values: EnumFieldStruct(E, Value, default)

std.enums.EnumArray.initFill

函数

第 1104 行

pub fn initFill(v: Value) Self

参数

v: Value

std.enums.EnumArray.initUndefined

函数

第 1100 行

pub fn initUndefined() Self

std.enums.EnumArray.iterator

函数

第 1131 行

按索引顺序遍历数组中的元素。

pub fn iterator(self: *Self) Iterator

参数

self: *Self

std.enums.EnumArray.Iterator

容器

第 1149 行

字段

index: usize = 0
values: *[Indexer.count]Value

std.enums.EnumArray.Iterator.next

函数

第 1153 行

pub fn next(self: *Iterator) ?Entry

参数

self: *Iterator

std.enums.EnumArray.Key

常量

第 1076 行

用于索引此映射的键类型

std.enums.EnumArray.len

常量

第 1080 行

映射中可能存在的键的数量

std.enums.EnumArray.Self

别名

第 1071 行

别名目标 std.enums.EnumArray

std.enums.EnumArray.set

函数

第 1126 行

设置与某键关联槽位中的值。

pub fn set(self: *Self, key: Key, value: Value) void

参数

self: *Self
key: Key
value: Value

std.enums.EnumArray.Value

常量

第 1078 行

此映射中存储的值类型

std.enums.EnumFieldStruct

类型函数

第 33 行

返回一个结构体,其中为每个唯一命名的枚举成员包含对应字段。 如果枚举是 extern,且多个名称对应相同值,则仅使用 第一个名称。每个字段的类型为 Data,并使用提供的 默认值,该值可以是 undefined。

pub fn EnumFieldStruct(comptime E: type, comptime Data: type, comptime field_default: ?Data) type

参数

E: type
Data: type
field_default: ?Data

std.enums.EnumIndexer

类型函数

第 1277 行

pub fn EnumIndexer(comptime E: type) type

参数

E: type

std.enums.EnumIndexer.backing_int_sign

常量

第 1290 行

std.enums.EnumIndexer.count

常量

第 1295 行

comptime_int

std.enums.EnumIndexer.count

常量

第 1318 行

comptime_int

std.enums.EnumIndexer.count

常量

第 1343 行

comptime_int

std.enums.EnumIndexer.count

常量

第 1361 行

comptime_int

std.enums.EnumIndexer.indexOf

函数

第 1297 行

pub fn indexOf(e: E) usize

参数

e: E

std.enums.EnumIndexer.indexOf

函数

第 1319 行

pub fn indexOf(e: E) usize

参数

e: E

std.enums.EnumIndexer.indexOf

函数

第 1344 行

pub fn indexOf(e: E) usize

参数

e: E

std.enums.EnumIndexer.indexOf

函数

第 1362 行

pub fn indexOf(e: E) usize

参数

e: E

std.enums.EnumIndexer.Key

常量

第 1288 行

type

std.enums.EnumIndexer.Key

常量

第 1317 行

std.enums.EnumIndexer.Key

常量

第 1342 行

std.enums.EnumIndexer.Key

常量

第 1360 行

std.enums.EnumIndexer.keyForIndex

函数

第 1306 行

pub fn keyForIndex(i: usize) E

参数

i: usize

std.enums.EnumIndexer.keyForIndex

函数

第 1323 行

pub fn keyForIndex(i: usize) E

参数

i: usize

std.enums.EnumIndexer.keyForIndex

函数

第 1347 行

pub fn keyForIndex(i: usize) E

参数

i: usize

std.enums.EnumIndexer.keyForIndex

函数

第 1368 行

pub fn keyForIndex(i: usize) E

参数

i: usize

std.enums.EnumIndexer.lessThan

函数

第 1333 行

fn lessThan(_: void, a: comptime_int, b: comptime_int) bool

参数

_: void
a: comptime_int
b: comptime_int

std.enums.EnumIndexer.max_value

常量

第 1292 行

std.enums.EnumIndexer.min_value

常量

第 1291 行

std.enums.EnumIndexer.RangeType

常量

第 1294 行

std.enums.EnumMap

类型函数

第 425 行

以枚举为键、以位域和稠密数组作为底层存储的映射。 如果枚举穷尽但不稠密,将构造从 枚举值到稠密索引的映射。此类型不进行动态 分配,可以按值复制。

默认初始化已弃用;请改用 .empty。

pub fn EnumMap(comptime E: type, comptime V: type) type

参数

E: type
V: type

字段

bits: BitSet = .empty

用于确定元素是否位于映射中的位

values: [Indexer.count]Value = undefined

映射中各项的值。若关联 位为零,则该值未定义。

用法示例

test EnumMap {
    const Ball = enum { red, green, blue };

    const none: EnumMap(Ball, u8) = .empty;
    try testing.expectEqual(0, none.count());

    const some: EnumMap(Ball, u8) = .init(.{
        .green = 0xff,
        .blue = 0x80,
    });
    try testing.expectEqual(2, some.count());
    try testing.expectEqual(null, some.get(.red));
    try testing.expectEqual(0xff, some.get(.green));
    try testing.expectEqual(0x80, some.get(.blue));

    const all: EnumMap(Ball, u8) = .initFull(0);
    try testing.expectEqual(3, all.count());
}

std.enums.EnumMap.BitSet

类型

第 438 行

std.enums.EnumMap.contains

函数

第 514 行

检查映射是否包含某一项。

pub fn contains(self: *const Self, key: Key) bool

参数

self: *const Self
key: Key

std.enums.EnumMap.count

函数

第 509 行

映射中的条目数量。

pub fn count(self: *const Self) usize

参数

self: *const Self

std.enums.EnumMap.empty

常量

第 446 行

Self

std.enums.EnumMap.Entry

容器

第 622 行

映射中的条目。

字段

key: Key

与此条目关联的键。 修改此键不会改变映射。

value: *Value

指向映射中与此键关联的值的指针。通过该指针修改会更改底层数据。

std.enums.EnumMap.fetchPut

函数

第 585 行

设置映射中与键关联的值,并返回旧值。 若该键原不在映射中, 则返回 null。

pub fn fetchPut(self: *Self, key: Key, value: Value) ?Value

参数

self: *Self
key: Key
value: Value

std.enums.EnumMap.fetchRemove

函数

第 603 行

从映射中移除键,并返回旧值。 如果映射中没有该键,则返回 null。

pub fn fetchRemove(self: *Self, key: Key) ?Value

参数

self: *Self
key: Key

std.enums.EnumMap.get

函数

第 520 行

获取与某个键关联的值。 键不在映射中则返回 null。

pub fn get(self: *const Self, key: Key) ?Value

参数

self: *const Self
key: Key

std.enums.EnumMap.getAssertContains

函数

第 527 行

获取与键关联的值;该键必须已存在于映射中。

pub fn getAssertContains(self: *const Self, key: Key) Value

参数

self: *const Self
key: Key

std.enums.EnumMap.getPtr

函数

第 535 行

获取与某个键关联的值的地址。 键不在映射中则返回 null。

pub fn getPtr(self: *Self, key: Key) ?*Value

参数

self: *Self
key: Key

std.enums.EnumMap.getPtrAssertContains

函数

第 549 行

获取与某个键关联的值的地址。 键必须存在于映射中。

pub fn getPtrAssertContains(self: *Self, key: Key) *Value

参数

self: *Self
key: Key

std.enums.EnumMap.getPtrConst

函数

第 542 行

获取与某个键关联的常量值的地址。 键不在映射中则返回 null。

pub fn getPtrConst(self: *const Self, key: Key) ?*const Value

参数

self: *const Self
key: Key

std.enums.EnumMap.getPtrConstAssertContains

函数

第 557 行

获取与某个键关联的常量值的地址。 该键必须存在于映射中。

pub fn getPtrConstAssertContains(self: *const Self, key: Key) *const Value

参数

self: *const Self
key: Key

std.enums.EnumMap.Indexer

类型

第 430 行

此映射的索引映射

std.enums.EnumMap.init

函数

第 452 行

使用由可选值组成的稀疏结构体初始化映射

pub fn init(init_values: EnumFieldStruct(E, ?Value, @as(?Value, null))) Self

参数

init_values: EnumFieldStruct(E, ?Value, @as(?Value, null))

std.enums.EnumMap.initFull

函数

第 479 行

初始化包含所有键的完整映射,并将各值设为 value。 如果映射将始终保持完整,考虑改用 EnumArray。

pub fn initFull(value: Value) Self

参数

value: Value

std.enums.EnumMap.initFullWith

函数

第 488 行

使用提供的值初始化完整映射。 如果映射将始终保持完整,请考虑改用 EnumArray。

pub fn initFullWith(init_values: EnumFieldStruct(E, Value, null)) Self

参数

init_values: EnumFieldStruct(E, Value, null)

std.enums.EnumMap.initFullWithDefault

函数

第 494 行

使用所提供的默认值初始化完整映射。 若映射将始终保持完整,可考虑改用 EnumArray。

pub fn initFullWithDefault(comptime default: ?Value, init_values: EnumFieldStruct(E, Value, default)) Self

参数

default: ?Value
init_values: EnumFieldStruct(E, Value, default)

std.enums.EnumMap.iterator

函数

第 614 行

返回按索引顺序访问元素的映射迭代器。 对底层映射的修改可能被迭代器观察到, 也可能不会,但不会使迭代器失效。

pub fn iterator(self: *Self) Iterator

参数

self: *Self

std.enums.EnumMap.Iterator

容器

第 633 行

字段

inner: BitSet.Iterator(.{})
values: *[Indexer.count]Value

std.enums.EnumMap.Iterator.next

函数

第 637 行

pub fn next(self: *Iterator) ?Entry

参数

self: *Iterator

std.enums.EnumMap.Key

常量

第 432 行

用于索引此映射的键类型

std.enums.EnumMap.len

常量

第 436 行

映射中可能存在的键的数量

std.enums.EnumMap.put

函数

第 565 行

将键及给定值添加到映射。 如果映射中已存在该键,则覆盖其值。

pub fn put(self: *Self, key: Key, value: Value) void

参数

self: *Self
key: Key
value: Value

std.enums.EnumMap.putUninitialized

函数

第 575 行

将键加入映射,并令其值为未定义状态。 若键已存在于映射中,其值也会变为未定义状态。 返回指向该值的指针, 应使用此指针初始化该值。

pub fn putUninitialized(self: *Self, key: Key) *Value

参数

self: *Self
key: Key

std.enums.EnumMap.remove

函数

第 595 行

从映射中移除键。 如果键不在映射中,则不进行操作。

pub fn remove(self: *Self, key: Key) void

参数

self: *Self
key: Key

std.enums.EnumMap.Self

别名

第 427 行

别名目标 std.enums.EnumMap

std.enums.EnumMap.Value

常量

第 434 行

此映射中存储的值类型

std.enums.EnumMultiset

类型函数

第 672 行

枚举元素的多重集合,计数上限为 usize。 底层使用 EnumArray。此类型不进行动态分配, 可以按值复制。

pub fn EnumMultiset(comptime E: type) type

参数

E: type

字段

counts: EnumArray(E, CountSize)

用法示例

test EnumMultiset {
    const Ball = enum { red, green, blue };

    const empty = EnumMultiset(Ball).empty;
    const r0_g1_b2 = EnumMultiset(Ball).init(.{
        .red = 0,
        .green = 1,
        .blue = 2,
    });
    const ten_of_each = EnumMultiset(Ball).initWithCount(10);

    try testing.expectEqual(empty.count(), 0);
    try testing.expectEqual(r0_g1_b2.count(), 3);
    try testing.expectEqual(ten_of_each.count(), 30);

    try testing.expect(!empty.contains(.red));
    try testing.expect(!empty.contains(.green));
    try testing.expect(!empty.contains(.blue));

    try testing.expect(!r0_g1_b2.contains(.red));
    try testing.expect(r0_g1_b2.contains(.green));
    try testing.expect(r0_g1_b2.contains(.blue));

    try testing.expect(ten_of_each.contains(.red));
    try testing.expect(ten_of_each.contains(.green));
    try testing.expect(ten_of_each.contains(.blue));

    {
        var copy = ten_of_each;
        copy.removeAll(.red);
        try testing.expect(!copy.contains(.red));

        // 第二次调用 removeAll 不会执行任何操作
        copy.removeAll(.red);
        try testing.expect(!copy.contains(.red));
    }

    {
        var copy = ten_of_each;
        copy.addAssertSafe(.red, 6);
        try testing.expectEqual(copy.getCount(.red), 16);
    }

    {
        var copy = ten_of_each;
        try copy.add(.red, 6);
        try testing.expectEqual(copy.getCount(.red), 16);

        try testing.expectError(error.Overflow, copy.add(.red, std.math.maxInt(usize)));
    }

    {
        var copy = ten_of_each;
        copy.remove(.red, 4);
        try testing.expectEqual(copy.getCount(.red), 6);

        // 减去超过其内容的数量不会下溢
        copy.remove(.green, 14);
        try testing.expectEqual(copy.getCount(.green), 0);
    }

    try testing.expectEqual(empty.getCount(.green), 0);
    try testing.expectEqual(r0_g1_b2.getCount(.green), 1);
    try testing.expectEqual(ten_of_each.getCount(.green), 10);

    {
        var copy = empty;
        copy.setCount(.red, 6);
        try testing.expectEqual(copy.getCount(.red), 6);
    }

    {
        var copy = r0_g1_b2;
        copy.addSetAssertSafe(ten_of_each);
        try testing.expectEqual(copy.getCount(.red), 10);
        try testing.expectEqual(copy.getCount(.green), 11);
        try testing.expectEqual(copy.getCount(.blue), 12);
    }

    {
        var copy = r0_g1_b2;
        try copy.addSet(ten_of_each);
        try testing.expectEqual(copy.getCount(.red), 10);
        try testing.expectEqual(copy.getCount(.green), 11);
        try testing.expectEqual(copy.getCount(.blue), 12);

        const full = EnumMultiset(Ball).initWithCount(std.math.maxInt(usize));
        try testing.expectError(error.Overflow, copy.addSet(full));
    }

    {
        var copy = ten_of_each;
        copy.removeSet(r0_g1_b2);
        try testing.expectEqual(copy.getCount(.red), 10);
        try testing.expectEqual(copy.getCount(.green), 9);
        try testing.expectEqual(copy.getCount(.blue), 8);

        copy.removeSet(ten_of_each);
        try testing.expectEqual(copy.getCount(.red), 0);
        try testing.expectEqual(copy.getCount(.green), 0);
        try testing.expectEqual(copy.getCount(.blue), 0);
    }

    try testing.expect(empty.eql(empty));
    try testing.expect(r0_g1_b2.eql(r0_g1_b2));
    try testing.expect(ten_of_each.eql(ten_of_each));
    try testing.expect(!empty.eql(r0_g1_b2));
    try testing.expect(!r0_g1_b2.eql(ten_of_each));
    try testing.expect(!ten_of_each.eql(empty));

    try testing.expect(empty.subsetOf(empty));
    try testing.expect(r0_g1_b2.subsetOf(r0_g1_b2));
    try testing.expect(empty.subsetOf(r0_g1_b2));
    try testing.expect(r0_g1_b2.subsetOf(ten_of_each));
    try testing.expect(!ten_of_each.subsetOf(r0_g1_b2));
    try testing.expect(!r0_g1_b2.subsetOf(empty));

    try testing.expect(empty.supersetOf(empty));
    try testing.expect(r0_g1_b2.supersetOf(r0_g1_b2));
    try testing.expect(r0_g1_b2.supersetOf(empty));
    try testing.expect(ten_of_each.supersetOf(r0_g1_b2));
    try testing.expect(!r0_g1_b2.supersetOf(ten_of_each));
    try testing.expect(!empty.supersetOf(r0_g1_b2));

    {
        // 对于多重集合,可能存在两个集合
        // 互不为对方的子集,
        // 也互不为对方的超集。

        const r10 = EnumMultiset(Ball).init(.{
            .red = 10,
        });
        const b10 = EnumMultiset(Ball).init(.{
            .blue = 10,
        });

        try testing.expect(!r10.subsetOf(b10));
        try testing.expect(!b10.subsetOf(r10));
        try testing.expect(!r10.supersetOf(b10));
        try testing.expect(!b10.supersetOf(r10));
    }

    {
        const result = r0_g1_b2.plusAssertSafe(ten_of_each);
        try testing.expectEqual(result.getCount(.red), 10);
        try testing.expectEqual(result.getCount(.green), 11);
        try testing.expectEqual(result.getCount(.blue), 12);
    }

    {
        const result = try r0_g1_b2.plus(ten_of_each);
        try testing.expectEqual(result.getCount(.red), 10);
        try testing.expectEqual(result.getCount(.green), 11);
        try testing.expectEqual(result.getCount(.blue), 12);

        const full = EnumMultiset(Ball).initWithCount(std.math.maxInt(usize));
        try testing.expectError(error.Overflow, result.plus(full));
    }

    {
        const result = ten_of_each.minus(r0_g1_b2);
        try testing.expectEqual(result.getCount(.red), 10);
        try testing.expectEqual(result.getCount(.green), 9);
        try testing.expectEqual(result.getCount(.blue), 8);
    }

    {
        const result = ten_of_each.minus(r0_g1_b2).minus(ten_of_each);
        try testing.expectEqual(result.getCount(.red), 0);
        try testing.expectEqual(result.getCount(.green), 0);
        try testing.expectEqual(result.getCount(.blue), 0);
    }

    {
        var copy = empty;
        var it = copy.iterator();
        var entry = it.next().?;
        try testing.expectEqual(entry.key, .red);
        try testing.expectEqual(entry.value.*, 0);
        entry = it.next().?;
        try testing.expectEqual(entry.key, .green);
        try testing.expectEqual(entry.value.*, 0);
        entry = it.next().?;
        try testing.expectEqual(entry.key, .blue);
        try testing.expectEqual(entry.value.*, 0);
        try testing.expectEqual(it.next(), null);
    }

    {
        var copy = r0_g1_b2;
        var it = copy.iterator();
        var entry = it.next().?;
        try testing.expectEqual(entry.key, .red);
        try testing.expectEqual(entry.value.*, 0);
        entry = it.next().?;
        try testing.expectEqual(entry.key, .green);
        try testing.expectEqual(entry.value.*, 1);
        entry = it.next().?;
        try testing.expectEqual(entry.key, .blue);
        try testing.expectEqual(entry.value.*, 2);
        try testing.expectEqual(it.next(), null);
    }
}

std.enums.EnumSet

类型函数

第 241 行

以位域作为底层存储的一组枚举成员。若枚举 穷尽但不稠密,则会构造从枚举值到 稠密索引的映射。此类型不进行动态分配, 可以按值复制。

pub fn EnumSet(comptime E: type) type

参数

E: type

字段

bits: BitSet = .empty

std.enums.EnumSet.BitSet

类型

第 250 行

std.enums.EnumSet.complement

函数

第 370 行

返回一个集合,其中包含此集合中不存在的所有键。

pub fn complement(self: Self) Self

参数

self: Self

std.enums.EnumSet.contains

函数

第 305 行

检查键是否位于集合中。

pub fn contains(self: Self, key: Key) bool

参数

self: Self
key: Key

std.enums.EnumSet.count

函数

第 300 行

返回集合中的键数。

pub fn count(self: Self) usize

参数

self: Self

std.enums.EnumSet.differenceWith

函数

第 394 行

返回此集合与另一集合的差集。

pub fn differenceWith(self: Self, other: Self) Self

参数

self: Self
other: Self

std.enums.EnumSet.empty

常量

第 282 行

不包含键的集合。

Self

std.enums.EnumSet.eql

函数

第 351 行

当且仅当两个集合包含相同的键时,返回 true。

pub fn eql(self: Self, other: Self) bool

参数

self: Self
other: Self

std.enums.EnumSet.full

常量

第 285 行

包含所有可能键的集合。

Self

std.enums.EnumSet.Indexer

类型

第 246 行

键与索引相互转换时的索引规则。

std.enums.EnumSet.init

函数

第 258 行

使用布尔值结构体初始化集合

pub fn init(init_values: EnumFieldStruct(E, bool, false)) Self

参数

init_values: EnumFieldStruct(E, bool, false)

std.enums.EnumSet.initMany

函数

第 288 行

返回包含多个键的集合。

pub fn initMany(keys: []const Key) Self

参数

keys: []const Key

std.enums.EnumSet.initOne

函数

第 295 行

返回仅含一个键的集合。

pub fn initOne(key: Key) Self

参数

key: Key

std.enums.EnumSet.insert

函数

第 310 行

向集合中放入一个键。

pub fn insert(self: *Self, key: Key) void

参数

self: *Self
key: Key

std.enums.EnumSet.intersectWith

函数

第 382 行

返回包含同时存在于此集合和另一个集合中的 键的集合。

pub fn intersectWith(self: Self, other: Self) Self

参数

self: Self
other: Self

std.enums.EnumSet.iterator

函数

第 402 行

返回按索引顺序遍历此集合的 迭代器。迭代期间对集合的修改 可能被迭代器观察到,也可能不被观察到, 但不会使其失效。

pub fn iterator(self: *const Self) Iterator

参数

self: *const Self

std.enums.EnumSet.Iterator

容器

第 406 行

字段

inner: BitSet.Iterator(.{})

std.enums.EnumSet.Iterator.next

函数

第 409 行

pub fn next(self: *Iterator) ?Key

参数

self: *Iterator

std.enums.EnumSet.Key

常量

第 248 行

此集合的元素类型。

std.enums.EnumSet.len

常量

第 253 行

此集合中元素数量的上限。

std.enums.EnumSet.remove

函数

第 315 行

从集合中移除键。

pub fn remove(self: *Self, key: Key) void

参数

self: *Self
key: Key

std.enums.EnumSet.Self

别名

第 243 行

别名目标 std.enums.EnumSet

std.enums.EnumSet.setIntersection

函数

第 346 行

移除所有不在传入集合中的键。

pub fn setIntersection(self: *Self, other: Self) void

参数

self: *Self
other: Self

std.enums.EnumSet.setPresent

函数

第 320 行

根据传入布尔值,更改某键是否存在于集合中。

pub fn setPresent(self: *Self, key: Key, present: bool) void

参数

self: *Self
key: Key
present: bool

std.enums.EnumSet.setUnion

函数

第 341 行

将传入集合中的全部键添加到此集合。

pub fn setUnion(self: *Self, other: Self) void

参数

self: *Self
other: Self

std.enums.EnumSet.subsetOf

函数

第 358 行

当且仅当此集合中的全部键都在另一集合中时返回 true。 另一集合可以含有本集合没有的键。

pub fn subsetOf(self: Self, other: Self) bool

参数

self: Self
other: Self

std.enums.EnumSet.supersetOf

函数

第 365 行

当且仅当此集合包含另一集合中的全部键时返回 true。 此集合也可以具有另一集合中 不存在的键。

pub fn supersetOf(self: Self, other: Self) bool

参数

self: Self
other: Self

std.enums.EnumSet.toggle

函数

第 326 行

切换键在集合中的存在状态。 若集合已有该键则移除,否则添加。

pub fn toggle(self: *Self, key: Key) void

参数

self: *Self
key: Key

std.enums.EnumSet.toggleAll

函数

第 336 行

翻转集合中全部可能的键的状态。

pub fn toggleAll(self: *Self) void

参数

self: *Self

std.enums.EnumSet.toggleSet

函数

第 331 行

切换传入集合中所有键的存在状态。

pub fn toggleSet(self: *Self, other: Self) void

参数

self: *Self
other: Self

std.enums.EnumSet.unionWith

函数

第 376 行

返回此集合与另一集合的并集。

pub fn unionWith(self: Self, other: Self) Self

参数

self: Self
other: Self

std.enums.EnumSet.xorWith

函数

第 388 行

返回包含仅存在于此集合或另一集合中, 但不同时存在于两者中的键的集合。

pub fn xorWith(self: Self, other: Self) Self

参数

self: Self
other: Self

std.enums.eval_branch_quota_cushion

常量

第 8 行

新增会添加单个后向分支的 API 时,递增此值。

std.enums.fromInt

函数

第 10 行

pub fn fromInt(comptime E: type, integer: anytype) ?E

参数

E: type

用法示例

test fromInt {
    const E1 = enum {
        A,
    };
    const E2 = enum {
        A,
        B,
    };
    const E3 = enum(i8) { A, _ };
    const E4 = enum(u8) { A };

    var zero: u8 = 0;
    var one: u16 = 1;
    _ = &zero;
    _ = &one;
    try testing.expect(fromInt(E1, zero).? == E1.A);
    try testing.expect(fromInt(E2, one).? == E2.B);
    try testing.expect(fromInt(E3, zero).? == E3.A);
    try testing.expect(fromInt(E3, 127).? == @as(E3, @fromBackingInt(@intCast(127))));
    try testing.expect(fromInt(E3, -128).? == @as(E3, @fromBackingInt(@intCast(-128))));
    try testing.expectEqual(null, fromInt(E1, one));
    try testing.expectEqual(null, fromInt(E3, 128));
    try testing.expectEqual(null, fromInt(E3, -129));

    // 过去,若尝试转换一个未超出范围但不是有效值的整数,`fromInt` 会产生编译错误,而不是返回 `null`。
    //
    try testing.expectEqual(null, fromInt(E4, 1));
}

std.enums.std

别名

第 3 行

别名目标 std

std.enums.tagName

函数

第 63 行

适用于非穷尽枚举的 @tagName() 安全替代方案, 当 e 没有对应的标签值时不会 panic。 返回 e 的标签名;若不存在标签,则返回 null。

pub fn tagName(comptime E: type, e: E) ?[:0]const u8

参数

E: type
e: E

用法示例

test tagName {
    const E = enum(u8) { a, b, _ };
    try testing.expect(tagName(E, .a) != null);
    try testing.expectEqualStrings("a", tagName(E, .a).?);
    try testing.expect(tagName(E, @as(E, @fromBackingInt(@intCast(42)))) == null);
}

std.enums.testing

别名

第 5 行

别名目标 std.testing

std.enums.values

函数

第 56 行

按声明顺序,返回给定枚举中所有命名值的集合。

pub inline fn values(comptime E: type) []const E

参数

E: type

用法示例

test values {
    const E = enum {
        X,
        Y,
        Z,
        const A = 1;
    };
    try testing.expectEqualSlices(E, &.{ .X, .Y, .Z }, values(E));
}

std.enums.valuesFromFields

函数

第 42 行

在给定枚举类型中查找所提供的字段值。 结果数组的顺序与输入相同。

pub inline fn valuesFromFields(comptime E: type, comptime field_values: []const comptime_int) []const E

参数

E: type
field_values: []const comptime_int
源码

std/enums.zig

//! 此模块包含处理枚举的实用工具和数据结构。

const std = @import("std");
const assert = std.debug.assert;
const testing = std.testing;

/// 新增会添加单个后向分支的 API 时,递增此值。
const eval_branch_quota_cushion = 10;

pub fn fromInt(comptime E: type, integer: anytype) ?E {
    const enum_info = @typeInfo(E).@"enum";
    if (enum_info.mode == .nonexhaustive) {
        if (std.math.cast(enum_info.tag_type, integer)) |tag| {
            return @fromBackingInt(@intCast(tag));
        }
        return null;
    }
    // 我们不直接迭代 E 的字段,因为那
    // 需要内联循环。改为创建一个编译时已知的值
    // 数组;此数组可以在运行时迭代,
    // 而无需内联循环。
    // 这样会生成更好的机器码。
    for (values(E)) |value| {
        if (@backingInt(value) == integer) return value;
    }
    return null;
}

/// 返回一个结构体,其中为每个唯一命名的枚举成员包含对应字段。
/// 如果枚举是 extern,且多个名称对应相同值,则仅使用
/// 第一个名称。每个字段的类型为 Data,并使用提供的
/// 默认值,该值可以是 undefined。
pub fn EnumFieldStruct(comptime E: type, comptime Data: type, comptime field_default: ?Data) type {
    @setEvalBranchQuota(@typeInfo(E).@"enum".field_names.len + eval_branch_quota_cushion);
    const default_ptr: ?*const anyopaque = if (field_default) |d| @ptrCast(&d) else null;
    const field_names = @typeInfo(E).@"enum".field_names;
    return @Struct(.auto, null, field_names, &@splat(Data), &@splat(.{ .default_value_ptr = default_ptr }));
}

/// 在给定枚举类型中查找所提供的字段值。
/// 结果数组的顺序与输入相同。
pub inline fn valuesFromFields(comptime E: type, comptime field_values: []const comptime_int) []const E {
    comptime {
        @setEvalBranchQuota(@typeInfo(E).@"enum".field_names.len + eval_branch_quota_cushion);
        var result: [field_values.len]E = undefined;
        for (&result, field_values) |*r, f_value| {
            r.* = @fromBackingInt(@intCast(f_value));
        }
        const final = result;
        return &final;
    }
}

/// 按声明顺序,返回给定枚举中所有命名值的集合。
///
pub inline fn values(comptime E: type) []const E {
    return comptime valuesFromFields(E, @typeInfo(E).@"enum".field_values);
}

/// 适用于非穷尽枚举的 @tagName() 安全替代方案,
/// 当 `e` 没有对应的标签值时不会 panic。
/// 返回 `e` 的标签名;若不存在标签,则返回 null。
pub fn tagName(comptime E: type, e: E) ?[:0]const u8 {
    const field_names = @typeInfo(E).@"enum".field_names;
    const field_values = @typeInfo(E).@"enum".field_values;
    @setEvalBranchQuota(field_names.len);
    return inline for (field_names, field_values) |f_name, f_value| {
        if (@backingInt(e) == f_value) break f_name;
    } else null;
}

test tagName {
    const E = enum(u8) { a, b, _ };
    try testing.expect(tagName(E, .a) != null);
    try testing.expectEqualStrings("a", tagName(E, .a).?);
    try testing.expect(tagName(E, @as(E, @fromBackingInt(@intCast(42)))) == null);
}

/// 确定直接映射的枚举数组的长度,其索引为
/// @intCast(usize, @intFromEnum(enum_value))。
/// 如果枚举非穷尽,则结果长度只足以
/// 容纳所有显式字段。
/// 如果枚举中存在值无法用 usize
/// 表示的字段,则产生编译错误。max_unused_slots 参数限制
/// 没有对应枚举键的元素总数,即枚举编号中的空洞数。
/// 例如,若枚举的值为 1、2、5、6,则 max_unused_slots
/// 至少须为 3,以允许未使用的槽位 0、3、4。
pub fn directEnumArrayLen(comptime E: type, comptime max_unused_slots: comptime_int) comptime_int {
    var max_value: comptime_int = -1;
    const max_usize: comptime_int = ~@as(usize, 0);
    const info = @typeInfo(E).@"enum";
    for (info.field_names, info.field_values) |f_name, f_value| {
        if (f_value < 0) {
            @compileError("Cannot create a direct enum array for " ++ @typeName(E) ++ ", field ." ++ f_name ++ " has a negative value.");
        }
        if (f_value > max_value) {
            if (f_value > max_usize) {
                @compileError("Cannot create a direct enum array for " ++ @typeName(E) ++ ", field ." ++ f_name ++ " is larger than the max value of usize.");
            }
            max_value = f_value;
        }
    }

    const unused_slots = max_value + 1 - info.field_names.len;
    if (unused_slots > max_unused_slots) {
        const unused_str = std.fmt.comptimePrint("{d}", .{unused_slots});
        const allowed_str = std.fmt.comptimePrint("{d}", .{max_unused_slots});
        @compileError("Cannot create a direct enum array for " ++ @typeName(E) ++ ". It would have " ++ unused_str ++ " unused slots, but only " ++ allowed_str ++ " are allowed.");
    }

    return max_value + 1;
}

/// 初始化 Data 数组,可使用 @intCast(usize, @intFromEnum(enum_value)) 索引。
/// 若枚举为非穷尽枚举,结果数组只保证足以容纳所有显式字段。
/// 若任意枚举字段的值无法由 usize 表示,则产生编译错误。
/// max_unused_slots 参数限制没有匹配枚举键的条目总数,即枚举编号中的空洞。例如,若枚举值为 1、2、5 和 6,则 max_unused_slots 必须至少为 3,以允许未使用的槽位 0、3 和 4。
/// init_values 参数必须是结构体,其字段名与枚举值匹配。
/// 若枚举中有多个字段具有相同值,必须使用第一个字段的名称。
///
///
///
///
///
///
pub fn directEnumArray(
    comptime E: type,
    comptime Data: type,
    comptime max_unused_slots: comptime_int,
    init_values: EnumFieldStruct(E, Data, null),
) [directEnumArrayLen(E, max_unused_slots)]Data {
    return directEnumArrayDefault(E, Data, null, max_unused_slots, init_values);
}

test directEnumArray {
    const E = enum(i4) { a = 4, b = 6, c = 2 };
    var runtime_false: bool = false;
    _ = &runtime_false;
    const array = directEnumArray(E, bool, 4, .{
        .a = true,
        .b = runtime_false,
        .c = true,
    });

    try testing.expectEqual([7]bool, @TypeOf(array));
    try testing.expectEqual(true, array[4]);
    try testing.expectEqual(false, array[6]);
    try testing.expectEqual(true, array[2]);
}

/// 初始化 Data 数组,使其可通过
/// @intCast(usize, @intFromEnum(enum_value)) 索引。枚举必须穷举。
/// 若枚举包含值不能由 usize 表示的字段,
/// 则产生编译错误。max_unused_slots 参数限制
/// 不存在匹配枚举键的元素总数,即枚举
/// 编号中的空洞。例如枚举值为 1、2、5、6 时,max_unused_slots
/// 必须至少为 3,以容纳未使用的槽位 0、3、4。
/// init_values 参数必须为结构体,其字段名与枚举值匹配。
/// 若枚举的多个字段具有相同值,必须使用第一个字段
/// 的名称。
pub fn directEnumArrayDefault(
    comptime E: type,
    comptime Data: type,
    comptime default: ?Data,
    comptime max_unused_slots: comptime_int,
    init_values: EnumFieldStruct(E, Data, default),
) [directEnumArrayLen(E, max_unused_slots)]Data {
    const len = comptime directEnumArrayLen(E, max_unused_slots);
    var result: [len]Data = @splat(default orelse undefined);
    inline for (@typeInfo(@TypeOf(init_values)).@"struct".field_names) |f_name| {
        const enum_value = @field(E, f_name);
        const index = @as(usize, @intCast(@backingInt(enum_value)));
        result[index] = @field(init_values, f_name);
    }
    return result;
}

test directEnumArrayDefault {
    const E = enum(i4) { a = 4, b = 6, c = 2 };
    var runtime_false: bool = false;
    _ = &runtime_false;
    const array = directEnumArrayDefault(E, bool, false, 4, .{
        .a = true,
        .b = runtime_false,
    });

    try testing.expectEqual([7]bool, @TypeOf(array));
    try testing.expectEqual(true, array[4]);
    try testing.expectEqual(false, array[6]);
    try testing.expectEqual(false, array[2]);
}

test "directEnumArrayDefault slice" {
    const E = enum(i4) { a = 4, b = 6, c = 2 };
    var runtime_b = "b";
    _ = &runtime_b;
    const array = directEnumArrayDefault(E, []const u8, "default", 4, .{
        .a = "a",
        .b = runtime_b,
    });

    try testing.expectEqual([7][]const u8, @TypeOf(array));
    try testing.expectEqualSlices(u8, "a", array[4]);
    try testing.expectEqualSlices(u8, "b", array[6]);
    try testing.expectEqualSlices(u8, "default", array[2]);
}

test fromInt {
    const E1 = enum {
        A,
    };
    const E2 = enum {
        A,
        B,
    };
    const E3 = enum(i8) { A, _ };
    const E4 = enum(u8) { A };

    var zero: u8 = 0;
    var one: u16 = 1;
    _ = &zero;
    _ = &one;
    try testing.expect(fromInt(E1, zero).? == E1.A);
    try testing.expect(fromInt(E2, one).? == E2.B);
    try testing.expect(fromInt(E3, zero).? == E3.A);
    try testing.expect(fromInt(E3, 127).? == @as(E3, @fromBackingInt(@intCast(127))));
    try testing.expect(fromInt(E3, -128).? == @as(E3, @fromBackingInt(@intCast(-128))));
    try testing.expectEqual(null, fromInt(E1, one));
    try testing.expectEqual(null, fromInt(E3, 128));
    try testing.expectEqual(null, fromInt(E3, -129));

    // 过去,若尝试转换一个未超出范围但不是有效值的整数,`fromInt` 会产生编译错误,而不是返回 `null`。
    //
    try testing.expectEqual(null, fromInt(E4, 1));
}

/// 以位域作为底层存储的一组枚举成员。若枚举
/// 穷尽但不稠密,则会构造从枚举值到
/// 稠密索引的映射。此类型不进行动态分配,
/// 可以按值复制。
pub fn EnumSet(comptime E: type) type {
    return struct {
        const Self = @This();

        /// 键与索引相互转换时的索引规则。
        pub const Indexer = EnumIndexer(E);
        /// 此集合的元素类型。
        pub const Key = Indexer.Key;

        const BitSet = std.bit_set.Static(Indexer.count);

        /// 此集合中元素数量的上限。
        pub const len = Indexer.count;

        bits: BitSet = .empty,

        /// 使用布尔值结构体初始化集合
        pub fn init(init_values: EnumFieldStruct(E, bool, false)) Self {
            @setEvalBranchQuota(2 * @typeInfo(E).@"enum".field_names.len);
            var result: Self = .{};
            if (@typeInfo(E).@"enum".mode == .exhaustive) {
                inline for (0..Self.len) |i| {
                    const key = comptime Indexer.keyForIndex(i);
                    const tag = @tagName(key);
                    if (@field(init_values, tag)) {
                        result.bits.set(i);
                    }
                }
            } else {
                inline for (@typeInfo(E).@"enum".field_names) |field_name| {
                    const key = @field(E, field_name);
                    if (@field(init_values, field_name)) {
                        const i = comptime Indexer.indexOf(key);
                        result.bits.set(i);
                    }
                }
            }
            return result;
        }

        /// 不包含键的集合。
        pub const empty: Self = .{ .bits = .empty };

        /// 包含所有可能键的集合。
        pub const full: Self = .{ .bits = .full };

        /// 返回包含多个键的集合。
        pub fn initMany(keys: []const Key) Self {
            var set: Self = .empty;
            for (keys) |key| set.insert(key);
            return set;
        }

        /// 返回仅含一个键的集合。
        pub fn initOne(key: Key) Self {
            return initMany(&[_]Key{key});
        }

        /// 返回集合中的键数。
        pub fn count(self: Self) usize {
            return self.bits.count();
        }

        /// 检查键是否位于集合中。
        pub fn contains(self: Self, key: Key) bool {
            return self.bits.isSet(Indexer.indexOf(key));
        }

        /// 向集合中放入一个键。
        pub fn insert(self: *Self, key: Key) void {
            self.bits.set(Indexer.indexOf(key));
        }

        /// 从集合中移除键。
        pub fn remove(self: *Self, key: Key) void {
            self.bits.unset(Indexer.indexOf(key));
        }

        /// 根据传入布尔值,更改某键是否存在于集合中。
        pub fn setPresent(self: *Self, key: Key, present: bool) void {
            self.bits.setValue(Indexer.indexOf(key), present);
        }

        /// 切换键在集合中的存在状态。
        /// 若集合已有该键则移除,否则添加。
        pub fn toggle(self: *Self, key: Key) void {
            self.bits.toggle(Indexer.indexOf(key));
        }

        /// 切换传入集合中所有键的存在状态。
        pub fn toggleSet(self: *Self, other: Self) void {
            self.bits.toggleSet(other.bits);
        }

        /// 翻转集合中全部可能的键的状态。
        pub fn toggleAll(self: *Self) void {
            self.bits.toggleAll();
        }

        /// 将传入集合中的全部键添加到此集合。
        pub fn setUnion(self: *Self, other: Self) void {
            self.bits.setUnion(other.bits);
        }

        /// 移除所有不在传入集合中的键。
        pub fn setIntersection(self: *Self, other: Self) void {
            self.bits.setIntersection(other.bits);
        }

        /// 当且仅当两个集合包含相同的键时,返回 true。
        pub fn eql(self: Self, other: Self) bool {
            return self.bits.eql(other.bits);
        }

        /// 当且仅当此集合中的全部键都在另一集合中时返回 true。
        /// 另一集合可以含有本集合没有的键。
        ///
        pub fn subsetOf(self: Self, other: Self) bool {
            return self.bits.subsetOf(other.bits);
        }

        /// 当且仅当此集合包含另一集合中的全部键时返回 true。
        /// 此集合也可以具有另一集合中
        /// 不存在的键。
        pub fn supersetOf(self: Self, other: Self) bool {
            return self.bits.supersetOf(other.bits);
        }

        /// 返回一个集合,其中包含此集合中不存在的所有键。
        pub fn complement(self: Self) Self {
            return .{ .bits = self.bits.complement() };
        }

        /// 返回此集合与另一集合的并集。
        ///
        pub fn unionWith(self: Self, other: Self) Self {
            return .{ .bits = self.bits.unionWith(other.bits) };
        }

        /// 返回包含同时存在于此集合和另一个集合中的
        /// 键的集合。
        pub fn intersectWith(self: Self, other: Self) Self {
            return .{ .bits = self.bits.intersectWith(other.bits) };
        }

        /// 返回包含仅存在于此集合或另一集合中,
        /// 但不同时存在于两者中的键的集合。
        pub fn xorWith(self: Self, other: Self) Self {
            return .{ .bits = self.bits.xorWith(other.bits) };
        }

        /// 返回此集合与另一集合的差集。
        ///
        pub fn differenceWith(self: Self, other: Self) Self {
            return .{ .bits = self.bits.differenceWith(other.bits) };
        }

        /// 返回按索引顺序遍历此集合的
        /// 迭代器。迭代期间对集合的修改
        /// 可能被迭代器观察到,也可能不被观察到,
        /// 但不会使其失效。
        pub fn iterator(self: *const Self) Iterator {
            return .{ .inner = self.bits.iterator(.{}) };
        }

        pub const Iterator = struct {
            inner: BitSet.Iterator(.{}),

            pub fn next(self: *Iterator) ?Key {
                return if (self.inner.next()) |index|
                    Indexer.keyForIndex(index)
                else
                    null;
            }
        };
    };
}

/// 以枚举为键、以位域和稠密数组作为底层存储的映射。
/// 如果枚举穷尽但不稠密,将构造从
/// 枚举值到稠密索引的映射。此类型不进行动态
/// 分配,可以按值复制。
///
/// 默认初始化已弃用;请改用 .empty。
pub fn EnumMap(comptime E: type, comptime V: type) type {
    return struct {
        const Self = @This();

        /// 此映射的索引映射
        pub const Indexer = EnumIndexer(E);
        /// 用于索引此映射的键类型
        pub const Key = Indexer.Key;
        /// 此映射中存储的值类型
        pub const Value = V;
        /// 映射中可能存在的键的数量
        pub const len = Indexer.count;

        const BitSet = std.bit_set.Static(Indexer.count);

        /// 用于确定元素是否位于映射中的位
        bits: BitSet = .empty,
        /// 映射中各项的值。若关联
        /// 位为零,则该值未定义。
        values: [Indexer.count]Value = undefined,

        pub const empty: Self = .{
            .bits = .empty,
            .values = undefined,
        };

        /// 使用由可选值组成的稀疏结构体初始化映射
        pub fn init(init_values: EnumFieldStruct(E, ?Value, @as(?Value, null))) Self {
            @setEvalBranchQuota(2 * @typeInfo(E).@"enum".field_names.len);
            var result: Self = .{};
            if (@typeInfo(E).@"enum".mode == .exhaustive) {
                inline for (0..Self.len) |i| {
                    const key = comptime Indexer.keyForIndex(i);
                    const tag = @tagName(key);
                    if (@field(init_values, tag)) |*v| {
                        result.bits.set(i);
                        result.values[i] = v.*;
                    }
                }
            } else {
                inline for (@typeInfo(E).@"enum".field_names) |field_name| {
                    const key = @field(E, field_name);
                    if (@field(init_values, field_name)) |*v| {
                        const i = comptime Indexer.indexOf(key);
                        result.bits.set(i);
                        result.values[i] = v.*;
                    }
                }
            }
            return result;
        }

        /// 初始化包含所有键的完整映射,并将各值设为 value。
        /// 如果映射将始终保持完整,考虑改用 EnumArray。
        pub fn initFull(value: Value) Self {
            return .{
                .bits = .full,
                .values = @splat(value),
            };
        }

        /// 使用提供的值初始化完整映射。
        /// 如果映射将始终保持完整,请考虑改用 EnumArray。
        pub fn initFullWith(init_values: EnumFieldStruct(E, Value, null)) Self {
            return initFullWithDefault(null, init_values);
        }

        /// 使用所提供的默认值初始化完整映射。
        /// 若映射将始终保持完整,可考虑改用 EnumArray。
        pub fn initFullWithDefault(comptime default: ?Value, init_values: EnumFieldStruct(E, Value, default)) Self {
            @setEvalBranchQuota(2 * @typeInfo(E).@"enum".field_names.len);
            var result: Self = .{
                .bits = .full,
                .values = undefined,
            };
            inline for (0..Self.len) |i| {
                const key = comptime Indexer.keyForIndex(i);
                const tag = @tagName(key);
                result.values[i] = @field(init_values, tag);
            }
            return result;
        }

        /// 映射中的条目数量。
        pub fn count(self: *const Self) usize {
            return self.bits.count();
        }

        /// 检查映射是否包含某一项。
        pub fn contains(self: *const Self, key: Key) bool {
            return self.bits.isSet(Indexer.indexOf(key));
        }

        /// 获取与某个键关联的值。
        /// 键不在映射中则返回 null。
        pub fn get(self: *const Self, key: Key) ?Value {
            const index = Indexer.indexOf(key);
            return if (self.bits.isSet(index)) self.values[index] else null;
        }

        /// 获取与键关联的值;该键必须已存在于映射中。
        ///
        pub fn getAssertContains(self: *const Self, key: Key) Value {
            const index = Indexer.indexOf(key);
            assert(self.bits.isSet(index));
            return self.values[index];
        }

        /// 获取与某个键关联的值的地址。
        /// 键不在映射中则返回 null。
        pub fn getPtr(self: *Self, key: Key) ?*Value {
            const index = Indexer.indexOf(key);
            return if (self.bits.isSet(index)) &self.values[index] else null;
        }

        /// 获取与某个键关联的常量值的地址。
        /// 键不在映射中则返回 null。
        pub fn getPtrConst(self: *const Self, key: Key) ?*const Value {
            const index = Indexer.indexOf(key);
            return if (self.bits.isSet(index)) &self.values[index] else null;
        }

        /// 获取与某个键关联的值的地址。
        /// 键必须存在于映射中。
        pub fn getPtrAssertContains(self: *Self, key: Key) *Value {
            const index = Indexer.indexOf(key);
            assert(self.bits.isSet(index));
            return &self.values[index];
        }

        /// 获取与某个键关联的常量值的地址。
        /// 该键必须存在于映射中。
        pub fn getPtrConstAssertContains(self: *const Self, key: Key) *const Value {
            const index = Indexer.indexOf(key);
            assert(self.bits.isSet(index));
            return &self.values[index];
        }

        /// 将键及给定值添加到映射。
        /// 如果映射中已存在该键,则覆盖其值。
        pub fn put(self: *Self, key: Key, value: Value) void {
            const index = Indexer.indexOf(key);
            self.bits.set(index);
            self.values[index] = value;
        }

        /// 将键加入映射,并令其值为未定义状态。
        /// 若键已存在于映射中,其值也会变为未定义状态。
        /// 返回指向该值的指针,
        /// 应使用此指针初始化该值。
        pub fn putUninitialized(self: *Self, key: Key) *Value {
            const index = Indexer.indexOf(key);
            self.bits.set(index);
            self.values[index] = undefined;
            return &self.values[index];
        }

        /// 设置映射中与键关联的值,并返回旧值。
        /// 若该键原不在映射中,
        /// 则返回 null。
        pub fn fetchPut(self: *Self, key: Key, value: Value) ?Value {
            const index = Indexer.indexOf(key);
            const result: ?Value = if (self.bits.isSet(index)) self.values[index] else null;
            self.bits.set(index);
            self.values[index] = value;
            return result;
        }

        /// 从映射中移除键。
        /// 如果键不在映射中,则不进行操作。
        pub fn remove(self: *Self, key: Key) void {
            const index = Indexer.indexOf(key);
            self.bits.unset(index);
            self.values[index] = undefined;
        }

        /// 从映射中移除键,并返回旧值。
        /// 如果映射中没有该键,则返回 null。
        pub fn fetchRemove(self: *Self, key: Key) ?Value {
            const index = Indexer.indexOf(key);
            const result: ?Value = if (self.bits.isSet(index)) self.values[index] else null;
            self.bits.unset(index);
            self.values[index] = undefined;
            return result;
        }

        /// 返回按索引顺序访问元素的映射迭代器。
        /// 对底层映射的修改可能被迭代器观察到,
        /// 也可能不会,但不会使迭代器失效。
        pub fn iterator(self: *Self) Iterator {
            return .{
                .inner = self.bits.iterator(.{}),
                .values = &self.values,
            };
        }

        /// 映射中的条目。
        pub const Entry = struct {
            /// 与此条目关联的键。
            /// 修改此键不会改变映射。
            key: Key,

            /// 指向映射中与此键关联的值的指针。通过该指针修改会更改底层数据。
            ///
            ///
            value: *Value,
        };

        pub const Iterator = struct {
            inner: BitSet.Iterator(.{}),
            values: *[Indexer.count]Value,

            pub fn next(self: *Iterator) ?Entry {
                return if (self.inner.next()) |index|
                    Entry{
                        .key = Indexer.keyForIndex(index),
                        .value = &self.values[index],
                    }
                else
                    null;
            }
        };
    };
}

test EnumMap {
    const Ball = enum { red, green, blue };

    const none: EnumMap(Ball, u8) = .empty;
    try testing.expectEqual(0, none.count());

    const some: EnumMap(Ball, u8) = .init(.{
        .green = 0xff,
        .blue = 0x80,
    });
    try testing.expectEqual(2, some.count());
    try testing.expectEqual(null, some.get(.red));
    try testing.expectEqual(0xff, some.get(.green));
    try testing.expectEqual(0x80, some.get(.blue));

    const all: EnumMap(Ball, u8) = .initFull(0);
    try testing.expectEqual(3, all.count());
}

/// 枚举元素的多重集合,计数上限为 usize。
/// 底层使用 EnumArray。此类型不进行动态分配,
/// 可以按值复制。
pub fn EnumMultiset(comptime E: type) type {
    return BoundedEnumMultiset(E, usize);
}

/// 枚举元素的多重集合,计数上限为 CountSize。
/// 底层使用 EnumArray。此类型不进行动态分配,
/// 可以按值复制。
pub fn BoundedEnumMultiset(comptime E: type, comptime CountSize: type) type {
    return struct {
        const Self = @This();

        counts: EnumArray(E, CountSize),

        /// 使用包含计数的结构体初始化多重集合。
        pub fn init(init_counts: EnumFieldStruct(E, CountSize, 0)) Self {
            @setEvalBranchQuota(2 * @typeInfo(E).@"enum".field_names.len);
            var self = initWithCount(0);
            const info = @typeInfo(E).@"enum";
            inline for (info.field_names, info.field_values) |field_name, field_value| {
                const c = @field(init_counts, field_name);
                const key: E = @fromBackingInt(@intCast(field_value));
                self.counts.set(key, c);
            }
            return self;
        }

        /// 计数为零的多重集合。
        pub const empty: Self = .initWithCount(0);

        /// 初始化多重集合,
        /// 将所有键设为相同计数。
        pub fn initWithCount(comptime c: CountSize) Self {
            return .{
                .counts = .initDefault(c, .{}),
            };
        }

        /// 返回多重集中所有键计数之和。
        pub fn count(self: Self) usize {
            var sum: usize = 0;
            for (self.counts.values) |c| {
                sum += c;
            }
            return sum;
        }

        /// 检查多重集合中是否至少有一个键。
        pub fn contains(self: Self, key: E) bool {
            return self.counts.get(key) > 0;
        }

        /// 从多重集合中移除某键的全部实例。
        /// 等价于 setCount(key, 0)。
        pub fn removeAll(self: *Self, key: E) void {
            return self.counts.set(key, 0);
        }

        /// 将键计数增加给定数量。调用方断言
        /// 操作不会溢出。
        pub fn addAssertSafe(self: *Self, key: E, c: CountSize) void {
            self.counts.getPtr(key).* += c;
        }

        /// 按给定数量增加键计数。
        pub fn add(self: *Self, key: E, c: CountSize) error{Overflow}!void {
            self.counts.set(key, try std.math.add(CountSize, self.counts.get(key), c));
        }

        /// 将键计数减少给定数量。若该数量
        /// 大于多重集中键的数量,则将键计数
        /// 设为零。
        pub fn remove(self: *Self, key: E, c: CountSize) void {
            self.counts.getPtr(key).* -= @min(self.getCount(key), c);
        }

        /// 返回某个键的计数。
        pub fn getCount(self: Self, key: E) CountSize {
            return self.counts.get(key);
        }

        /// 设置键的计数。
        pub fn setCount(self: *Self, key: E, c: CountSize) void {
            self.counts.set(key, c);
        }

        /// 按照给定多重集合增加所有键的计数。
        /// 调用方断言此操作不会使任何键的计数溢出。
        pub fn addSetAssertSafe(self: *Self, other: Self) void {
            inline for (@typeInfo(E).@"enum".field_values) |field_value| {
                const key = @as(E, @fromBackingInt(@intCast(field_value)));
                self.addAssertSafe(key, other.getCount(key));
            }
        }

        /// 按照给定多重集合增加所有键的计数。
        pub fn addSet(self: *Self, other: Self) error{Overflow}!void {
            inline for (@typeInfo(E).@"enum".field_values) |field_value| {
                const key = @as(E, @fromBackingInt(@intCast(field_value)));
                try self.add(key, other.getCount(key));
            }
        }

        /// 按给定多重集合减少所有键的计数。
        /// 若给定多重集合中某键的计数更多,则该键的计数归零。
        ///
        pub fn removeSet(self: *Self, other: Self) void {
            inline for (@typeInfo(E).@"enum".field_values) |field_value| {
                const key = @as(E, @fromBackingInt(@intCast(field_value)));
                self.remove(key, other.getCount(key));
            }
        }

        /// 当且仅当所有键的计数均与
        /// 给定多重集合相同时,返回 true。
        pub fn eql(self: Self, other: Self) bool {
            inline for (@typeInfo(E).@"enum".field_values) |field_value| {
                const key = @as(E, @fromBackingInt(@intCast(field_value)));
                if (self.getCount(key) != other.getCount(key)) {
                    return false;
                }
            }
            return true;
        }

        /// 当且仅当所有键计数均小于或
        /// 等于给定多重集的对应计数时返回 true。
        pub fn subsetOf(self: Self, other: Self) bool {
            inline for (@typeInfo(E).@"enum".field_values) |field_value| {
                const key = @as(E, @fromBackingInt(@intCast(field_value)));
                if (self.getCount(key) > other.getCount(key)) {
                    return false;
                }
            }
            return true;
        }

        /// 当且仅当所有键的计数均大于或等于
        /// 给定多重集合中的对应计数时,返回 true。
        pub fn supersetOf(self: Self, other: Self) bool {
            inline for (@typeInfo(E).@"enum".field_values) |field_value| {
                const key = @as(E, @fromBackingInt(@intCast(field_value)));
                if (self.getCount(key) < other.getCount(key)) {
                    return false;
                }
            }
            return true;
        }

        /// 返回一个多重集合,其键计数为此集合与另一集合的计数之和。调用方保证此操作不会使任何键计数溢出。
        ///
        ///
        pub fn plusAssertSafe(self: Self, other: Self) Self {
            var result = self;
            result.addSetAssertSafe(other);
            return result;
        }

        /// 返回一个多重集合,其键总数等于此多重集合与另一多重集合的键数之和。
        ///
        pub fn plus(self: Self, other: Self) error{Overflow}!Self {
            var result = self;
            try result.addSet(other);
            return result;
        }

        /// 返回一个多重集合,其键计数等于此多重集合
        /// 对应键的计数减去另一个多重集合中
        /// 对应键的计数。若另一个多重集合的
        /// 键计数大于本集合,则该键的
        /// 计数为零。
        pub fn minus(self: Self, other: Self) Self {
            var result = self;
            result.removeSet(other);
            return result;
        }

        pub const Entry = EnumArray(E, CountSize).Entry;
        pub const Iterator = EnumArray(E, CountSize).Iterator;

        /// 返回遍历此多重集的迭代器。计数为零的键
        /// 也会包含在内。迭代过程中对集合的修改,
        /// 可能被迭代器观察到,也可能不被观察到,
        /// 但不会使迭代器失效。
        pub fn iterator(self: *Self) Iterator {
            return self.counts.iterator();
        }
    };
}

test EnumMultiset {
    const Ball = enum { red, green, blue };

    const empty = EnumMultiset(Ball).empty;
    const r0_g1_b2 = EnumMultiset(Ball).init(.{
        .red = 0,
        .green = 1,
        .blue = 2,
    });
    const ten_of_each = EnumMultiset(Ball).initWithCount(10);

    try testing.expectEqual(empty.count(), 0);
    try testing.expectEqual(r0_g1_b2.count(), 3);
    try testing.expectEqual(ten_of_each.count(), 30);

    try testing.expect(!empty.contains(.red));
    try testing.expect(!empty.contains(.green));
    try testing.expect(!empty.contains(.blue));

    try testing.expect(!r0_g1_b2.contains(.red));
    try testing.expect(r0_g1_b2.contains(.green));
    try testing.expect(r0_g1_b2.contains(.blue));

    try testing.expect(ten_of_each.contains(.red));
    try testing.expect(ten_of_each.contains(.green));
    try testing.expect(ten_of_each.contains(.blue));

    {
        var copy = ten_of_each;
        copy.removeAll(.red);
        try testing.expect(!copy.contains(.red));

        // 第二次调用 removeAll 不会执行任何操作
        copy.removeAll(.red);
        try testing.expect(!copy.contains(.red));
    }

    {
        var copy = ten_of_each;
        copy.addAssertSafe(.red, 6);
        try testing.expectEqual(copy.getCount(.red), 16);
    }

    {
        var copy = ten_of_each;
        try copy.add(.red, 6);
        try testing.expectEqual(copy.getCount(.red), 16);

        try testing.expectError(error.Overflow, copy.add(.red, std.math.maxInt(usize)));
    }

    {
        var copy = ten_of_each;
        copy.remove(.red, 4);
        try testing.expectEqual(copy.getCount(.red), 6);

        // 减去超过其内容的数量不会下溢
        copy.remove(.green, 14);
        try testing.expectEqual(copy.getCount(.green), 0);
    }

    try testing.expectEqual(empty.getCount(.green), 0);
    try testing.expectEqual(r0_g1_b2.getCount(.green), 1);
    try testing.expectEqual(ten_of_each.getCount(.green), 10);

    {
        var copy = empty;
        copy.setCount(.red, 6);
        try testing.expectEqual(copy.getCount(.red), 6);
    }

    {
        var copy = r0_g1_b2;
        copy.addSetAssertSafe(ten_of_each);
        try testing.expectEqual(copy.getCount(.red), 10);
        try testing.expectEqual(copy.getCount(.green), 11);
        try testing.expectEqual(copy.getCount(.blue), 12);
    }

    {
        var copy = r0_g1_b2;
        try copy.addSet(ten_of_each);
        try testing.expectEqual(copy.getCount(.red), 10);
        try testing.expectEqual(copy.getCount(.green), 11);
        try testing.expectEqual(copy.getCount(.blue), 12);

        const full = EnumMultiset(Ball).initWithCount(std.math.maxInt(usize));
        try testing.expectError(error.Overflow, copy.addSet(full));
    }

    {
        var copy = ten_of_each;
        copy.removeSet(r0_g1_b2);
        try testing.expectEqual(copy.getCount(.red), 10);
        try testing.expectEqual(copy.getCount(.green), 9);
        try testing.expectEqual(copy.getCount(.blue), 8);

        copy.removeSet(ten_of_each);
        try testing.expectEqual(copy.getCount(.red), 0);
        try testing.expectEqual(copy.getCount(.green), 0);
        try testing.expectEqual(copy.getCount(.blue), 0);
    }

    try testing.expect(empty.eql(empty));
    try testing.expect(r0_g1_b2.eql(r0_g1_b2));
    try testing.expect(ten_of_each.eql(ten_of_each));
    try testing.expect(!empty.eql(r0_g1_b2));
    try testing.expect(!r0_g1_b2.eql(ten_of_each));
    try testing.expect(!ten_of_each.eql(empty));

    try testing.expect(empty.subsetOf(empty));
    try testing.expect(r0_g1_b2.subsetOf(r0_g1_b2));
    try testing.expect(empty.subsetOf(r0_g1_b2));
    try testing.expect(r0_g1_b2.subsetOf(ten_of_each));
    try testing.expect(!ten_of_each.subsetOf(r0_g1_b2));
    try testing.expect(!r0_g1_b2.subsetOf(empty));

    try testing.expect(empty.supersetOf(empty));
    try testing.expect(r0_g1_b2.supersetOf(r0_g1_b2));
    try testing.expect(r0_g1_b2.supersetOf(empty));
    try testing.expect(ten_of_each.supersetOf(r0_g1_b2));
    try testing.expect(!r0_g1_b2.supersetOf(ten_of_each));
    try testing.expect(!empty.supersetOf(r0_g1_b2));

    {
        // 对于多重集合,可能存在两个集合
        // 互不为对方的子集,
        // 也互不为对方的超集。

        const r10 = EnumMultiset(Ball).init(.{
            .red = 10,
        });
        const b10 = EnumMultiset(Ball).init(.{
            .blue = 10,
        });

        try testing.expect(!r10.subsetOf(b10));
        try testing.expect(!b10.subsetOf(r10));
        try testing.expect(!r10.supersetOf(b10));
        try testing.expect(!b10.supersetOf(r10));
    }

    {
        const result = r0_g1_b2.plusAssertSafe(ten_of_each);
        try testing.expectEqual(result.getCount(.red), 10);
        try testing.expectEqual(result.getCount(.green), 11);
        try testing.expectEqual(result.getCount(.blue), 12);
    }

    {
        const result = try r0_g1_b2.plus(ten_of_each);
        try testing.expectEqual(result.getCount(.red), 10);
        try testing.expectEqual(result.getCount(.green), 11);
        try testing.expectEqual(result.getCount(.blue), 12);

        const full = EnumMultiset(Ball).initWithCount(std.math.maxInt(usize));
        try testing.expectError(error.Overflow, result.plus(full));
    }

    {
        const result = ten_of_each.minus(r0_g1_b2);
        try testing.expectEqual(result.getCount(.red), 10);
        try testing.expectEqual(result.getCount(.green), 9);
        try testing.expectEqual(result.getCount(.blue), 8);
    }

    {
        const result = ten_of_each.minus(r0_g1_b2).minus(ten_of_each);
        try testing.expectEqual(result.getCount(.red), 0);
        try testing.expectEqual(result.getCount(.green), 0);
        try testing.expectEqual(result.getCount(.blue), 0);
    }

    {
        var copy = empty;
        var it = copy.iterator();
        var entry = it.next().?;
        try testing.expectEqual(entry.key, .red);
        try testing.expectEqual(entry.value.*, 0);
        entry = it.next().?;
        try testing.expectEqual(entry.key, .green);
        try testing.expectEqual(entry.value.*, 0);
        entry = it.next().?;
        try testing.expectEqual(entry.key, .blue);
        try testing.expectEqual(entry.value.*, 0);
        try testing.expectEqual(it.next(), null);
    }

    {
        var copy = r0_g1_b2;
        var it = copy.iterator();
        var entry = it.next().?;
        try testing.expectEqual(entry.key, .red);
        try testing.expectEqual(entry.value.*, 0);
        entry = it.next().?;
        try testing.expectEqual(entry.key, .green);
        try testing.expectEqual(entry.value.*, 1);
        entry = it.next().?;
        try testing.expectEqual(entry.key, .blue);
        try testing.expectEqual(entry.value.*, 2);
        try testing.expectEqual(it.next(), null);
    }
}

/// 以枚举为索引、以稠密数组作为底层存储的数组。
/// 若枚举不稠密,则构造从
/// 枚举值到稠密索引的映射。此类型不进行动态
/// 分配,可以按值复制。
pub fn EnumArray(comptime E: type, comptime V: type) type {
    return struct {
        const Self = @This();

        /// 此映射的索引映射
        pub const Indexer = EnumIndexer(E);
        /// 用于索引此映射的键类型
        pub const Key = Indexer.Key;
        /// 此映射中存储的值类型
        pub const Value = V;
        /// 映射中可能存在的键的数量
        pub const len = Indexer.count;

        values: [Indexer.count]Value,

        pub fn init(init_values: EnumFieldStruct(E, Value, null)) Self {
            return initDefault(null, init_values);
        }

        /// 使用指定默认值初始化枚举数组中的值。
        pub fn initDefault(comptime default: ?Value, init_values: EnumFieldStruct(E, Value, default)) Self {
            @setEvalBranchQuota(2 * @typeInfo(E).@"enum".field_names.len);
            var result: Self = .{ .values = undefined };
            inline for (0..Self.len) |i| {
                const key = comptime Indexer.keyForIndex(i);
                const tag = @tagName(key);
                result.values[i] = @field(init_values, tag);
            }
            return result;
        }

        pub fn initUndefined() Self {
            return Self{ .values = undefined };
        }

        pub fn initFill(v: Value) Self {
            var self: Self = undefined;
            @memset(&self.values, v);
            return self;
        }

        /// 返回数组中与指定键关联的值。
        pub fn get(self: Self, key: Key) Value {
            return self.values[Indexer.indexOf(key)];
        }

        /// 返回指向数组中与某个键关联槽位的指针。
        pub fn getPtr(self: *Self, key: Key) *Value {
            return &self.values[Indexer.indexOf(key)];
        }

        /// 返回指向数组中与某个键关联槽位的常量指针。
        pub fn getPtrConst(self: *const Self, key: Key) *const Value {
            return &self.values[Indexer.indexOf(key)];
        }

        /// 设置与某键关联槽位中的值。
        pub fn set(self: *Self, key: Key, value: Value) void {
            self.values[Indexer.indexOf(key)] = value;
        }

        /// 按索引顺序遍历数组中的元素。
        pub fn iterator(self: *Self) Iterator {
            return .{
                .values = &self.values,
            };
        }

        /// 数组中的条目。
        pub const Entry = struct {
            /// 与此条目关联的键。
            /// 修改此键不会改变数组。
            key: Key,

            /// 指向数组中与此键关联的
            /// 值的指针。通过此
            /// 指针进行修改会改变底层数据。
            value: *Value,
        };

        pub const Iterator = struct {
            index: usize = 0,
            values: *[Indexer.count]Value,

            pub fn next(self: *Iterator) ?Entry {
                const index = self.index;
                if (index < Indexer.count) {
                    self.index += 1;
                    return Entry{
                        .key = Indexer.keyForIndex(index),
                        .value = &self.values[index],
                    };
                }
                return null;
            }
        };
    };
}

test "pure EnumSet fns" {
    const Suit = enum { spades, hearts, clubs, diamonds };

    const empty = EnumSet(Suit).empty;
    const full = EnumSet(Suit).full;
    const black = EnumSet(Suit).initMany(&[_]Suit{ .spades, .clubs });
    const red = EnumSet(Suit).initMany(&[_]Suit{ .hearts, .diamonds });

    try testing.expect(empty.eql(empty));
    try testing.expect(full.eql(full));
    try testing.expect(!empty.eql(full));
    try testing.expect(!full.eql(empty));
    try testing.expect(!empty.eql(black));
    try testing.expect(!full.eql(red));
    try testing.expect(!red.eql(empty));
    try testing.expect(!black.eql(full));

    try testing.expect(empty.subsetOf(empty));
    try testing.expect(empty.subsetOf(full));
    try testing.expect(full.subsetOf(full));
    try testing.expect(!black.subsetOf(red));
    try testing.expect(!red.subsetOf(black));

    try testing.expect(full.supersetOf(full));
    try testing.expect(full.supersetOf(empty));
    try testing.expect(empty.supersetOf(empty));
    try testing.expect(!black.supersetOf(red));
    try testing.expect(!red.supersetOf(black));

    try testing.expect(empty.complement().eql(full));
    try testing.expect(full.complement().eql(empty));
    try testing.expect(black.complement().eql(red));
    try testing.expect(red.complement().eql(black));

    try testing.expect(empty.unionWith(empty).eql(empty));
    try testing.expect(empty.unionWith(full).eql(full));
    try testing.expect(full.unionWith(full).eql(full));
    try testing.expect(full.unionWith(empty).eql(full));
    try testing.expect(black.unionWith(red).eql(full));
    try testing.expect(red.unionWith(black).eql(full));

    try testing.expect(empty.intersectWith(empty).eql(empty));
    try testing.expect(empty.intersectWith(full).eql(empty));
    try testing.expect(full.intersectWith(full).eql(full));
    try testing.expect(full.intersectWith(empty).eql(empty));
    try testing.expect(black.intersectWith(red).eql(empty));
    try testing.expect(red.intersectWith(black).eql(empty));

    try testing.expect(empty.xorWith(empty).eql(empty));
    try testing.expect(empty.xorWith(full).eql(full));
    try testing.expect(full.xorWith(full).eql(empty));
    try testing.expect(full.xorWith(empty).eql(full));
    try testing.expect(black.xorWith(red).eql(full));
    try testing.expect(red.xorWith(black).eql(full));

    try testing.expect(empty.differenceWith(empty).eql(empty));
    try testing.expect(empty.differenceWith(full).eql(empty));
    try testing.expect(full.differenceWith(full).eql(empty));
    try testing.expect(full.differenceWith(empty).eql(full));
    try testing.expect(full.differenceWith(red).eql(black));
    try testing.expect(full.differenceWith(black).eql(red));
}

test "EnumSet empty" {
    const E = enum {};
    const empty = EnumSet(E).empty;
    const full = EnumSet(E).full;

    try std.testing.expect(empty.eql(full));
    try std.testing.expect(empty.complement().eql(full));
    try std.testing.expect(empty.complement().eql(full.complement()));
    try std.testing.expect(empty.eql(full.complement()));
}

test "EnumSet const iterator" {
    const Direction = enum { up, down, left, right };
    const diag_move = init: {
        var move = EnumSet(Direction).empty;
        move.insert(.right);
        move.insert(.up);
        break :init move;
    };

    var result = EnumSet(Direction).empty;
    var it = diag_move.iterator();
    while (it.next()) |dir| {
        result.insert(dir);
    }

    try testing.expect(result.eql(diag_move));
}

test "EnumSet non-exhaustive" {
    const BitIndices = enum(u4) {
        a = 0,
        b = 1,
        c = 4,
        _,
    };
    const BitField = EnumSet(BitIndices);

    var flags = BitField.init(.{ .a = true, .b = true });
    flags.insert(.c);
    flags.remove(.a);
    try testing.expect(!flags.contains(.a));
    try testing.expect(flags.contains(.b));
    try testing.expect(flags.contains(.c));
}

pub fn EnumIndexer(comptime E: type) type {
    // 下面 `std.mem.sortUnstable` 调用的 n log n。
    const fields_len = @typeInfo(E).@"enum".field_names.len;
    @setEvalBranchQuota(3 * fields_len * std.math.log2(@max(fields_len, 1)) + eval_branch_quota_cushion);

    if (@typeInfo(E).@"enum".mode == .nonexhaustive) {
        const BackingInt = @typeInfo(E).@"enum".tag_type;
        if (@bitSizeOf(BackingInt) > @bitSizeOf(usize))
            @compileError("Cannot create an enum indexer for a given non-exhaustive enum, tag_type is larger than usize.");

        return struct {
            pub const Key: type = E;

            const backing_int_sign = @typeInfo(BackingInt).int.signedness;
            const min_value = std.math.minInt(BackingInt);
            const max_value = std.math.maxInt(BackingInt);

            const RangeType = @Int(.unsigned, @bitSizeOf(BackingInt));
            pub const count: comptime_int = std.math.maxInt(RangeType) + 1;

            pub fn indexOf(e: E) usize {
                if (backing_int_sign == .unsigned)
                    return @backingInt(e);

                return if (@backingInt(e) < 0)
                    @intCast(@backingInt(e) - min_value)
                else
                    @as(RangeType, -min_value) + @as(RangeType, @intCast(@backingInt(e)));
            }
            pub fn keyForIndex(i: usize) E {
                if (backing_int_sign == .unsigned)
                    return @fromBackingInt(@intCast(i));

                return @fromBackingInt(@intCast(@as(@Int(.signed, @bitSizeOf(RangeType) + 1), @intCast(i)) + min_value));
            }
        };
    }

    if (fields_len == 0) {
        return struct {
            pub const Key = E;
            pub const count: comptime_int = 0;
            pub fn indexOf(e: E) usize {
                _ = e;
                unreachable;
            }
            pub fn keyForIndex(i: usize) E {
                _ = i;
                unreachable;
            }
        };
    }

    var field_values = @typeInfo(E).@"enum".field_values[0..fields_len].*;

    std.mem.sortUnstable(comptime_int, &field_values, {}, struct {
        fn lessThan(_: void, a: comptime_int, b: comptime_int) bool {
            return a < b;
        }
    }.lessThan);

    const min = field_values[0];
    const max = field_values[fields_len - 1];
    if (max - min == field_values.len - 1) {
        return struct {
            pub const Key = E;
            pub const count: comptime_int = fields_len;
            pub fn indexOf(e: E) usize {
                return @as(usize, @intCast(@backingInt(e) - min));
            }
            pub fn keyForIndex(i: usize) E {
                // TODO: 修正加法语义。为避免人为将
                // 有符号枚举值范围限制为 max_isize,
                // 此计算牺牲了部分安全性。
                const enum_value = if (min < 0) @as(isize, @bitCast(i)) +% min else i + min;
                return @as(E, @fromBackingInt(@intCast(@as(@typeInfo(E).@"enum".tag_type, @intCast(enum_value)))));
            }
        };
    }

    const keys = valuesFromFields(E, &field_values);

    return struct {
        pub const Key = E;
        pub const count: comptime_int = fields_len;
        pub fn indexOf(e: E) usize {
            for (keys, 0..) |k, i| {
                if (k == e) return i;
            }
            unreachable;
        }
        pub fn keyForIndex(i: usize) E {
            return keys[i];
        }
    };
}

test "EnumIndexer non-exhaustive" {
    const backing_ints = [_]type{
        i1,
        i2,
        i3,
        i4,
        i8,
        i16,
        @Int(.signed, @bitSizeOf(isize) - 1),
        isize,
        u1,
        u2,
        u3,
        u4,
        u16,
        @Int(.unsigned, @bitSizeOf(usize) - 1),
        usize,
    };
    inline for (backing_ints) |BackingInt| {
        const E = enum(BackingInt) {
            number_zero_tag = 0,
            _,
        };
        const Indexer = EnumIndexer(E);

        const min_tag: E = @fromBackingInt(@intCast(std.math.minInt(BackingInt)));
        const max_tag: E = @fromBackingInt(@intCast(std.math.maxInt(BackingInt)));

        const RangedType = @Int(.unsigned, @bitSizeOf(BackingInt));
        const max_index: comptime_int = std.math.maxInt(RangedType);
        const number_zero_tag_index: usize = switch (@typeInfo(BackingInt).int.signedness) {
            .unsigned => 0,
            .signed => @divCeil(max_index, 2),
        };

        try testing.expectEqual(E, Indexer.Key);
        try testing.expectEqual(max_index + 1, Indexer.count);

        try testing.expectEqual(@as(usize, 0), Indexer.indexOf(min_tag));
        try testing.expectEqual(number_zero_tag_index, Indexer.indexOf(E.number_zero_tag));
        try testing.expectEqual(@as(usize, max_index), Indexer.indexOf(max_tag));

        try testing.expectEqual(min_tag, Indexer.keyForIndex(0));
        try testing.expectEqual(E.number_zero_tag, Indexer.keyForIndex(number_zero_tag_index));
        try testing.expectEqual(max_tag, Indexer.keyForIndex(max_index));
    }
}

test "EnumIndexer dense zeroed" {
    const E = enum(u2) { b = 1, a = 0, c = 2 };
    const Indexer = EnumIndexer(E);
    try testing.expectEqual(E, Indexer.Key);
    try testing.expectEqual(3, Indexer.count);

    try testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
    try testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
    try testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));

    try testing.expectEqual(E.a, Indexer.keyForIndex(0));
    try testing.expectEqual(E.b, Indexer.keyForIndex(1));
    try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}

test "EnumIndexer dense positive" {
    const E = enum(u4) { c = 6, a = 4, b = 5 };
    const Indexer = EnumIndexer(E);
    try testing.expectEqual(E, Indexer.Key);
    try testing.expectEqual(3, Indexer.count);

    try testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
    try testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
    try testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));

    try testing.expectEqual(E.a, Indexer.keyForIndex(0));
    try testing.expectEqual(E.b, Indexer.keyForIndex(1));
    try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}

test "EnumIndexer dense negative" {
    const E = enum(i4) { a = -6, c = -4, b = -5 };
    const Indexer = EnumIndexer(E);
    try testing.expectEqual(E, Indexer.Key);
    try testing.expectEqual(3, Indexer.count);

    try testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
    try testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
    try testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));

    try testing.expectEqual(E.a, Indexer.keyForIndex(0));
    try testing.expectEqual(E.b, Indexer.keyForIndex(1));
    try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}

test "EnumIndexer sparse" {
    const E = enum(i4) { a = -2, c = 6, b = 4 };
    const Indexer = EnumIndexer(E);
    try testing.expectEqual(E, Indexer.Key);
    try testing.expectEqual(3, Indexer.count);

    try testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
    try testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
    try testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));

    try testing.expectEqual(E.a, Indexer.keyForIndex(0));
    try testing.expectEqual(E.b, Indexer.keyForIndex(1));
    try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}

test "EnumIndexer empty" {
    const E = enum {};
    const Indexer = EnumIndexer(E);
    try testing.expectEqual(E, Indexer.Key);
    try testing.expectEqual(0, Indexer.count);
}

test "EnumIndexer large dense unsorted" {
    @setEvalBranchQuota(500_000); // 多次 `comptimePrint`。
    // 创建含 500 个字段的枚举,字段值按*降序*排列。
    const E = @Enum(u32, .exhaustive, names: {
        var names: [500][]const u8 = undefined;
        for (&names, 0..) |*name, i| name.* = std.fmt.comptimePrint("f{d}", .{i});
        break :names &names;
    }, vals: {
        var vals: [500]u32 = undefined;
        for (&vals, 0..) |*val, i| val.* = 500 - i;
        break :vals &vals;
    });
    const Indexer = EnumIndexer(E);
    try testing.expectEqual(E.f0, Indexer.keyForIndex(499));
    try testing.expectEqual(E.f499, Indexer.keyForIndex(0));
    try testing.expectEqual(499, Indexer.indexOf(.f0));
    try testing.expectEqual(0, Indexer.indexOf(.f499));
}

test values {
    const E = enum {
        X,
        Y,
        Z,
        const A = 1;
    };
    try testing.expectEqualSlices(E, &.{ .X, .Y, .Z }, values(E));
}