membuiltinnative_endianstddebugassertmathtestingEndianAbsorbSentinelbyte_size_in_bitsAllocatorAlignmentValidationAllocatorvalidationWrapcopyForwardscopyBackwardscopySentinelcopySentinelInclusivezeroeszeroInitsortsortUnstablesortContextsortUnstableContextorderorderZboundedOrderZlessThanlessThanZuse_vectorsuse_vectors_for_comparisoneqleqlBytesindexOfDifffindDiffSpanspanSliceTosliceTolenSliceTolenindexOfSentinelfindSentinelallEqualtrimStarttrimEndtrimindexOfScalarfindScalarlastIndexOfScalarfindScalarLastindexOfScalarPosfindScalarPosindexOfAnyfindAnylastIndexOfAnyfindLastAnyindexOfAnyPosfindAnyPosindexOfNonefindNonelastIndexOfNonefindLastNoneindexOfNonePosfindNonePosindexOffindlastIndexOfLinearfindLastLinearindexOfPosLinearfindPosLinearboyerMooreHorspoolPreprocessReverseboyerMooreHorspoolPreprocesslastIndexOffindLastindexOfPosfindPoscountcountScalarcontainsAtLeastcontainsAtLeastScalarreadVarIntreadVarPackedIntreadIntreadPackedIntLittlereadPackedIntBigreadPackedIntwriteIntwritePackedIntLittlewritePackedIntBigwritePackedIntwriteVarPackedIntbyteSwapAllFieldsbyteSwapAllFieldsAlignedbyteSwapbyteSwapAlignedbyteSwapAllElementstokenizeAnytokenizeSequencetokenizeScalarsplitSequencesplitAnysplitScalarsplitBackwardsSequencesplitBackwardsAnysplitBackwardsScalarwindowWindowIteratorstartsWithendsWithcutPrefixcutSuffixcutcutLastcutScalarcutScalarLastDelimiterTypeTokenIteratorSplitIteratorSplitBackwardsIteratorjoinjoinZjoinMaybeZconcatconcatWithSentinelconcatMaybeSentinelmoreReadIntTestsminmaxminMaxindexOfMinfindMinindexOfMaxfindMaxindexOfMinMaxfindMinMaxswapreverseVectorreverseReverseIteratorreverseIteratorrotatereplacereplaceScalarcollapseRepeatsLencollapseRepeatstestCollapseRepeatsreplacementSizereplaceOwnedlittleToNativebigToNativetoNativenativeTonativeToLittlenativeToBigalignPointerOffsetalignPointercheckAlignCopyPtrAttrsAsBytesReturnTypeasBytestoBytesBytesAsValueReturnTypebytesAsValuebytesToValueBytesAsSliceReturnTypebytesAsSliceSliceAsBytesReturnTypesliceAsBytesdoTheTestabsorbSentinelalignForwardAnyAlignalignForwardalignForwardLog2doNotOptimizeAwayalignBackwardAnyAlignalignBackwardisValidAlignisValidAlignGenericisAlignedAnyAlignisAlignedLog2isAlignedisAlignedGenericAlignedSlicealignInBytesalignInSlicePrintErrorprintprintSentinel
std.mem.absorbSentinel
函数
如果提供的切片没有以哨兵值结尾,则不执行任何操作并返回该切片。 如果切片以哨兵值结尾,则返回不带哨兵的切片, 长度加一,以包含被吸收的哨兵元素。
pub fn absorbSentinel(slice: anytype) AbsorbSentinel(@TypeOf(slice))
用法示例
test absorbSentinel {
{
var buffer: [3:0]u8 = .{ 1, 2, 3 };
const foo: [:0]const u8 = &buffer;
const bar: []const u8 = &buffer;
const baz: *const [3:0]u8 = &buffer;
try testing.expectEqual([]const u8, @TypeOf(absorbSentinel(foo)));
try testing.expectEqual([]const u8, @TypeOf(absorbSentinel(bar)));
try testing.expectEqual(*const [4]u8, @TypeOf(absorbSentinel(baz)));
try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 0 }, absorbSentinel(foo));
try testing.expectEqualSlices(u8, &.{ 1, 2, 3 }, absorbSentinel(bar));
try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 0 }, absorbSentinel(baz));
}
{
var buffer: [3:0]u8 = .{ 1, 2, 3 };
const foo: [:0]u8 = &buffer;
const bar: []u8 = &buffer;
const baz: *[3:0]u8 = &buffer;
try testing.expectEqual([]u8, @TypeOf(absorbSentinel(foo)));
try testing.expectEqual([]u8, @TypeOf(absorbSentinel(bar)));
try testing.expectEqual(*[4]u8, @TypeOf(absorbSentinel(baz)));
var expected_foo = [_]u8{ 1, 2, 3, 0 };
try testing.expectEqualSlices(u8, &expected_foo, absorbSentinel(foo));
var expected_bar = [_]u8{ 1, 2, 3 };
try testing.expectEqualSlices(u8, &expected_bar, absorbSentinel(bar));
var expected_baz = [_]u8{ 1, 2, 3, 0 };
try testing.expectEqualSlices(u8, &expected_baz, absorbSentinel(baz));
}
}
std.mem.AbsorbSentinel
别名
std.mem.alignBackward
函数
将地址向下舍入到前一个或当前对齐地址。 对齐值必须为大于 0 的 2 的幂。
pub fn alignBackward(comptime T: type, addr: T, alignment: T) T
参数
T: type
addr: T
alignment: T
std.mem.alignBackwardAnyAlign
函数
将地址向下舍入到前一个(或当前)对齐地址。
与 alignBackward 不同,alignment 可为任意正数,不限于 2 的幂。
pub fn alignBackwardAnyAlign(comptime T: type, addr: T, alignment: T) T
参数
T: type
addr: T
alignment: T
std.mem.AlignedSlice
类型函数
返回具有指定新对齐要求的切片,
其余指针属性均从 AttributeSource 复制。
fn AlignedSlice(comptime AttributeSource: type, comptime new_alignment: usize) type
参数
AttributeSource: type
new_alignment: usize
std.mem.alignForward
函数
将地址向上舍入到下一个(或当前)对齐地址。 对齐值必须为大于 0 的 2 的幂。 断言地址向上舍入不会引起整数溢出。
pub fn alignForward(comptime T: type, addr: T, alignment: T) T
参数
T: type
addr: T
alignment: T
用法示例
test alignForward {
try testing.expect(alignForward(usize, 1, 1) == 1);
try testing.expect(alignForward(usize, 2, 1) == 2);
try testing.expect(alignForward(usize, 1, 2) == 2);
try testing.expect(alignForward(usize, 2, 2) == 2);
try testing.expect(alignForward(usize, 3, 2) == 4);
try testing.expect(alignForward(usize, 4, 2) == 4);
try testing.expect(alignForward(usize, 7, 8) == 8);
try testing.expect(alignForward(usize, 8, 8) == 8);
try testing.expect(alignForward(usize, 9, 8) == 16);
try testing.expect(alignForward(usize, 15, 8) == 16);
try testing.expect(alignForward(usize, 16, 8) == 16);
try testing.expect(alignForward(usize, 17, 8) == 24);
}
std.mem.alignForwardAnyAlign
函数
将地址向下舍入到最近的对齐地址(可能是当前地址)。
与 alignForward 不同,alignment 可为任意正数,不限于 2 的幂。
pub fn alignForwardAnyAlign(comptime T: type, addr: T, alignment: T) T
参数
T: type
addr: T
alignment: T
std.mem.alignForwardLog2
函数
使用 log2 表示,将地址向上舍入到下一个对齐边界。 等同于以 alignment = 1 << log2_alignment 调用 alignForward。 已知对齐量为 2 的幂时更高效。
pub fn alignForwardLog2(addr: usize, log2_alignment: u8) usize
参数
addr: usize
log2_alignment: u8
std.mem.alignInBytes
函数
返回给定字节中满足新对齐要求的最大切片,
若给定字节中没有符合要求的地址,则返回 null。
pub fn alignInBytes(bytes: []u8, comptime new_alignment: usize) ?[]align(new_alignment) u8
参数
bytes: []u8
new_alignment: usize
std.mem.alignInSlice
函数
返回给定切片内满足新对齐要求的最大子切片;
若给定切片不包含符合要求的地址,则返回 null。
pub fn alignInSlice(slice: anytype, comptime new_alignment: usize) ?AlignedSlice(@TypeOf(slice), new_alignment)
参数
new_alignment: usize
std.mem.Alignment
容器
以 2 的幂形式存储。
字段
@"1" = 0
@"2" = 1
@"4" = 2
@"8" = 3
@"16" = 4
@"32" = 5
@"64" = 6
_
std.mem.Alignment.backward
函数
返回满足此对齐要求的前一个地址。
pub fn backward(a: Alignment, address: usize) usize
参数
a: Alignment
address: usize
std.mem.Alignment.check
函数
返回地址是否满足此对齐要求。
pub fn check(a: Alignment, address: usize) bool
参数
a: Alignment
address: usize
std.mem.Alignment.compare
函数
pub fn compare(lhs: Alignment, op: std.math.CompareOperator, rhs: Alignment) bool
参数
std.mem.Alignment.forward
函数
返回满足此对齐要求的下一个地址。
pub fn forward(a: Alignment, address: usize) usize
参数
a: Alignment
address: usize
std.mem.Alignment.fromByteUnits
函数
pub fn fromByteUnits(n: usize) Alignment
参数
n: usize
std.mem.Alignment.fromByteUnitsOptional
函数
pub fn fromByteUnitsOptional(maybe_n: ?usize) ?Alignment
参数
maybe_n: ?usize
std.mem.Alignment.max
函数
pub fn max(lhs: Alignment, rhs: Alignment) Alignment
参数
std.mem.Alignment.min
函数
pub fn min(lhs: Alignment, rhs: Alignment) Alignment
参数
std.mem.Alignment.of
函数
pub inline fn of(comptime T: type) Alignment
参数
T: type
std.mem.Alignment.order
函数
pub fn order(lhs: Alignment, rhs: Alignment) std.math.Order
参数
std.mem.Alignment.toByteUnits
函数
pub fn toByteUnits(a: Alignment) usize
参数
a: Alignment
std.mem.alignPointer
函数
将给定指针值按指定对齐因子对齐。 返回对齐后的指针;满足以下任一条件时 返回 null:
- 对齐后的指针超出地址空间;
- 为对齐指针所需的位移不是所指类型 大小的整数倍。
pub fn alignPointer(ptr: anytype, align_to: usize) ?@TypeOf(ptr)
参数
align_to: usize
用法示例
test alignPointer {
const S = struct {
fn checkAlign(comptime T: type, base: usize, align_to: usize, expected: usize) !void {
const ptr: T = @ptrFromInt(base);
const aligned = alignPointer(ptr, align_to);
try testing.expectEqual(expected, @intFromPtr(aligned));
}
};
try S.checkAlign([*]u8, 0x123, 0x200, 0x200);
try S.checkAlign([*]align(4) u8, 0x10, 2, 0x10);
try S.checkAlign([*]u32, 0x10, 2, 0x10);
try S.checkAlign([*]u32, 0x4, 16, 0x10);
// 未对齐。
try S.checkAlign([*]align(1) u32, 0x3, 2, 0);
// 溢出。
try S.checkAlign([*]u32, math.maxInt(usize) - 3, 8, 0);
}
std.mem.alignPointerOffset
函数
返回需要加到给定指针上的元素数量,使指针对齐到指定数量的倍数。
满足以下任一条件时返回 null:
- 对齐后的指针超出地址空间。
- 对齐所需的偏移量不是所指类型大小的整数倍。
pub fn alignPointerOffset(ptr: anytype, align_to: usize) ?usize
参数
align_to: usize
std.mem.allEqual
函数
如果切片中的所有元素均等于给定标量值,则返回 true。
pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool
参数
T: type
slice: []const T
scalar: T
std.mem.Allocator
别名
别名目标 std.mem.Allocator
std.mem.asBytes
函数
给定指向单个元素的指针,返回底层字节的切片,并保留指针属性。
pub fn asBytes(ptr: anytype) AsBytesReturnType(@TypeOf(ptr))
用法示例
test asBytes {
const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xEF\xBE\xAD\xDE",
};
try testing.expect(eql(u8, asBytes(&deadbeef), deadbeef_bytes));
var codeface = @as(u32, 0xC0DEFACE);
for (asBytes(&codeface)) |*b|
b.* = 0;
try testing.expect(codeface == 0);
const S = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
};
const inst = S{
.a = 0xBE,
.b = 0xEF,
.c = 0xDE,
.d = 0xA1,
};
switch (native_endian) {
.little => {
try testing.expect(eql(u8, asBytes(&inst), "\xBE\xEF\xDE\xA1"));
},
.big => {
try testing.expect(eql(u8, asBytes(&inst), "\xA1\xDE\xEF\xBE"));
},
}
const ZST = struct {};
const zero = ZST{};
try testing.expect(eql(u8, asBytes(&zero), ""));
}
std.mem.AsBytesReturnType
类型函数
fn AsBytesReturnType(comptime P: type) type
参数
P: type
std.mem.assert
别名
别名目标 std.debug.assert
std.mem.bigToNative
函数
将大端整数转换为主机字节序。
pub fn bigToNative(comptime T: type, x: T) T
参数
T: type
x: T
std.mem.boundedOrderZ
函数
按字典序比较两个以 NUL 结尾的多元素指针,直到指定边界。
pub fn boundedOrderZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T, bound: usize) math.Order
参数
T: type
lhs: [*:0]const T
rhs: [*:0]const T
bound: usize
std.mem.boyerMooreHorspoolPreprocess
函数
fn boyerMooreHorspoolPreprocess(pattern: []const u8, table: *[256]usize) void
参数
pattern: []const u8
table: *[256]usize
std.mem.boyerMooreHorspoolPreprocessReverse
函数
fn boyerMooreHorspoolPreprocessReverse(pattern: []const u8, table: *[256]usize) void
参数
pattern: []const u8
table: *[256]usize
std.mem.builtin
常量
std.mem.byte_size_in_bits
常量
标准库目前全面依赖一个字节为 8 位这一条件。 (可见分配代码中广泛使用 u8 作为 “字节”类型。)依赖此条件的代码可以引用 此声明。如果将来尝试把标准库移植到 字节并非 8 位的平台,就可以据此搜索 需要更新的位置。
std.mem.bytesAsSlice
函数
给定字节切片,返回由这些字节作为底层存储、
元素为指定类型的切片,保留指针属性。
若 T 的大小为零字节,则返回切片的 len 为零。
pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T, @TypeOf(bytes))
参数
T: type
用法示例
test bytesAsSlice {
{
const bytes = [_]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
const slice = bytesAsSlice(u16, bytes[0..]);
try testing.expect(slice.len == 2);
try testing.expect(bigToNative(u16, slice[0]) == 0xDEAD);
try testing.expect(bigToNative(u16, slice[1]) == 0xBEEF);
}
{
const bytes = [_]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
var runtime_zero: usize = 0;
_ = &runtime_zero;
const slice = bytesAsSlice(u16, bytes[runtime_zero..]);
try testing.expect(slice.len == 2);
try testing.expect(bigToNative(u16, slice[0]) == 0xDEAD);
try testing.expect(bigToNative(u16, slice[1]) == 0xBEEF);
}
}
std.mem.BytesAsSliceReturnType
类型函数
fn BytesAsSliceReturnType(comptime T: type, comptime bytesType: type) type
参数
T: type
bytesType: type
std.mem.bytesAsValue
函数
给定字节数组指针,返回指向由这些字节作为存储的指定类型值的指针,并保留指针属性。
pub fn bytesAsValue(comptime T: type, bytes: anytype) BytesAsValueReturnType(T, @TypeOf(bytes))
参数
T: type
用法示例
test bytesAsValue {
const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xEF\xBE\xAD\xDE",
};
try testing.expect(deadbeef == bytesAsValue(u32, deadbeef_bytes).*);
var codeface_bytes: [4]u8 = switch (native_endian) {
.big => "\xC0\xDE\xFA\xCE",
.little => "\xCE\xFA\xDE\xC0",
}.*;
const codeface = bytesAsValue(u32, &codeface_bytes);
try testing.expect(codeface.* == 0xC0DEFACE);
codeface.* = 0;
for (codeface_bytes) |b|
try testing.expect(b == 0);
const S = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
};
const inst = S{
.a = 0xBE,
.b = 0xEF,
.c = 0xDE,
.d = 0xA1,
};
const inst_bytes = switch (native_endian) {
.little => "\xBE\xEF\xDE\xA1",
.big => "\xA1\xDE\xEF\xBE",
};
const inst2 = bytesAsValue(S, inst_bytes);
try testing.expect(std.meta.eql(inst, inst2.*));
}
std.mem.BytesAsValueReturnType
类型函数
fn BytesAsValueReturnType(comptime T: type, comptime B: type) type
参数
T: type
B: type
std.mem.bytesToValue
函数
给定字节数组指针,返回指定类型的值, 其底层数据为这些字节的副本。
pub fn bytesToValue(comptime T: type, bytes: anytype) T
参数
T: type
用法示例
test bytesToValue {
const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xEF\xBE\xAD\xDE",
};
const deadbeef = bytesToValue(u32, deadbeef_bytes);
try testing.expect(deadbeef == @as(u32, 0xDEADBEEF));
}
std.mem.byteSwap
函数
反转字节顺序。 递归处理结构体、联合体、数组、枚举、浮点数和整数。 extern 结构体字段和数组元素的顺序保持不变, 并递归交换其字节顺序。 可用于在小端和大端表示之间转换。
pub fn byteSwap(comptime S: type, ptr: *S) void
参数
S: type
ptr: *S
用法示例
test byteSwap {
const T = extern struct {
f0: u8,
f1: u16,
f2: u32,
f3: [1]u8,
f4: bool,
f5: f32,
f6: extern union { f0: u16, f1: u16 },
};
const K = extern struct {
f0: u8,
f1: T,
f2: u16,
f3: [1]u8,
f4: bool,
f5: f32,
};
const P = packed struct(u32) {
f0: u1,
f1: u7,
f2: u4,
f3: u4,
f4: u16,
};
const A = extern struct {
f0: u32,
f1: extern struct {
f0: u64,
} align(4),
f2: u32,
};
const E = enum(u32) {
_,
};
var s = T{
.f0 = 0x12,
.f1 = 0x1234,
.f2 = 0x12345678,
.f3 = .{0x12},
.f4 = true,
.f5 = @bitCast(@as(u32, 0x4640e400)),
.f6 = .{ .f0 = 0x1234 },
};
var k = K{
.f0 = 0x12,
.f1 = s,
.f2 = 0x1234,
.f3 = .{0x12},
.f4 = false,
.f5 = @bitCast(@as(u32, 0x45d42800)),
};
var p: P = @bitCast(@as(u32, 0x01234567));
var a: A = A{
.f0 = 0x12345678,
.f1 = .{ .f0 = 0x123456789ABCDEF0 },
.f2 = 0x87654321,
};
var e: E = @fromBackingInt(0x12345678);
var f: f32 = @bitCast(@as(u32, 0x4640e400));
byteSwap(T, &s);
byteSwap(K, &k);
byteSwap(P, &p);
byteSwap(A, &a);
byteSwap(E, &e);
byteSwap(f32, &f);
try std.testing.expectEqual(T{
.f0 = 0x12,
.f1 = 0x3412,
.f2 = 0x78563412,
.f3 = .{0x12},
.f4 = true,
.f5 = @bitCast(@as(u32, 0x00e44046)),
.f6 = .{ .f0 = 0x3412 },
}, s);
try std.testing.expectEqual(K{
.f0 = 0x12,
.f1 = s,
.f2 = 0x3412,
.f3 = .{0x12},
.f4 = false,
.f5 = @bitCast(@as(u32, 0x0028d445)),
}, k);
try std.testing.expectEqual(@as(P, @bitCast(@as(u32, 0x67452301))), p);
try std.testing.expectEqual(A{
.f0 = 0x78563412,
.f1 = .{ .f0 = 0xF0DEBC9A78563412 },
.f2 = 0x21436587,
}, a);
try std.testing.expectEqual(@as(E, @fromBackingInt(0x78563412)), e);
try std.testing.expectEqual(@as(f32, @bitCast(@as(u32, 0x00e44046))), f);
}
std.mem.byteSwapAligned
函数
反转字节顺序。 递归处理结构体、联合体、数组、枚举、浮点数和整数。 extern 结构体字段和数组元素的顺序保持不变, 并递归交换其字节顺序。 可用于在小端和大端表示之间转换。
pub fn byteSwapAligned( comptime S: type, comptime a: Alignment, ptr: *align(a.toByteUnits()) S, ) void
参数
std.mem.byteSwapAllElements
函数
反转切片中所有元素的字节顺序。 递归处理结构体、联合体、数组、枚举、浮点数和整数。 可用于在小端和大端表示之间转换。
pub fn byteSwapAllElements(comptime Elem: type, slice: []Elem) void
参数
Elem: type
slice: []Elem
std.mem.byteSwapAllFields
别名
已弃用:改用 byteSwap。
别名目标 std.mem.byteSwap
std.mem.byteSwapAllFieldsAligned
别名
已弃用:改用 byteSwapAligned。
std.mem.checkAlign
函数
fn checkAlign(comptime T: type, base: usize, align_to: usize, expected: usize) !void
参数
T: type
base: usize
align_to: usize
expected: usize
std.mem.collapseRepeats
函数
将连续重复元素合并为一个条目。
pub fn collapseRepeats(comptime T: type, slice: []T, elem: T) []T
参数
T: type
slice: []T
elem: T
用法示例
test collapseRepeats {
try testCollapseRepeats("", '/', "");
try testCollapseRepeats("a", '/', "a");
try testCollapseRepeats("/", '/', "/");
try testCollapseRepeats("//", '/', "/");
try testCollapseRepeats("/a", '/', "/a");
try testCollapseRepeats("//a", '/', "/a");
try testCollapseRepeats("a/", '/', "a/");
try testCollapseRepeats("a//", '/', "a/");
try testCollapseRepeats("a/a", '/', "a/a");
try testCollapseRepeats("a//a", '/', "a/a");
try testCollapseRepeats("//a///a////", '/', "/a/a/");
}
std.mem.collapseRepeatsLen
函数
将连续重复元素合并为一个条目。
pub fn collapseRepeatsLen(comptime T: type, slice: []T, elem: T) usize
参数
T: type
slice: []T
elem: T
std.mem.concat
函数
将各切片中的 T 复制到一个恰好容纳所有元素的新切片中。
pub fn concat(allocator: Allocator, comptime T: type, slices: []const []const T) Allocator.Error![]T
参数
错误
- OutOfMemory
用法示例
test concat {
{
const str = try concat(testing.allocator, u8, &[_][]const u8{ "abc", "def", "ghi" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "abcdefghi"));
}
{
const str = try concat(testing.allocator, u32, &[_][]const u32{
&[_]u32{ 0, 1 },
&[_]u32{ 2, 3, 4 },
&[_]u32{},
&[_]u32{5},
});
defer testing.allocator.free(str);
try testing.expect(eql(u32, str, &[_]u32{ 0, 1, 2, 3, 4, 5 }));
}
{
const str = try concatWithSentinel(testing.allocator, u8, &[_][]const u8{ "abc", "def", "ghi" }, 0);
defer testing.allocator.free(str);
try testing.expectEqualSentinel(u8, 0, str, "abcdefghi");
}
{
const slice = try concatWithSentinel(testing.allocator, u8, &[_][]const u8{}, 0);
defer testing.allocator.free(slice);
try testing.expectEqualSentinel(u8, 0, slice, &[_:0]u8{});
}
{
const slice = try concatWithSentinel(testing.allocator, u32, &[_][]const u32{
&[_]u32{ 0, 1 },
&[_]u32{ 2, 3, 4 },
&[_]u32{},
&[_]u32{5},
}, 2);
defer testing.allocator.free(slice);
try testing.expectEqualSentinel(u32, 2, slice, &[_:2]u32{ 0, 1, 2, 3, 4, 5 });
}
}
std.mem.concatMaybeSentinel
函数
将各切片中的每个 T 复制到新切片中,该切片恰好容纳所有元素及哨兵。
pub fn concatMaybeSentinel(allocator: Allocator, comptime T: type, slices: []const []const T, comptime s: ?T) Allocator.Error![]T
参数
错误
- OutOfMemory
std.mem.concatWithSentinel
函数
将各切片中的 T 复制到一个恰好容纳所有元素的新切片中。
pub fn concatWithSentinel(allocator: Allocator, comptime T: type, slices: []const []const T, comptime s: T) Allocator.Error![:s]T
参数
错误
- OutOfMemory
std.mem.containsAtLeast
函数
若 haystack 中至少存在 expected_count 个 needle,则返回 true
needle.len 必须 > 0
不计算重叠匹配
另见:containsAtLeastScalar
pub fn containsAtLeast(comptime T: type, haystack: []const T, expected_count: usize, needle: []const T) bool
参数
T: type
haystack: []const T
expected_count: usize
needle: []const T
用法示例
test containsAtLeast {
try testing.expect(containsAtLeast(u8, "aa", 0, "a"));
try testing.expect(containsAtLeast(u8, "aa", 1, "a"));
try testing.expect(containsAtLeast(u8, "aa", 2, "a"));
try testing.expect(!containsAtLeast(u8, "aa", 3, "a"));
try testing.expect(containsAtLeast(u8, "radaradar", 1, "radar"));
try testing.expect(!containsAtLeast(u8, "radaradar", 2, "radar"));
try testing.expect(containsAtLeast(u8, "radarradaradarradar", 3, "radar"));
try testing.expect(!containsAtLeast(u8, "radarradaradarradar", 4, "radar"));
try testing.expect(containsAtLeast(u8, " radar radar ", 2, "radar"));
try testing.expect(!containsAtLeast(u8, " radar radar ", 3, "radar"));
}
std.mem.containsAtLeastScalar
函数
若 element 在 list 中至少出现 minimum 次,则返回 true。
相关接口:
pub fn containsAtLeastScalar(comptime T: type, list: []const T, element: T, minimum: usize) bool
参数
T: type
list: []const T
element: T
minimum: usize
用法示例
test containsAtLeastScalar {
try testing.expect(containsAtLeastScalar(u8, "aa", 'a', 0));
try testing.expect(containsAtLeastScalar(u8, "aa", 'a', 1));
try testing.expect(containsAtLeastScalar(u8, "aa", 'a', 2));
try testing.expect(!containsAtLeastScalar(u8, "aa", 'a', 3));
try testing.expect(containsAtLeastScalar(u8, "adadda", 'd', 3));
try testing.expect(!containsAtLeastScalar(u8, "adadda", 'd', 4));
}
std.mem.copyBackwards
函数
将全部 source 复制到 dest 的位置 0。 dest.len 必须 >= source.len。 若切片重叠,dest.ptr 必须 >= src.ptr。 此函数已弃用;请改用 @memmove。
pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void
参数
T: type
dest: []T
source: []const T
std.mem.copyForwards
函数
将整个 source 复制到 dest 的位置 0。 dest.len 必须 >= source.len。 若切片重叠,dest.ptr 必须 <= src.ptr。 此函数已弃用;请改用 @memmove。
pub fn copyForwards(comptime T: type, dest: []T, source: []const T) void
参数
T: type
dest: []T
source: []const T
std.mem.CopyPtrAttrs
类型函数
fn CopyPtrAttrs( comptime source: type, comptime size: std.builtin.Type.Pointer.Size, comptime child: type, ) type
参数
std.mem.copySentinel
函数
将 source 复制到 dest,不包括哨兵元素。
断言没有重叠。断言 dest.len 大于或等于 source 长度。返回复制的元素数量,
不计哨兵元素。
pub fn copySentinel(comptime T: type, comptime s: T, dest: []T, source: [*:s]const T) usize
参数
T: type
s: T
dest: []T
source: [*:s]const T
用法示例
test copySentinel {
var dst: [11]u8 = @splat(0xff);
const n = copySentinel(u8, 0, &dst, "hello this\x00is my null-terminated string");
try testing.expectEqualStrings("hello this\xff", &dst);
try testing.expectEqual(n, 10);
}
std.mem.copySentinelInclusive
函数
将 source 复制到 dest,包括哨兵元素。
断言没有重叠。断言 dest.len 大于或等于 source 长度,且包含哨兵所需空间。
返回已复制元素数量,包括哨兵元素。
pub fn copySentinelInclusive(comptime T: type, comptime s: T, dest: []T, source: [*:s]const T) usize
参数
T: type
s: T
dest: []T
source: [*:s]const T
用法示例
test copySentinelInclusive {
var dst: [12]u8 = @splat(0xff);
const n = copySentinelInclusive(u8, 0, &dst, "hello this\x00is my null-terminated string");
try testing.expectEqualStrings("hello this\x00\xff", &dst);
try testing.expectEqual(n, 11);
}
std.mem.count
函数
返回 haystack 中 needle 的数量 needle.len 必须 > 0 不计入重叠的 needle
pub fn count(comptime T: type, haystack: []const T, needle: []const T) usize
参数
T: type
haystack: []const T
needle: []const T
用法示例
test count {
try testing.expect(count(u8, "", "h") == 0);
try testing.expect(count(u8, "h", "h") == 1);
try testing.expect(count(u8, "hh", "h") == 2);
try testing.expect(count(u8, "world!", "hello") == 0);
try testing.expect(count(u8, "hello world!", "hello") == 1);
try testing.expect(count(u8, " abcabc abc", "abc") == 3);
try testing.expect(count(u8, "udexdcbvbruhasdrw", "bruh") == 1);
try testing.expect(count(u8, "foo bar", "o bar") == 1);
try testing.expect(count(u8, "foofoofoo", "foo") == 3);
try testing.expect(count(u8, "fffffff", "ff") == 3);
try testing.expect(count(u8, "owowowu", "owowu") == 1);
}
std.mem.countScalar
函数
返回 element 在内存切片中的出现次数。
pub fn countScalar(comptime T: type, list: []const T, element: T) usize
参数
T: type
list: []const T
element: T
用法示例
test countScalar {
try testing.expectEqual(0, countScalar(u8, "", 'h'));
try testing.expectEqual(1, countScalar(u8, "h", 'h'));
try testing.expectEqual(2, countScalar(u8, "hh", 'h'));
try testing.expectEqual(2, countScalar(u8, "ahhb", 'h'));
try testing.expectEqual(3, countScalar(u8, " abcabc abc", 'b'));
}
std.mem.cut
函数
pub fn cut(comptime T: type, haystack: []const T, needle: []const T) ?struct { []const T, []const T }
参数
T: type
haystack: []const T
needle: []const T
用法示例
test cut {
try testing.expectEqual(null, cut(u8, "a b c", "B"));
const before, const after = cut(u8, "a be c", "be") orelse return error.TestFailed;
try testing.expectEqualStrings("a ", before);
try testing.expectEqualStrings(" c", after);
}
std.mem.cutLast
函数
pub fn cutLast(comptime T: type, haystack: []const T, needle: []const T) ?struct { []const T, []const T }
参数
T: type
haystack: []const T
needle: []const T
用法示例
test cutLast {
try testing.expectEqual(null, cutLast(u8, "a b c", "B"));
const before, const after = cutLast(u8, "a be c be d", "be") orelse return error.TestFailed;
try testing.expectEqualStrings("a be c ", before);
try testing.expectEqualStrings(" d", after);
}
std.mem.cutPrefix
函数
如果 slice 以 prefix 开头,则返回 slice 从 prefix.len 开始的剩余部分。
pub fn cutPrefix(comptime T: type, slice: []const T, prefix: []const T) ?[]const T
参数
T: type
slice: []const T
prefix: []const T
用法示例
test cutPrefix {
try testing.expectEqualStrings("foo", cutPrefix(u8, "--example=foo", "--example=").?);
try testing.expectEqual(null, cutPrefix(u8, "--example=foo", "-example="));
}
std.mem.cutScalar
函数
pub fn cutScalar(comptime T: type, haystack: []const T, needle: T) ?struct { []const T, []const T }
参数
T: type
haystack: []const T
needle: T
用法示例
test cutScalar {
try testing.expectEqual(null, cutScalar(u8, "a b c", 'B'));
const before, const after = cutScalar(u8, "a b c", 'b') orelse return error.TestFailed;
try testing.expectEqualStrings("a ", before);
try testing.expectEqualStrings(" c", after);
}
std.mem.cutScalarLast
函数
pub fn cutScalarLast(comptime T: type, haystack: []const T, needle: T) ?struct { []const T, []const T }
参数
T: type
haystack: []const T
needle: T
用法示例
test cutScalarLast {
try testing.expectEqual(null, cutScalarLast(u8, "a b c", 'B'));
const before, const after = cutScalarLast(u8, "a b c b d", 'b') orelse return error.TestFailed;
try testing.expectEqualStrings("a b c ", before);
try testing.expectEqualStrings(" d", after);
}
std.mem.cutSuffix
函数
若 slice 以 suffix 结尾,则返回 slice 从开头到 suffix 起始处的部分。
pub fn cutSuffix(comptime T: type, slice: []const T, suffix: []const T) ?[]const T
参数
T: type
slice: []const T
suffix: []const T
用法示例
test cutSuffix {
try testing.expectEqualStrings("foo", cutSuffix(u8, "foobar", "bar").?);
try testing.expectEqual(null, cutSuffix(u8, "foobar", "baz"));
}
std.mem.debug
别名
别名目标 std.debug
std.mem.DelimiterType
容器
分词和拆分操作的分隔符类型。
字段
sequence
any
scalar
std.mem.doNotOptimizeAway
函数
强制对表达式求值;即使最终丢弃结果, 也尝试阻止编译器将计算优化掉。
pub fn doNotOptimizeAway(val: anytype) void
用法示例
test doNotOptimizeAway {
comptime doNotOptimizeAway("test");
doNotOptimizeAway(null);
doNotOptimizeAway(true);
doNotOptimizeAway(0);
doNotOptimizeAway(0.0);
doNotOptimizeAway(@as(u1, 0));
doNotOptimizeAway(@as(u3, 0));
doNotOptimizeAway(@as(u8, 0));
doNotOptimizeAway(@as(u16, 0));
doNotOptimizeAway(@as(u32, 0));
doNotOptimizeAway(@as(u64, 0));
doNotOptimizeAway(@as(u128, 0));
doNotOptimizeAway(@as(u13, 0));
doNotOptimizeAway(@as(u37, 0));
doNotOptimizeAway(@as(u96, 0));
doNotOptimizeAway(@as(u200, 0));
doNotOptimizeAway(@as(f32, 0.0));
doNotOptimizeAway(@as(f64, 0.0));
doNotOptimizeAway(@as([4]u8, @splat(0)));
doNotOptimizeAway(@as([100]u8, @splat(0)));
doNotOptimizeAway(@as(std.builtin.Endian, .little));
}
std.mem.doNotOptimizeAway.escape
变量
*const anyopaque
std.mem.doTheTest
函数
fn doTheTest() !void
std.mem.Endian
别名
别名目标 std.lang.Endian
std.mem.endsWith
函数
如果 haystack 以 needle 结尾,则返回 true。 时间复杂度:O(needle.len)。
pub fn endsWith(comptime T: type, haystack: []const T, needle: []const T) bool
参数
T: type
haystack: []const T
needle: []const T
用法示例
test endsWith {
try testing.expect(endsWith(u8, "Needle in haystack", "haystack"));
try testing.expect(!endsWith(u8, "Bob", "Bo"));
}
std.mem.eql
函数
当且仅当切片长度相同,且全部元素通过相等运算符 比较均为 true 时,返回 true。
pub fn eql(comptime T: type, a: []const T, b: []const T) bool
参数
T: type
a: []const T
b: []const T
用法示例
test eql {
try testing.expect(eql(u8, "abcd", "abcd"));
try testing.expect(!eql(u8, "abcdef", "abZdef"));
try testing.expect(!eql(u8, "abcdefg", "abcdef"));
comptime {
try testing.expect(eql(type, &.{ bool, f32 }, &.{ bool, f32 }));
try testing.expect(!eql(type, &.{ bool, f32 }, &.{ f32, bool }));
try testing.expect(!eql(type, &.{ bool, f32 }, &.{bool}));
try testing.expect(eql(comptime_int, &.{ 1, 2, 3 }, &.{ 1, 2, 3 }));
try testing.expect(!eql(comptime_int, &.{ 1, 2, 3 }, &.{ 3, 2, 1 }));
try testing.expect(!eql(comptime_int, &.{1}, &.{ 1, 2 }));
}
try testing.expect(eql(void, &.{ {}, {} }, &.{ {}, {} }));
try testing.expect(!eql(void, &.{{}}, &.{ {}, {} }));
const x: [3]f64 = .{ 42.0, math.nan(f64), 3.1415 };
try testing.expect(!eql(f64, &x, &x));
}
std.mem.eqlBytes
函数
std.mem.eql 对字节切片进行了充分优化。
fn eqlBytes(a: []const u8, b: []const u8) bool
参数
a: []const u8
b: []const u8
std.mem.eqlBytes.Chunk
常量
std.mem.eqlBytes.Chunk
类型
std.mem.eqlBytes.isNotEqual
函数
pub inline fn isNotEqual(chunk_a: Chunk, chunk_b: Chunk) bool
参数
std.mem.eqlBytes.isNotEqual
函数
pub inline fn isNotEqual(chunk_a: Chunk, chunk_b: Chunk) bool
参数
std.mem.eqlBytes.size
常量
std.mem.eqlBytes.size
常量
std.mem.find
函数
在 haystack 中查找 needle,返回首次出现位置的索引。 对较大输入使用 Boyer-Moore-Horspool 算法,对较小输入使用线性搜索。 若未找到 needle,则返回 null。
pub fn find(comptime T: type, haystack: []const T, needle: []const T) ?usize
参数
T: type
haystack: []const T
needle: []const T
用法示例
test find {
try testing.expect(find(u8, "one two three four five six seven eight nine ten eleven", "three four").? == 8);
try testing.expect(findLast(u8, "one two three four five six seven eight nine ten eleven", "three four").? == 8);
try testing.expect(find(u8, "one two three four five six seven eight nine ten eleven", "two two") == null);
try testing.expect(findLast(u8, "one two three four five six seven eight nine ten eleven", "two two") == null);
try testing.expect(find(u8, "one two three four five six seven eight nine ten", "").? == 0);
try testing.expect(findLast(u8, "one two three four five six seven eight nine ten", "").? == 48);
try testing.expect(find(u8, "one two three four", "four").? == 14);
try testing.expect(findLast(u8, "one two three two four", "two").? == 14);
try testing.expect(find(u8, "one two three four", "gour") == null);
try testing.expect(findLast(u8, "one two three four", "gour") == null);
try testing.expect(find(u8, "foo", "foo").? == 0);
try testing.expect(findLast(u8, "foo", "foo").? == 0);
try testing.expect(find(u8, "foo", "fool") == null);
try testing.expect(findLast(u8, "foo", "lfoo") == null);
try testing.expect(findLast(u8, "foo", "fool") == null);
try testing.expect(find(u8, "foo foo", "foo").? == 0);
try testing.expect(findLast(u8, "foo foo", "foo").? == 4);
try testing.expect(findLastAny(u8, "boo, cat", "abo").? == 6);
try testing.expect(findScalarLast(u8, "boo", 'o').? == 2);
}
std.mem.findAny
函数
线性查找切片中任意给定列表值的索引。 未找到任何值则返回 null。
pub fn findAny(comptime T: type, slice: []const T, values: []const T) ?usize
参数
T: type
slice: []const T
values: []const T
std.mem.findAnyPos
函数
从给定位置开始,在线性搜索中查找切片内所提供列表中任一值的索引。 若未找到任何值,则返回 null。
pub fn findAnyPos(comptime T: type, slice: []const T, start_index: usize, values: []const T) ?usize
参数
T: type
slice: []const T
start_index: usize
values: []const T
std.mem.findDiff
函数
比较两个切片,返回首个不相等位置的索引。 切片相等则返回 null。
pub fn findDiff(comptime T: type, a: []const T, b: []const T) ?usize
参数
T: type
a: []const T
b: []const T
用法示例
test findDiff {
try testing.expectEqual(null, findDiff(u8, "one", "one"));
try testing.expectEqual(3, findDiff(u8, "one two", "one"));
try testing.expectEqual(3, findDiff(u8, "one", "one two"));
try testing.expectEqual(6, findDiff(u8, "one twx", "one two"));
try testing.expectEqual(0, findDiff(u8, "xne", "one"));
const x: [3]f64 = .{ 42.0, math.nan(f64), 3.1415 };
try testing.expectEqual(1, findDiff(f64, &x, &x));
}
std.mem.findLast
函数
从末尾向前搜索,查找子切片在切片中的索引。
要从其他索引开始搜索,请先对待搜索数据取切片。
较大输入使用反向 Boyer-Moore-Horspool 算法;
较小输入使用 lastIndexOfLinear。
pub fn findLast(comptime T: type, haystack: []const T, needle: []const T) ?usize
参数
T: type
haystack: []const T
needle: []const T
std.mem.findLastAny
函数
线性搜索切片中所提供列表内任一值的最后一个索引。 若未找到任何值,则返回 null。
pub fn findLastAny(comptime T: type, slice: []const T, values: []const T) ?usize
参数
T: type
slice: []const T
values: []const T
std.mem.findLastLinear
函数
从末尾向前搜索,查找子切片在切片中的索引。
若要从其他索引开始搜索,请先对被搜索切片进行切片。
可考虑改用 lastIndexOf,它会在输入较大时
自动采用更精细的算法。
pub fn findLastLinear(comptime T: type, haystack: []const T, needle: []const T) ?usize
参数
T: type
haystack: []const T
needle: []const T
std.mem.findLastNone
函数
查找 slice 中最后一个不包含在 values 中的元素。
类似于 C 标准库的 strspn,但从末尾搜索。
pub fn findLastNone(comptime T: type, slice: []const T, values: []const T) ?usize
参数
T: type
slice: []const T
values: []const T
std.mem.findMax
函数
返回切片中最大数的索引。O(n)。
slice 不得为空。
pub fn findMax(comptime T: type, slice: []const T) usize
参数
T: type
slice: []const T
用法示例
test findMax {
try testing.expectEqual(findMax(u8, "abcdefg"), 6);
try testing.expectEqual(findMax(u8, "gabcdef"), 0);
try testing.expectEqual(findMax(u8, "a"), 0);
}
std.mem.findMin
函数
返回切片中最小数的索引。O(n)。
slice 不得为空。
pub fn findMin(comptime T: type, slice: []const T) usize
参数
T: type
slice: []const T
用法示例
test findMin {
try testing.expectEqual(findMin(u8, "abcdefg"), 0);
try testing.expectEqual(findMin(u8, "bcdefga"), 6);
try testing.expectEqual(findMin(u8, "a"), 0);
}
std.mem.findMinMax
类型函数
查找切片中最小值和最大值的索引。O(n)。
按最小值索引、最大值索引的顺序返回。
slice 不得为空。
pub fn findMinMax(comptime T: type, slice: []const T) struct { usize, usize }
参数
T: type
slice: []const T
用法示例
test findMinMax {
try testing.expectEqual(.{ 0, 6 }, findMinMax(u8, "abcdefg"));
try testing.expectEqual(.{ 1, 0 }, findMinMax(u8, "gabcdef"));
try testing.expectEqual(.{ 0, 0 }, findMinMax(u8, "a"));
}
std.mem.findNone
函数
查找 slice 中首个不包含于 values 的元素。
类似 C 标准库中的 strspn。
pub fn findNone(comptime T: type, slice: []const T, values: []const T) ?usize
参数
T: type
slice: []const T
values: []const T
用法示例
test findNone {
try testing.expect(findNone(u8, "abc123", "123").? == 0);
try testing.expect(findLastNone(u8, "abc123", "123").? == 2);
try testing.expect(findNone(u8, "123abc", "123").? == 3);
try testing.expect(findLastNone(u8, "123abc", "123").? == 5);
try testing.expect(findNone(u8, "123123", "123") == null);
try testing.expect(findNone(u8, "333333", "123") == null);
try testing.expect(findNonePos(u8, "abc123", 3, "321") == null);
}
std.mem.findNonePos
函数
查找 slice[start_index..] 中第一个不包含在 values 内的元素。
返回索引相对于 slice 的起始位置,绝不会小于 start_index。
类似于 C 标准库的 strspn。
pub fn findNonePos(comptime T: type, slice: []const T, start_index: usize, values: []const T) ?usize
参数
T: type
slice: []const T
start_index: usize
values: []const T
std.mem.findPos
函数
对大输入使用 Boyer-Moore-Horspool 算法;对小输入使用 findPosLinear。
pub fn findPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize
参数
T: type
haystack: []const T
start_index: usize
needle: []const T
std.mem.findPosLinear
函数
可考虑改用 findPos,它会对较大的输入
自动使用更精细的算法。
pub fn findPosLinear(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize
参数
T: type
haystack: []const T
start_index: usize
needle: []const T
用法示例
test findPosLinear {
try testing.expectEqual(0, findPosLinear(u8, "", 0, ""));
try testing.expectEqual(0, findPosLinear(u8, "123", 0, ""));
try testing.expectEqual(null, findPosLinear(u8, "", 0, "1"));
try testing.expectEqual(0, findPosLinear(u8, "1", 0, "1"));
try testing.expectEqual(null, findPosLinear(u8, "2", 0, "1"));
try testing.expectEqual(1, findPosLinear(u8, "21", 0, "1"));
try testing.expectEqual(null, findPosLinear(u8, "222", 0, "1"));
try testing.expectEqual(null, findPosLinear(u8, "", 0, "12"));
try testing.expectEqual(null, findPosLinear(u8, "1", 0, "12"));
try testing.expectEqual(null, findPosLinear(u8, "2", 0, "12"));
try testing.expectEqual(0, findPosLinear(u8, "12", 0, "12"));
try testing.expectEqual(null, findPosLinear(u8, "21", 0, "12"));
try testing.expectEqual(1, findPosLinear(u8, "212", 0, "12"));
try testing.expectEqual(0, findPosLinear(u8, "122", 0, "12"));
try testing.expectEqual(1, findPosLinear(u8, "212112", 0, "12"));
}
std.mem.findScalar
函数
线性查找切片中标量值的索引。
pub fn findScalar(comptime T: type, slice: []const T, value: T) ?usize
参数
T: type
slice: []const T
value: T
std.mem.findScalarLast
函数
线性搜索标量值在切片中最后一次出现的索引。
pub fn findScalarLast(comptime T: type, slice: []const T, value: T) ?usize
参数
T: type
slice: []const T
value: T
std.mem.findScalarPos
函数
从给定位置开始,线性查找切片中标量值的索引。 未找到该值则返回 null。
pub fn findScalarPos(comptime T: type, slice: []const T, start_index: usize, value: T) ?usize
参数
T: type
slice: []const T
start_index: usize
value: T
用法示例
test findScalarPos {
const Types = [_]type{ u8, u16, u32, u64 };
inline for (Types) |T| {
var memory: [64 / @sizeOf(T)]T = undefined;
@memset(&memory, 0xaa);
memory[memory.len - 1] = 0;
for (0..memory.len) |i| {
try testing.expectEqual(memory.len - i - 1, findScalarPos(T, memory[i..], 0, 0).?);
}
}
}
std.mem.findSentinel
函数
返回以哨兵终止的指针中哨兵值的索引。 线性搜索内存,直到找到哨兵。
pub fn findSentinel(comptime T: type, comptime sentinel: T, p: [*:sentinel]const T) usize
参数
T: type
sentinel: T
p: [*:sentinel]const T
std.mem.indexOf
别名
已弃用,请使用 find。
别名目标 std.mem.find
std.mem.indexOfAny
别名
已弃用,改用 findAny。
别名目标 std.mem.findAny
std.mem.indexOfAnyPos
别名
已弃用,请改用 findAnyPos。
别名目标 std.mem.findAnyPos
std.mem.indexOfDiff
别名
已弃用,改用 findDiff。
别名目标 std.mem.findDiff
std.mem.indexOfMax
别名
别名目标 std.mem.findMax
std.mem.indexOfMin
别名
已弃用,改用 findMin。
别名目标 std.mem.findMin
std.mem.indexOfMinMax
别名
已弃用,改用 findMinMax。
别名目标 std.mem.findMinMax
std.mem.indexOfNone
别名
已弃用,请使用 findNone。
别名目标 std.mem.findNone
std.mem.indexOfNonePos
别名
别名目标 std.mem.findNonePos
std.mem.indexOfPos
别名
已弃用,改用 findPos。
别名目标 std.mem.findPos
std.mem.indexOfPosLinear
别名
std.mem.indexOfScalar
别名
已弃用,改用 findScalar。
别名目标 std.mem.findScalar
std.mem.indexOfScalarPos
别名
已弃用,改用 findScalarPos。
std.mem.indexOfSentinel
别名
已弃用,改用 findSentinel。
别名目标 std.mem.findSentinel
std.mem.isAligned
函数
给定地址和对齐值,若地址为对齐值的倍数,则返回 true。 对齐值必须是大于 0 的 2 的幂。
pub fn isAligned(addr: usize, alignment: usize) bool
参数
addr: usize
alignment: usize
用法示例
test isAligned {
try testing.expect(isAligned(0, 4));
try testing.expect(isAligned(1, 1));
try testing.expect(isAligned(2, 1));
try testing.expect(isAligned(2, 2));
try testing.expect(!isAligned(2, 4));
try testing.expect(isAligned(3, 1));
try testing.expect(!isAligned(3, 2));
try testing.expect(!isAligned(3, 4));
try testing.expect(isAligned(4, 4));
try testing.expect(isAligned(4, 2));
try testing.expect(isAligned(4, 1));
try testing.expect(!isAligned(4, 8));
try testing.expect(!isAligned(4, 16));
}
std.mem.isAlignedAnyAlign
函数
若 i 按给定对齐值对齐,则返回 true。
适用于任意正对齐值,不限于 2 的幂。
对 2 的幂对齐值,isAligned 更高效。
pub fn isAlignedAnyAlign(i: usize, alignment: usize) bool
参数
i: usize
alignment: usize
std.mem.isAlignedGeneric
函数
isAligned 的泛型版本,适用于任意整数类型。
若 addr 按给定对齐值对齐,则返回 true。
对齐值必须为大于 0 的 2 的幂。
pub fn isAlignedGeneric(comptime T: type, addr: T, alignment: T) bool
参数
T: type
addr: T
alignment: T
std.mem.isAlignedLog2
函数
若 addr 按 2^log2_alignment 对齐,则返回 true。
已知对齐量为 2 的幂时,比 isAligned 更高效。
log2_alignment 必须 < @bitSizeOf(usize)。
pub fn isAlignedLog2(addr: usize, log2_alignment: u8) bool
参数
addr: usize
log2_alignment: u8
std.mem.isValidAlign
函数
返回 alignment 是否为有效对齐值,即正数 2 的幂。
pub fn isValidAlign(alignment: usize) bool
参数
alignment: usize
std.mem.isValidAlignGeneric
函数
返回 alignment 是否为有效对齐值,即正数 2 的幂。
pub fn isValidAlignGeneric(comptime T: type, alignment: T) bool
参数
T: type
alignment: T
std.mem.join
函数
直接使用分隔符合并一系列切片。 为结果分配内存,必须由调用者释放。
pub fn join(allocator: Allocator, separator: []const u8, slices: []const []const u8) Allocator.Error![]u8
参数
错误
- OutOfMemory
用法示例
test join {
{
const str = try join(testing.allocator, ",", &[_][]const u8{});
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, ""));
}
{
const str = try join(testing.allocator, ",", &[_][]const u8{ "a", "b", "c" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a,b,c"));
}
{
const str = try join(testing.allocator, ",", &[_][]const u8{"a"});
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a"));
}
{
const str = try join(testing.allocator, ",", &[_][]const u8{ "a", "", "b", "", "c" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a,,b,,c"));
}
}
std.mem.joinMaybeZ
函数
fn joinMaybeZ(allocator: Allocator, separator: []const u8, slices: []const []const u8, zero: bool) Allocator.Error![]u8
参数
错误
- OutOfMemory
std.mem.joinZ
函数
直接用分隔符连接一系列切片,并添加空终止符。 为结果分配内存,调用方必须释放。
pub fn joinZ(allocator: Allocator, separator: []const u8, slices: []const []const u8) Allocator.Error![:0]u8
参数
错误
- OutOfMemory
用法示例
test joinZ {
{
const str = try joinZ(testing.allocator, ",", &[_][]const u8{});
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, ""));
try testing.expectEqual(str[str.len], 0);
}
{
const str = try joinZ(testing.allocator, ",", &[_][]const u8{ "a", "b", "c" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a,b,c"));
try testing.expectEqual(str[str.len], 0);
}
{
const str = try joinZ(testing.allocator, ",", &[_][]const u8{"a"});
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a"));
try testing.expectEqual(str[str.len], 0);
}
{
const str = try joinZ(testing.allocator, ",", &[_][]const u8{ "a", "", "b", "", "c" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a,,b,,c"));
try testing.expectEqual(str[str.len], 0);
}
}
std.mem.lastIndexOf
别名
已弃用,请使用 find。
别名目标 std.mem.findLast
std.mem.lastIndexOfAny
别名
已弃用,改用 findLastAny。
别名目标 std.mem.findLastAny
std.mem.lastIndexOfLinear
别名
已弃用,改用 findLastLinear。
std.mem.lastIndexOfNone
别名
已弃用,请改用 findLastNone。
别名目标 std.mem.findLastNone
std.mem.lastIndexOfScalar
别名
已弃用,请改用 findScalarLast。
std.mem.len
函数
接收哨兵终止指针,遍历内存以查找
哨兵并确定长度。
假定 [*c] 指针非空且以 0 终止。
pub fn len(value: anytype) usize
用法示例
test len {
var array: [5]u16 = [_]u16{ 1, 2, 0, 4, 5 };
const ptr = @as([*:4]u16, array[0..3 :4]);
try testing.expect(len(ptr) == 3);
const c_ptr = @as([*c]u16, ptr);
try testing.expect(len(c_ptr) == 2);
}
std.mem.lenSliceTo
函数
sliceTo() 的私有辅助函数。若需要长度,请使用 sliceTo(foo, x).len。
fn lenSliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) usize
参数
用法示例
test lenSliceTo {
try testing.expect(lenSliceTo("aoeu", 0) == 4);
{
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqual(@as(usize, 5), lenSliceTo(&array, 0));
try testing.expectEqual(@as(usize, 3), lenSliceTo(array[0..3], 0));
try testing.expectEqual(@as(usize, 2), lenSliceTo(&array, 3));
try testing.expectEqual(@as(usize, 2), lenSliceTo(array[0..3], 3));
const sentinel_ptr = @as([*:5]u16, @ptrCast(&array));
try testing.expectEqual(@as(usize, 2), lenSliceTo(sentinel_ptr, 3));
try testing.expectEqual(@as(usize, 4), lenSliceTo(sentinel_ptr, 99));
const c_ptr = @as([*c]u16, &array);
try testing.expectEqual(@as(usize, 2), lenSliceTo(c_ptr, 3));
const slice: []u16 = &array;
try testing.expectEqual(@as(usize, 2), lenSliceTo(slice, 3));
try testing.expectEqual(@as(usize, 5), lenSliceTo(slice, 99));
const sentinel_slice: [:5]u16 = array[0..4 :5];
try testing.expectEqual(@as(usize, 2), lenSliceTo(sentinel_slice, 3));
try testing.expectEqual(@as(usize, 4), lenSliceTo(sentinel_slice, 99));
}
{
var sentinel_array: [5:0]u16 = [_:0]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqual(@as(usize, 2), lenSliceTo(&sentinel_array, 3));
try testing.expectEqual(@as(usize, 5), lenSliceTo(&sentinel_array, 0));
try testing.expectEqual(@as(usize, 5), lenSliceTo(&sentinel_array, 99));
}
}
std.mem.lessThan
函数
若 lhs < rhs 则返回 true,否则返回 false
pub fn lessThan(comptime T: type, lhs: []const T, rhs: []const T) bool
参数
T: type
lhs: []const T
rhs: []const T
用法示例
test lessThan {
try testing.expect(lessThan(u8, "abcd", "bee"));
try testing.expect(!lessThan(u8, "abc", "abc"));
try testing.expect(lessThan(u8, "abc", "abc0"));
try testing.expect(!lessThan(u8, "", ""));
try testing.expect(lessThan(u8, "", "a"));
}
std.mem.lessThanZ
函数
当 lhs < rhs 时返回 true,否则返回 false;操作对象为以空字符终止的数组。
pub fn lessThanZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T) bool
参数
T: type
lhs: [*:0]const T
rhs: [*:0]const T
用法示例
test lessThanZ {
try testing.expect(lessThanZ(u8, "abcd", "bee"));
try testing.expect(!lessThanZ(u8, "abc", "abc"));
try testing.expect(lessThanZ(u8, "abc", "abc0"));
try testing.expect(!lessThanZ(u8, "", ""));
try testing.expect(lessThanZ(u8, "", "a"));
}
std.mem.littleToNative
函数
将小端序整数转换为主机字节序。
pub fn littleToNative(comptime T: type, x: T) T
参数
T: type
x: T
std.mem.math
别名
别名目标 std.math
std.mem.max
函数
返回切片中的最大数。O(n)。
slice 不得为空。
pub fn max(comptime T: type, slice: []const T) T
参数
T: type
slice: []const T
用法示例
test max {
try testing.expectEqual(max(u8, "abcdefg"), 'g');
try testing.expectEqual(max(u8, "gabcdef"), 'g');
try testing.expectEqual(max(u8, "g"), 'g');
}
std.mem.mem
别名
别名目标 std.mem
std.mem.min
函数
返回切片中的最小值。时间复杂度 O(n)。
slice 不得为空。
pub fn min(comptime T: type, slice: []const T) T
参数
T: type
slice: []const T
用法示例
test min {
try testing.expectEqual(min(u8, "abcdefg"), 'a');
try testing.expectEqual(min(u8, "bcdefga"), 'a');
try testing.expectEqual(min(u8, "a"), 'a');
}
std.mem.minMax
类型函数
pub fn minMax(comptime T: type, slice: []const T) struct { T, T }
参数
T: type
slice: []const T
用法示例
test minMax {
{
const actual_min, const actual_max = minMax(u8, "abcdefg");
try testing.expectEqual(@as(u8, 'a'), actual_min);
try testing.expectEqual(@as(u8, 'g'), actual_max);
}
{
const actual_min, const actual_max = minMax(u8, "bcdefga");
try testing.expectEqual(@as(u8, 'a'), actual_min);
try testing.expectEqual(@as(u8, 'g'), actual_max);
}
{
const actual_min, const actual_max = minMax(u8, "a");
try testing.expectEqual(@as(u8, 'a'), actual_min);
try testing.expectEqual(@as(u8, 'a'), actual_max);
}
}
std.mem.moreReadIntTests
函数
fn moreReadIntTests() !void
std.mem.native_endian
常量
std.mem.nativeTo
函数
将采用宿主端序的整数转换为所需端序。
pub fn nativeTo(comptime T: type, x: T, desired_endianness: Endian) T
参数
std.mem.nativeToBig
函数
将采用主机字节序的整数转换为大端字节序。
pub fn nativeToBig(comptime T: type, x: T) T
参数
T: type
x: T
std.mem.nativeToLittle
函数
将采用宿主端序的整数转换为小端序。
pub fn nativeToLittle(comptime T: type, x: T) T
参数
T: type
x: T
std.mem.order
函数
按字典序比较两个数值切片。O(n)。
pub fn order(comptime T: type, lhs: []const T, rhs: []const T) math.Order
参数
T: type
lhs: []const T
rhs: []const T
用法示例
test order {
try testing.expect(order(u8, "abcd", "bee") == .lt);
try testing.expect(order(u8, "abc", "abc") == .eq);
try testing.expect(order(u8, "abc", "abc0") == .lt);
try testing.expect(order(u8, "", "") == .eq);
try testing.expect(order(u8, "", "a") == .lt);
const s: []const u8 = "abc";
try testing.expect(order(u8, s, s) == .eq);
try testing.expect(order(u8, s[0..2], s) == .lt);
}
std.mem.orderZ
函数
按字典序比较两个以 NUL 结尾的多元素指针。
pub fn orderZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T) math.Order
参数
T: type
lhs: [*:0]const T
rhs: [*:0]const T
用法示例
test orderZ {
try testing.expect(orderZ(u8, "abcd", "bee") == .lt);
try testing.expect(orderZ(u8, "abc", "abc") == .eq);
try testing.expect(orderZ(u8, "abc", "abc0") == .lt);
try testing.expect(orderZ(u8, "", "") == .eq);
try testing.expect(orderZ(u8, "", "a") == .lt);
const s: [*:0]const u8 = "abc";
try testing.expect(orderZ(u8, s, s) == .eq);
}
std.mem.print
函数
将格式化字符串写入 buffer。返回从 buffer
索引 0 开始、包含结果的切片;若截断了一个或多个字节,
则返回 error.NoSpaceLeft。
pub fn print(buffer: []u8, comptime format: []const u8, args: anytype) PrintError![]u8
参数
buffer: []u8
format: []const u8
错误
- NoSpaceLeft
已尽量向缓冲区写入数据,但缓冲区太小, 无法容纳所有打印字节。
用法示例
test print {
const x: i32 = -1;
const y: []const u8 = "hi";
var buffer: [64]u8 = undefined;
const s = try print(&buffer, "{d}={s}", .{ x, y });
try testing.expectEqualStrings("-1=hi", s);
}
std.mem.PrintError
错误集合
错误
- NoSpaceLeft
已尽量向缓冲区写入数据,但缓冲区太小, 无法容纳所有打印字节。
std.mem.printSentinel
函数
类似 print,但返回切片带有所提供的哨兵值。
pub fn printSentinel( buffer: []u8, comptime format: []const u8, args: anytype, comptime sentinel: u8, ) PrintError![:sentinel]u8
参数
buffer: []u8
format: []const u8
sentinel: u8
错误
- NoSpaceLeft
已尽量向缓冲区写入数据,但缓冲区太小, 无法容纳所有打印字节。
用法示例
test printSentinel {
const x: i32 = -1;
const y: []const u8 = "hi";
var buffer: [64]u8 = undefined;
const s = try printSentinel(&buffer, "{d}={s}", .{ x, y }, 0);
try testing.expectEqualStrings("-1=hi", s);
try testing.expectEqual(0, s[s.len]);
}
std.mem.readInt
函数
从内存读取整数,其比特数由 T 指定。 T 的比特数必须可被 8 整除。 此函数不会失败,也不会导致未定义行为。
pub inline fn readInt(comptime T: type, buffer: *const [@divExact(@typeInfo(T).int.bits, 8)]u8, endian: Endian) T
参数
用法示例
test readInt {
try testing.expect(readInt(u0, &[_]u8{}, .big) == 0x0);
try testing.expect(readInt(u0, &[_]u8{}, .little) == 0x0);
try testing.expect(readInt(u8, &[_]u8{0x32}, .big) == 0x32);
try testing.expect(readInt(u8, &[_]u8{0x12}, .little) == 0x12);
try testing.expect(readInt(u16, &[_]u8{ 0x12, 0x34 }, .big) == 0x1234);
try testing.expect(readInt(u16, &[_]u8{ 0x12, 0x34 }, .little) == 0x3412);
try testing.expect(readInt(u72, &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 }, .big) == 0x123456789abcdef024);
try testing.expect(readInt(u72, &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe }, .little) == 0xfedcba9876543210ec);
try testing.expect(readInt(i8, &[_]u8{0xff}, .big) == -1);
try testing.expect(readInt(i8, &[_]u8{0xfe}, .little) == -2);
try testing.expect(readInt(i16, &[_]u8{ 0xff, 0xfd }, .big) == -3);
try testing.expect(readInt(i16, &[_]u8{ 0xfc, 0xff }, .little) == -4);
try moreReadIntTests();
try comptime moreReadIntTests();
}
std.mem.readPackedInt
函数
从打包内存中加载整数。 断言缓冲区至少包含 bit_offset + @bitSizeOf(T) 位。
pub fn readPackedInt(comptime T: type, bytes: []const u8, bit_offset: usize, endian: Endian) T
参数
用法示例
test readPackedInt {
const T = packed struct(u16) { a: u3, b: u7, c: u6 };
var st = T{ .a = 1, .b = 2, .c = 4 };
const b_field = readPackedInt(u7, std.mem.asBytes(&st), @bitOffsetOf(T, "b"), builtin.cpu.arch.endian());
try std.testing.expectEqual(st.b, b_field);
}
std.mem.readPackedIntBig
函数
fn readPackedIntBig(comptime T: type, bytes: []const u8, bit_offset: usize) T
参数
T: type
bytes: []const u8
bit_offset: usize
std.mem.readPackedIntLittle
函数
fn readPackedIntLittle(comptime T: type, bytes: []const u8, bit_offset: usize) T
参数
T: type
bytes: []const u8
bit_offset: usize
std.mem.readVarInt
函数
从内存中读取大小等于 bytes.len 的整数。 ReturnType 指定返回类型,且必须足够大以存储结果。
pub fn readVarInt(comptime ReturnType: type, bytes: []const u8, endian: Endian) ReturnType
参数
用法示例
test readVarInt {
try testing.expect(readVarInt(u0, &[_]u8{}, .big) == 0x0);
try testing.expect(readVarInt(u0, &[_]u8{}, .little) == 0x0);
try testing.expect(readVarInt(u8, &[_]u8{0x12}, .big) == 0x12);
try testing.expect(readVarInt(u8, &[_]u8{0xde}, .little) == 0xde);
try testing.expect(readVarInt(u16, &[_]u8{ 0x12, 0x34 }, .big) == 0x1234);
try testing.expect(readVarInt(u16, &[_]u8{ 0x12, 0x34 }, .little) == 0x3412);
try testing.expect(readVarInt(i8, &[_]u8{0xff}, .big) == -1);
try testing.expect(readVarInt(i8, &[_]u8{0xfe}, .little) == -2);
try testing.expect(readVarInt(i16, &[_]u8{ 0xff, 0xfd }, .big) == -3);
try testing.expect(readVarInt(i16, &[_]u8{ 0xfc, 0xff }, .little) == -4);
// 返回类型可以大于所需大小(bytes.len * 8 < @typeInfo(ReturnType).int.bits)
try testing.expect(readVarInt(u9, &[_]u8{0x12}, .little) == 0x12);
try testing.expect(readVarInt(u9, &[_]u8{0xde}, .big) == 0xde);
try testing.expect(readVarInt(u80, &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 }, .big) == 0x123456789abcdef024);
try testing.expect(readVarInt(u80, &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe }, .little) == 0xfedcba9876543210ec);
try testing.expect(readVarInt(i9, &[_]u8{0xff}, .big) == 0xff);
try testing.expect(readVarInt(i9, &[_]u8{0xfe}, .little) == 0xfe);
}
std.mem.readVarPackedInt
函数
按给定 bit_count、bit_offset 和有符号性,从紧凑内存加载整数。 断言 T 足够大,能存储读取的值。
pub fn readVarPackedInt( comptime T: type, bytes: []const u8, bit_offset: usize, bit_count: usize, endian: std.builtin.Endian, signedness: std.builtin.Signedness, ) T
参数
T: type
bytes: []const u8
bit_offset: usize
bit_count: usize
endian: std.builtin.Endian
signedness: std.builtin.Signedness
用法示例
test readVarPackedInt {
const T = packed struct(u16) { a: u3, b: u7, c: u6 };
var st = T{ .a = 1, .b = 2, .c = 4 };
const b_field = readVarPackedInt(u64, std.mem.asBytes(&st), @bitOffsetOf(T, "b"), 7, builtin.cpu.arch.endian(), .unsigned);
try std.testing.expectEqual(st.b, b_field);
}
std.mem.replace
函数
尽可能多次将 needle 替换为 replacement,并写入假定大小合适的输出缓冲区。使用 replacementSize 计算适当缓冲区大小。
input 与 output 切片不得重叠。
needle 不得为空。
返回实际替换次数。
pub fn replace(comptime T: type, input: []const T, needle: []const T, replacement: []const T, output: []T) usize
参数
T: type
input: []const T
needle: []const T
replacement: []const T
output: []T
用法示例
test replace {
var output: [29]u8 = undefined;
var replacements = replace(u8, "All your base are belong to us", "base", "Zig", output[0..]);
var expected: []const u8 = "All your Zig are belong to us";
try testing.expect(replacements == 1);
try testing.expectEqualStrings(expected, output[0..expected.len]);
replacements = replace(u8, "Favor reading code over writing code.", "code", "", output[0..]);
expected = "Favor reading over writing .";
try testing.expect(replacements == 2);
try testing.expectEqualStrings(expected, output[0..expected.len]);
// 不允许空 needle,但输入可以为空。
replacements = replace(u8, "", "x", "y", output[0..0]);
expected = "";
try testing.expect(replacements == 0);
try testing.expectEqualStrings(expected, output[0..expected.len]);
// 相邻替换。
replacements = replace(u8, "\\n\\n", "\\n", "\n", output[0..]);
expected = "\n\n";
try testing.expect(replacements == 2);
try testing.expectEqualStrings(expected, output[0..expected.len]);
replacements = replace(u8, "abbba", "b", "cd", output[0..]);
expected = "acdcdcda";
try testing.expect(replacements == 3);
try testing.expectEqualStrings(expected, output[0..expected.len]);
}
std.mem.replacementSize
函数
计算执行替换所需的输出缓冲区大小。 待查找内容不得为空。
pub fn replacementSize(comptime T: type, input: []const T, needle: []const T, replacement: []const T) usize
参数
T: type
input: []const T
needle: []const T
replacement: []const T
用法示例
test replacementSize {
try testing.expect(replacementSize(u8, "All your base are belong to us", "base", "Zig") == 29);
try testing.expect(replacementSize(u8, "Favor reading code over writing code.", "code", "") == 29);
try testing.expect(replacementSize(u8, "Only one obvious way to do things.", "things.", "things in Zig.") == 41);
// 不允许空 needle,但输入可以为空。
try testing.expect(replacementSize(u8, "", "x", "y") == 0);
// 相邻替换。
try testing.expect(replacementSize(u8, "\\n\\n", "\\n", "\n") == 2);
try testing.expect(replacementSize(u8, "abbba", "b", "cd") == 8);
}
std.mem.replaceOwned
函数
在预先确定大小的已分配缓冲区上执行替换。调用方必须释放返回的内存。
pub fn replaceOwned(comptime T: type, allocator: Allocator, input: []const T, needle: []const T, replacement: []const T) Allocator.Error![]T
参数
错误
- OutOfMemory
用法示例
test replaceOwned {
const gpa = std.testing.allocator;
const base_replace = replaceOwned(u8, gpa, "All your base are belong to us", "base", "Zig") catch @panic("out of memory");
defer gpa.free(base_replace);
try testing.expect(eql(u8, base_replace, "All your Zig are belong to us"));
const zen_replace = replaceOwned(u8, gpa, "Favor reading code over writing code.", " code", "") catch @panic("out of memory");
defer gpa.free(zen_replace);
try testing.expect(eql(u8, zen_replace, "Favor reading over writing."));
}
std.mem.replaceScalar
函数
将所有 match 替换为 replacement。
pub fn replaceScalar(comptime T: type, slice: []T, match: T, replacement: T) void
参数
T: type
slice: []T
match: T
replacement: T
std.mem.reverse
函数
原地反转切片顺序
pub fn reverse(comptime T: type, items: []T) void
参数
T: type
items: []T
用法示例
test reverse {
{
var arr = [_]i32{ 5, 3, 1, 2, 4 };
reverse(i32, arr[0..]);
try testing.expectEqualSlices(i32, &arr, &.{ 4, 2, 1, 3, 5 });
}
{
var arr = [_]u0{};
reverse(u0, arr[0..]);
try testing.expectEqualSlices(u0, &arr, &.{});
}
{
var arr = [_]i64{ 19, 17, 15, 13, 11, 9, 7, 5, 3, 1, 2, 4, 6, 8, 10, 12, 14, 16, 18 };
reverse(i64, arr[0..]);
try testing.expectEqualSlices(i64, &arr, &.{ 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 });
}
{
var arr = [_][]const u8{ "a", "b", "c", "d" };
reverse([]const u8, arr[0..]);
try testing.expectEqualSlices([]const u8, &arr, &.{ "d", "c", "b", "a" });
}
{
const MyType = union(enum) {
a: [3]u8,
b: u24,
c,
};
var arr = [_]MyType{ .{ .a = .{ 0, 0, 0 } }, .{ .b = 0 }, .c };
reverse(MyType, arr[0..]);
try testing.expectEqualSlices(MyType, &arr, &([_]MyType{ .c, .{ .b = 0 }, .{ .a = .{ 0, 0, 0 } } }));
}
}
std.mem.reverseIterator
函数
反向遍历切片。
pub fn reverseIterator(slice: anytype) ReverseIterator(@TypeOf(slice))
用法示例
test reverseIterator {
{
var it = reverseIterator("abc");
try testing.expectEqual(@as(?u8, 'c'), it.next());
try testing.expectEqual(@as(?u8, 'b'), it.next());
try testing.expectEqual(@as(?u8, 'a'), it.next());
try testing.expectEqual(@as(?u8, null), it.next());
}
{
var array = [2]i32{ 3, 7 };
const slice: []const i32 = &array;
var it = reverseIterator(slice);
try testing.expectEqual(@as(?i32, 7), it.next());
try testing.expectEqual(@as(?i32, 3), it.next());
try testing.expectEqual(@as(?i32, null), it.next());
it = reverseIterator(slice);
try testing.expect(*const i32 == @TypeOf(it.nextPtr().?));
try testing.expectEqual(@as(?i32, 7), it.nextPtr().?.*);
try testing.expectEqual(@as(?i32, 3), it.nextPtr().?.*);
try testing.expectEqual(@as(?*const i32, null), it.nextPtr());
const mut_slice: []i32 = &array;
var mut_it = reverseIterator(mut_slice);
mut_it.nextPtr().?.* += 1;
mut_it.nextPtr().?.* += 2;
try testing.expectEqual([2]i32{ 5, 8 }, array);
}
{
var array = [2]i32{ 3, 7 };
const ptr_to_array: *const [2]i32 = &array;
var it = reverseIterator(ptr_to_array);
try testing.expectEqual(@as(?i32, 7), it.next());
try testing.expectEqual(@as(?i32, 3), it.next());
try testing.expectEqual(@as(?i32, null), it.next());
it = reverseIterator(ptr_to_array);
try testing.expect(*const i32 == @TypeOf(it.nextPtr().?));
try testing.expectEqual(@as(?i32, 7), it.nextPtr().?.*);
try testing.expectEqual(@as(?i32, 3), it.nextPtr().?.*);
try testing.expectEqual(@as(?*const i32, null), it.nextPtr());
const mut_ptr_to_array: *[2]i32 = &array;
var mut_it = reverseIterator(mut_ptr_to_array);
mut_it.nextPtr().?.* += 1;
mut_it.nextPtr().?.* += 2;
try testing.expectEqual([2]i32{ 5, 8 }, array);
}
}
std.mem.ReverseIterator
类型函数
由 reverseIterator 返回。
pub fn ReverseIterator(comptime T: type) type
参数
T: type
字段
ptr: Pointer
index: usize
std.mem.ReverseIterator.next
函数
pub fn next(self: *@This()) ?Element
参数
self: *@This()
std.mem.ReverseIterator.nextPtr
函数
pub fn nextPtr(self: *@This()) ?ElementPointer
参数
self: *@This()
std.mem.reverseVector
函数
inline fn reverseVector(comptime N: usize, comptime T: type, a: []T) [N]T
参数
N: usize
T: type
a: []T
std.mem.rotate
函数
原地旋转数组中的值(旋转 1 位时,[0 1 2 3] 变为 [1 2 3 0]) 假定 0 <= amount <= items.len
pub fn rotate(comptime T: type, items: []T, amount: usize) void
参数
T: type
items: []T
amount: usize
用法示例
test rotate {
var arr = [_]i32{ 5, 3, 1, 2, 4 };
rotate(i32, arr[0..], 2);
try testing.expect(eql(i32, &arr, &[_]i32{ 1, 2, 4, 5, 3 }));
}
std.mem.sliceAsBytes
函数
给定切片,返回底层字节的切片,并保留指针属性。
pub fn sliceAsBytes(slice: anytype) SliceAsBytesReturnType(@TypeOf(slice))
用法示例
test sliceAsBytes {
const bytes = [_]u16{ 0xDEAD, 0xBEEF };
const slice = sliceAsBytes(bytes[0..]);
try testing.expect(slice.len == 4);
try testing.expect(eql(u8, slice, switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xAD\xDE\xEF\xBE",
}));
}
std.mem.SliceAsBytesReturnType
类型函数
fn SliceAsBytesReturnType(comptime Slice: type) type
参数
Slice: type
std.mem.sliceTo
函数
接受数组指针、多元素指针或切片,返回截止第一次出现 end 之前的元素切片。
若未找到 end,结果切片包含直到输入长度或哨兵之前的全部元素。
若指针类型没有边界,即没有长度或哨兵,则 end 将作为结果切片的哨兵。
若指针类型以 end 作为终止哨兵,结果切片也以 end 作为终止哨兵。
保留可变性、对齐等指针属性。
假定 C 指针非空。
pub fn sliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) SliceTo(@TypeOf(ptr), end)
参数
用法示例
test sliceTo {
try testing.expectEqualSlices(u8, "aoeu", sliceTo("aoeu", 0));
{
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqualSlices(u16, &array, sliceTo(&array, 0));
try testing.expectEqualSlices(u16, array[0..3], sliceTo(array[0..3], 0));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(&array, 3));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(array[0..3], 3));
const many_ptr: [*]u16 = &array;
try testing.expectEqualSlices(u16, array[0..2], sliceTo(many_ptr, 3));
try testing.expectEqual([:3]u16, @TypeOf(sliceTo(many_ptr, 3)));
const sentinel_ptr = @as([*:5]u16, @ptrCast(&array));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(sentinel_ptr, 3));
try testing.expectEqual([]u16, @TypeOf(sliceTo(sentinel_ptr, 3)));
try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_ptr, 5));
try testing.expectEqual([:5]u16, @TypeOf(sliceTo(sentinel_ptr, 5)));
try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_ptr, 99));
const optional_sentinel_ptr = @as(?[*:5]u16, @ptrCast(&array));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(optional_sentinel_ptr, 3).?);
try testing.expectEqualSlices(u16, array[0..4], sliceTo(optional_sentinel_ptr, 99).?);
const c_ptr = @as([*c]u16, &array);
try testing.expectEqualSlices(u16, array[0..2], sliceTo(c_ptr, 3));
try testing.expectEqual([:3]u16, @TypeOf(sliceTo(c_ptr, 3)));
const slice: []u16 = &array;
try testing.expectEqualSlices(u16, array[0..2], sliceTo(slice, 3));
try testing.expectEqualSlices(u16, &array, sliceTo(slice, 99));
const sentinel_slice: [:5]u16 = array[0..4 :5];
try testing.expectEqualSlices(u16, array[0..2], sliceTo(sentinel_slice, 3));
try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_slice, 99));
}
{
var sentinel_array: [5:0]u16 = [_:0]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqualSlices(u16, sentinel_array[0..2], sliceTo(&sentinel_array, 3));
try testing.expectEqualSlices(u16, &sentinel_array, sliceTo(&sentinel_array, 0));
try testing.expectEqualSlices(u16, &sentinel_array, sliceTo(&sentinel_array, 99));
}
try testing.expectEqual(@as(?[]u8, null), sliceTo(@as(?[]u8, null), 0));
}
std.mem.SliceTo
类型函数
sliceTo() 返回类型的辅助函数
fn SliceTo(comptime T: type, comptime end: std.meta.Elem(T)) type
参数
std.mem.sort
函数
使用稳定算法原地排序切片,保持相等元素的相对顺序。 平均时间复杂度:O(n log n),最坏情况:O(n log n)。 递归调用的空间复杂度:O(log n)。
对采用默认顺序的原始类型切片,可考虑直接使用 std.sort.block。
不稳定但可能更快的排序参见 sortUnstable。
pub fn sort( comptime T: type, items: []T, context: anytype, comptime lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool, ) void
参数
T: type
items: []T
lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool
std.mem.sortContext
函数
TODO: 目前仅调用 insertionSortContext。此文件中的块排序实现
需要调整为使用排序上下文。
pub fn sortContext(a: usize, b: usize, context: anytype) void
参数
a: usize
b: usize
std.mem.sortUnstable
函数
使用不稳定算法原地排序切片,不保留相等元素的相对顺序。 时间复杂度:最好为 O(n),最坏和平均均为 O(n log n)。 通常比稳定排序快,但相等元素的顺序未定义。
使用破坏模式快速排序(PDQ)算法,在多种数据模式下表现良好。
若需要保留相等元素顺序的稳定排序,请使用 sort。
pub fn sortUnstable( comptime T: type, items: []T, context: anytype, comptime lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool, ) void
参数
T: type
items: []T
lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool
std.mem.sortUnstableContext
函数
使用带自定义上下文的不稳定算法,对范围 [a, b) 排序。 这是使用索引而非切片的底层排序接口。 不保留相等元素的相对顺序。
上下文必须提供 lessThan(a_idx, b_idx) 和 swap(a_idx, b_idx) 方法。 使用模式规避快速排序 PDQ 算法。
pub fn sortUnstableContext(a: usize, b: usize, context: anytype) void
参数
a: usize
b: usize
std.mem.span
函数
接受一个以哨兵值结尾的指针,并遍历内存找到哨兵值、确定长度,
然后返回切片。
保留指针属性,例如 const。
假定 [*c] 指针非空且以 0 结尾。
pub fn span(ptr: anytype) Span(@TypeOf(ptr))
用法示例
test span {
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
const ptr = @as([*:3]u16, array[0..2 :3]);
try testing.expect(eql(u16, span(ptr), &[_]u16{ 1, 2 }));
try testing.expectEqual(@as(?[:0]u16, null), span(@as(?[*:0]u16, null)));
}
std.mem.Span
类型函数
接受以哨兵值结尾的指针,返回保留指针属性的切片。
假定 [*c] 指针以 0 结尾,且不具有 allowzero 属性。
fn Span(comptime T: type) type
参数
T: type
用法示例
test Span {
try testing.expect(Span([*:1]u16) == [:1]u16);
try testing.expect(Span(?[*:1]u16) == ?[:1]u16);
try testing.expect(Span([*:1]const u8) == [:1]const u8);
try testing.expect(Span(?[*:1]const u8) == ?[:1]const u8);
try testing.expect(Span([*c]u16) == [:0]u16);
try testing.expect(Span(?[*c]u16) == ?[:0]u16);
try testing.expect(Span([*c]const u8) == [:0]const u8);
try testing.expect(Span(?[*c]const u8) == ?[:0]const u8);
}
std.mem.splitAny
函数
返回迭代器,遍历 buffer 中由
delimiters 中任意元素分隔的切片。
splitAny(u8, "abc,def||ghi", "|,") 将按顺序返回
切片 "abc"、"def"、""、"ghi"、null。
如果 buffer 中不存在 delimiters 中的任何元素,
迭代器将依次返回 buffer、null。
另请参见:splitSequence、splitScalar、splitBackwardsSequence、
splitBackwardsAny、splitBackwardsScalar、
tokenizeAny、tokenizeSequence、tokenizeScalar。
pub fn splitAny(comptime T: type, buffer: []const T, delimiters: []const T) SplitIterator(T, .any)
参数
T: type
buffer: []const T
delimiters: []const T
用法示例
test splitAny {
var it = splitAny(u8, "a,b, c d e", ", ");
try testing.expectEqualSlices(u8, it.first(), "a");
try testing.expectEqualSlices(u8, it.rest(), "b, c d e");
try testing.expectEqualSlices(u8, it.next().?, "b");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expectEqualSlices(u8, it.next().?, "c");
try testing.expectEqualSlices(u8, it.next().?, "d");
try testing.expectEqualSlices(u8, it.next().?, "e");
try testing.expect(it.next() == null);
it = splitAny(u8, "hello", "");
try testing.expect(eql(u8, it.next().?, "hello"));
try testing.expect(it.next() == null);
var it16 = splitAny(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a,b, c d e"),
std.unicode.utf8ToUtf16LeStringLiteral(", "),
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("a"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral(""));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("e"));
try testing.expect(it16.next() == null);
}
std.mem.splitBackwardsAny
函数
返回迭代器,反向遍历 buffer 中由
delimiters 中任意元素分隔的切片。
splitBackwardsAny(u8, "abc,def||ghi", "|,") 将按顺序返回
切片 "ghi"、""、"def"、"abc"、null。
如果 buffer 中不存在 delimiters 中的任何元素,
迭代器将依次返回 buffer、null。
另请参见:splitBackwardsSequence、splitBackwardsScalar、
splitSequence、splitAny、splitScalar、
tokenizeAny、tokenizeSequence、tokenizeScalar。
pub fn splitBackwardsAny(comptime T: type, buffer: []const T, delimiters: []const T) SplitBackwardsIterator(T, .any)
参数
T: type
buffer: []const T
delimiters: []const T
用法示例
test splitBackwardsAny {
var it = splitBackwardsAny(u8, "a,b, c d e", ", ");
try testing.expectEqualSlices(u8, it.rest(), "a,b, c d e");
try testing.expectEqualSlices(u8, it.first(), "e");
try testing.expectEqualSlices(u8, it.rest(), "a,b, c d");
try testing.expectEqualSlices(u8, it.next().?, "d");
try testing.expectEqualSlices(u8, it.rest(), "a,b, c");
try testing.expectEqualSlices(u8, it.next().?, "c");
try testing.expectEqualSlices(u8, it.rest(), "a,b,");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expectEqualSlices(u8, it.rest(), "a,b");
try testing.expectEqualSlices(u8, it.next().?, "b");
try testing.expectEqualSlices(u8, it.rest(), "a");
try testing.expectEqualSlices(u8, it.next().?, "a");
try testing.expectEqualSlices(u8, it.rest(), "");
try testing.expect(it.next() == null);
var it16 = splitBackwardsAny(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a,b, c d e"),
std.unicode.utf8ToUtf16LeStringLiteral(", "),
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("e"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral(""));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("a"));
try testing.expect(it16.next() == null);
}
std.mem.SplitBackwardsIterator
类型函数
从末尾向前拆分操作的迭代器类型,包括空序列。
pub fn SplitBackwardsIterator(comptime T: type, comptime delimiter_type: DelimiterType) type
参数
T: type
delimiter_type: DelimiterType
字段
buffer: []const T
index: ?usize
delimiter: switch (delimiter_type) {
.sequence, .any => []const T,
.scalar => T,
}
std.mem.SplitBackwardsIterator.first
函数
返回第一个字段的切片。
仅用于获取第一个字段,后续字段均通过 next 获取。
断言迭代尚未开始。
pub fn first(self: *Self) []const T
参数
self: *Self
std.mem.SplitBackwardsIterator.next
函数
返回下一个字段的切片;若拆分已完成,则返回 null。
pub fn next(self: *Self) ?[]const T
参数
self: *Self
std.mem.SplitBackwardsIterator.reset
函数
将迭代器重置到初始切片。
pub fn reset(self: *Self) void
参数
self: *Self
std.mem.SplitBackwardsIterator.rest
函数
返回剩余字节的切片。不影响迭代器状态。
pub fn rest(self: Self) []const T
参数
self: Self
std.mem.SplitBackwardsIterator.Self
别名
std.mem.splitBackwardsScalar
函数
返回迭代器,反向遍历 buffer 中由
delimiter 分隔的切片。
splitBackwardsScalar(u8, "abc|def||ghi", '|') 将按顺序返回
切片 "ghi"、""、"def"、"abc"、null。
如果 buffer 中不存在 delimiter,
迭代器将依次返回 buffer、null。
另请参见:splitBackwardsSequence、splitBackwardsAny、
splitSequence、splitAny、splitScalar、
tokenizeAny、tokenizeSequence、tokenizeScalar。
pub fn splitBackwardsScalar(comptime T: type, buffer: []const T, delimiter: T) SplitBackwardsIterator(T, .scalar)
参数
T: type
buffer: []const T
delimiter: T
用法示例
test splitBackwardsScalar {
var it = splitBackwardsScalar(u8, "abc|def||ghi", '|');
try testing.expectEqualSlices(u8, it.rest(), "abc|def||ghi");
try testing.expectEqualSlices(u8, it.first(), "ghi");
try testing.expectEqualSlices(u8, it.rest(), "abc|def|");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expectEqualSlices(u8, it.rest(), "abc|def");
try testing.expectEqualSlices(u8, it.next().?, "def");
try testing.expectEqualSlices(u8, it.rest(), "abc");
try testing.expectEqualSlices(u8, it.next().?, "abc");
try testing.expectEqualSlices(u8, it.rest(), "");
try testing.expect(it.next() == null);
it = splitBackwardsScalar(u8, "", '|');
try testing.expectEqualSlices(u8, it.first(), "");
try testing.expect(it.next() == null);
it = splitBackwardsScalar(u8, "|", '|');
try testing.expectEqualSlices(u8, it.first(), "");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expect(it.next() == null);
it = splitBackwardsScalar(u8, "hello", ' ');
try testing.expectEqualSlices(u8, it.first(), "hello");
try testing.expect(it.next() == null);
var it16 = splitBackwardsScalar(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("hello"),
' ',
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("hello"));
try testing.expect(it16.next() == null);
}
std.mem.splitBackwardsSequence
函数
返回迭代器,反向遍历 buffer 中由
delimiter 所示序列分隔的切片。
splitBackwardsSequence(u8, "abc||def||||ghi", "||") 将按顺序返回
切片 "ghi"、""、"def"、"abc"、null。
如果 buffer 中不存在 delimiter,
迭代器将依次返回 buffer、null。
分隔符长度不得为零。
另请参见:splitBackwardsAny、splitBackwardsScalar、
splitSequence、splitAny、splitScalar、
tokenizeAny、tokenizeSequence、tokenizeScalar。
pub fn splitBackwardsSequence(comptime T: type, buffer: []const T, delimiter: []const T) SplitBackwardsIterator(T, .sequence)
参数
T: type
buffer: []const T
delimiter: []const T
用法示例
test splitBackwardsSequence {
var it = splitBackwardsSequence(u8, "a, b ,, c, d, e", ", ");
try testing.expectEqualSlices(u8, it.rest(), "a, b ,, c, d, e");
try testing.expectEqualSlices(u8, it.first(), "e");
try testing.expectEqualSlices(u8, it.rest(), "a, b ,, c, d");
try testing.expectEqualSlices(u8, it.next().?, "d");
try testing.expectEqualSlices(u8, it.rest(), "a, b ,, c");
try testing.expectEqualSlices(u8, it.next().?, "c");
try testing.expectEqualSlices(u8, it.rest(), "a, b ,");
try testing.expectEqualSlices(u8, it.next().?, "b ,");
try testing.expectEqualSlices(u8, it.rest(), "a");
try testing.expectEqualSlices(u8, it.next().?, "a");
try testing.expectEqualSlices(u8, it.rest(), "");
try testing.expect(it.next() == null);
var it16 = splitBackwardsSequence(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a, b ,, c, d, e"),
std.unicode.utf8ToUtf16LeStringLiteral(", "),
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("e"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b ,"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("a"));
try testing.expect(it16.next() == null);
}
std.mem.SplitIterator
类型函数
拆分操作的迭代器类型,包含分隔符之间的空序列。
pub fn SplitIterator(comptime T: type, comptime delimiter_type: DelimiterType) type
参数
T: type
delimiter_type: DelimiterType
字段
buffer: []const T
index: ?usize
delimiter: switch (delimiter_type) {
.sequence, .any => []const T,
.scalar => T,
}
std.mem.SplitIterator.first
函数
返回第一个字段的切片。
仅用于获取第一个字段,后续字段均通过 next 获取。
断言迭代尚未开始。
pub fn first(self: *Self) []const T
参数
self: *Self
std.mem.SplitIterator.next
函数
返回下一个字段的切片;若拆分已完成,则返回 null。
pub fn next(self: *Self) ?[]const T
参数
self: *Self
std.mem.SplitIterator.peek
函数
返回下一个字段的切片;若拆分完成,则返回 null。 此方法不改变 self.index。
pub fn peek(self: *const Self) ?[]const T
参数
self: *const Self
std.mem.SplitIterator.reset
函数
将迭代器重置到初始切片。
pub fn reset(self: *Self) void
参数
self: *Self
std.mem.SplitIterator.rest
函数
返回剩余字节的切片。不影响迭代器状态。
pub fn rest(self: Self) []const T
参数
self: Self
std.mem.SplitIterator.Self
别名
std.mem.splitScalar
函数
返回迭代器,遍历 buffer 中由 delimiter 分隔的切片。
splitScalar(u8, "abc|def||ghi", '|') 将依次返回对应“abc”“def”“”“ghi”的切片,最后返回 null。
若缓冲区中不存在 delimiter,迭代器依次返回 buffer 和 null。
另见:splitSequence、splitAny、splitBackwardsSequence、
splitBackwardsAny、splitBackwardsScalar、
tokenizeAny、tokenizeSequence 和 tokenizeScalar。
pub fn splitScalar(comptime T: type, buffer: []const T, delimiter: T) SplitIterator(T, .scalar)
参数
T: type
buffer: []const T
delimiter: T
用法示例
test splitScalar {
var it = splitScalar(u8, "abc|def||ghi", '|');
try testing.expectEqualSlices(u8, it.rest(), "abc|def||ghi");
try testing.expectEqualSlices(u8, it.first(), "abc");
try testing.expectEqualSlices(u8, it.rest(), "def||ghi");
try testing.expectEqualSlices(u8, it.peek().?, "def");
try testing.expectEqualSlices(u8, it.next().?, "def");
try testing.expectEqualSlices(u8, it.rest(), "|ghi");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expectEqualSlices(u8, it.rest(), "ghi");
try testing.expectEqualSlices(u8, it.peek().?, "ghi");
try testing.expectEqualSlices(u8, it.next().?, "ghi");
try testing.expectEqualSlices(u8, it.rest(), "");
try testing.expect(it.peek() == null);
try testing.expect(it.next() == null);
it = splitScalar(u8, "", '|');
try testing.expectEqualSlices(u8, it.first(), "");
try testing.expect(it.next() == null);
it = splitScalar(u8, "|", '|');
try testing.expectEqualSlices(u8, it.first(), "");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expect(it.peek() == null);
try testing.expect(it.next() == null);
it = splitScalar(u8, "hello", ' ');
try testing.expectEqualSlices(u8, it.first(), "hello");
try testing.expect(it.next() == null);
var it16 = splitScalar(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("hello"),
' ',
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("hello"));
try testing.expect(it16.next() == null);
}
std.mem.splitSequence
函数
返回迭代器,遍历 buffer 中
由 delimiter 字节序列分隔的切片。
splitSequence(u8, "abc||def||||ghi", "||") 会依次返回
"abc"、"def"、""、"ghi" 的切片,最后返回 null。
若缓冲区中不存在 delimiter,
迭代器依次返回 buffer、null。
分隔符长度不得为零。
另请参见:splitAny、splitScalar、splitBackwardsSequence、
splitBackwardsAny、splitBackwardsScalar、
tokenizeAny、tokenizeSequence、tokenizeScalar。
pub fn splitSequence(comptime T: type, buffer: []const T, delimiter: []const T) SplitIterator(T, .sequence)
参数
T: type
buffer: []const T
delimiter: []const T
用法示例
test splitSequence {
var it = splitSequence(u8, "a, b ,, c, d, e", ", ");
try testing.expectEqualSlices(u8, it.first(), "a");
try testing.expectEqualSlices(u8, it.rest(), "b ,, c, d, e");
try testing.expectEqualSlices(u8, it.next().?, "b ,");
try testing.expectEqualSlices(u8, it.next().?, "c");
try testing.expectEqualSlices(u8, it.next().?, "d");
try testing.expectEqualSlices(u8, it.next().?, "e");
try testing.expect(it.next() == null);
var it16 = splitSequence(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a, b ,, c, d, e"),
std.unicode.utf8ToUtf16LeStringLiteral(", "),
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("a"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b ,"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("e"));
try testing.expect(it16.next() == null);
}
std.mem.startsWith
函数
如果 haystack 以 needle 开头,则返回 true。 时间复杂度:O(needle.len)。
pub fn startsWith(comptime T: type, haystack: []const T, needle: []const T) bool
参数
T: type
haystack: []const T
needle: []const T
用法示例
test startsWith {
try testing.expect(startsWith(u8, "Bob", "Bo"));
try testing.expect(!startsWith(u8, "Needle in haystack", "haystack"));
}
std.mem.std
别名
别名目标 std
std.mem.swap
函数
交换两个内存位置中的内容。
pub fn swap(comptime T: type, noalias a: *T, noalias b: *T) void
参数
T: type
a: *T
b: *T
std.mem.testCollapseRepeats
函数
fn testCollapseRepeats(str: []const u8, elem: u8, expected: []const u8) !void
参数
str: []const u8
elem: u8
expected: []const u8
std.mem.testing
别名
别名目标 std.testing
std.mem.toBytes
函数
接受任意值,以数组形式返回其字节的副本。
pub fn toBytes(value: anytype) [@sizeOf(@TypeOf(value))]u8
用法示例
test toBytes {
var my_bytes = toBytes(@as(u32, 0x12345678));
switch (native_endian) {
.big => try testing.expect(eql(u8, &my_bytes, "\x12\x34\x56\x78")),
.little => try testing.expect(eql(u8, &my_bytes, "\x78\x56\x34\x12")),
}
my_bytes[0] = '\x99';
switch (native_endian) {
.big => try testing.expect(eql(u8, &my_bytes, "\x99\x34\x56\x78")),
.little => try testing.expect(eql(u8, &my_bytes, "\x99\x56\x34\x12")),
}
}
std.mem.TokenIterator
类型函数
用于词元化操作的迭代器类型,会跳过空序列和分隔符序列。
pub fn TokenIterator(comptime T: type, comptime delimiter_type: DelimiterType) type
参数
T: type
delimiter_type: DelimiterType
字段
buffer: []const T
delimiter: switch (delimiter_type) {
.sequence, .any => []const T,
.scalar => T,
}
index: usize
std.mem.TokenIterator.isDelimiter
函数
fn isDelimiter(self: Self, index: usize) bool
参数
self: Self
index: usize
std.mem.TokenIterator.next
函数
返回当前词法标记的切片;若词法分析已完成,则返回 null, 并前进到下一个词法标记。
pub fn next(self: *Self) ?[]const T
参数
self: *Self
std.mem.TokenIterator.peek
函数
返回当前词元的切片;如果词法分析已结束,则返回 null。 不会前进到下一个词元。
pub fn peek(self: *Self) ?[]const T
参数
self: *Self
std.mem.TokenIterator.reset
函数
将迭代器重置到初始词法标记。
pub fn reset(self: *Self) void
参数
self: *Self
std.mem.TokenIterator.rest
函数
返回剩余字节的切片。不影响迭代器状态。
pub fn rest(self: Self) []const T
参数
self: Self
std.mem.TokenIterator.Self
别名
std.mem.tokenizeAny
函数
返回迭代器,遍历 buffer 中不属于 delimiters 任一元素的切片。
tokenizeAny(u8, " abc|def || ghi ", " |") 将依次返回对应“abc”“def”“ghi”的切片,最后返回 null。
若 buffer 为空,迭代器返回 null。
若缓冲区中没有出现任何 delimiters,迭代器依次返回 buffer 和 null。
另见:tokenizeSequence、tokenizeScalar、
splitSequence、splitAny、splitScalar、
splitBackwardsSequence、splitBackwardsAny 和 splitBackwardsScalar
pub fn tokenizeAny(comptime T: type, buffer: []const T, delimiters: []const T) TokenIterator(T, .any)
参数
T: type
buffer: []const T
delimiters: []const T
用法示例
test tokenizeAny {
var it = tokenizeAny(u8, "a|b,c/d e", " /,|");
try testing.expect(eql(u8, it.next().?, "a"));
try testing.expect(eql(u8, it.peek().?, "b"));
try testing.expect(eql(u8, it.next().?, "b"));
try testing.expect(eql(u8, it.next().?, "c"));
try testing.expect(eql(u8, it.next().?, "d"));
try testing.expect(eql(u8, it.next().?, "e"));
try testing.expect(it.next() == null);
try testing.expect(it.peek() == null);
it = tokenizeAny(u8, "hello", "");
try testing.expect(eql(u8, it.next().?, "hello"));
try testing.expect(it.next() == null);
var it16 = tokenizeAny(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a|b,c/d e"),
std.unicode.utf8ToUtf16LeStringLiteral(" /,|"),
);
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("a")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("e")));
try testing.expect(it16.next() == null);
}
std.mem.tokenizeScalar
函数
返回迭代器,遍历 buffer 中不等于 delimiter 的切片。
tokenizeScalar(u8, " abc def ghi ", ' ') 将依次返回对应“abc”“def”“ghi”的切片,最后返回 null。
若 buffer 为空,迭代器返回 null。
若缓冲区中不存在 delimiter,迭代器依次返回 buffer 和 null。
另见:tokenizeAny、tokenizeSequence、
splitSequence、splitAny 和 splitScalar、
splitBackwardsSequence、splitBackwardsAny 和 splitBackwardsScalar
pub fn tokenizeScalar(comptime T: type, buffer: []const T, delimiter: T) TokenIterator(T, .scalar)
参数
T: type
buffer: []const T
delimiter: T
用法示例
test tokenizeScalar {
var it = tokenizeScalar(u8, " abc def ghi ", ' ');
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(eql(u8, it.peek().?, "def"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
try testing.expect(it.next() == null);
it = tokenizeScalar(u8, "..\\bob", '\\');
try testing.expect(eql(u8, it.next().?, ".."));
try testing.expect(eql(u8, "..", "..\\bob"[0..it.index]));
try testing.expect(eql(u8, it.next().?, "bob"));
try testing.expect(it.next() == null);
it = tokenizeScalar(u8, "//a/b", '/');
try testing.expect(eql(u8, it.next().?, "a"));
try testing.expect(eql(u8, it.next().?, "b"));
try testing.expect(eql(u8, "//a/b", "//a/b"[0..it.index]));
try testing.expect(it.next() == null);
it = tokenizeScalar(u8, "|", '|');
try testing.expect(it.next() == null);
try testing.expect(it.peek() == null);
it = tokenizeScalar(u8, "", '|');
try testing.expect(it.next() == null);
try testing.expect(it.peek() == null);
it = tokenizeScalar(u8, "hello", ' ');
try testing.expect(eql(u8, it.next().?, "hello"));
try testing.expect(it.next() == null);
var it16 = tokenizeScalar(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("hello"),
' ',
);
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("hello")));
try testing.expect(it16.next() == null);
}
std.mem.tokenizeSequence
函数
返回迭代器,遍历 buffer 中不是
delimiter 所示序列的切片。
tokenizeSequence(u8, "<>abc><def<><>ghi", "<>") 将按顺序返回
切片 "abc><def"、"ghi"、null。
如果 buffer 为空,迭代器返回 null。
如果 buffer 中不存在 delimiter,
迭代器将依次返回 buffer、null。
分隔符长度不得为零。
另请参见:tokenizeAny、tokenizeScalar、
splitSequence、splitAny、splitScalar、
splitBackwardsSequence、splitBackwardsAny、splitBackwardsScalar。
pub fn tokenizeSequence(comptime T: type, buffer: []const T, delimiter: []const T) TokenIterator(T, .sequence)
参数
T: type
buffer: []const T
delimiter: []const T
用法示例
test tokenizeSequence {
var it = tokenizeSequence(u8, "a<>b<><>c><>d><", "<>");
try testing.expectEqualStrings("a", it.next().?);
try testing.expectEqualStrings("b", it.peek().?);
try testing.expectEqualStrings("b", it.next().?);
try testing.expectEqualStrings("c>", it.next().?);
try testing.expectEqualStrings("d><", it.next().?);
try testing.expect(it.next() == null);
try testing.expect(it.peek() == null);
var it16 = tokenizeSequence(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a<>b<><>c><>d><"),
std.unicode.utf8ToUtf16LeStringLiteral("<>"),
);
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("a")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c>")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d><")));
try testing.expect(it16.next() == null);
}
std.mem.toNative
函数
将整数从指定字节序转换为主机字节序。
pub fn toNative(comptime T: type, x: T, endianness_of_x: Endian) T
参数
std.mem.trim
函数
从切片首尾移除属于某值集合的元素。
pub fn trim(comptime T: type, slice: []const T, values_to_strip: []const T) []const T
参数
T: type
slice: []const T
values_to_strip: []const T
用法示例
test trim {
try testing.expectEqualSlices(u8, "foo", trim(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, "foo", trim(u8, "foo", " \n"));
}
std.mem.trimEnd
函数
从切片末尾移除一组值。
pub fn trimEnd(comptime T: type, slice: []const T, values_to_strip: []const T) []const T
参数
T: type
slice: []const T
values_to_strip: []const T
用法示例
test trimEnd {
try testing.expectEqualSlices(u8, " foo", trimEnd(u8, " foo\n ", " \n"));
}
std.mem.trimStart
函数
从切片开头移除一组值。
pub fn trimStart(comptime T: type, slice: []const T, values_to_strip: []const T) []const T
参数
T: type
slice: []const T
values_to_strip: []const T
用法示例
test trimStart {
try testing.expectEqualSlices(u8, "foo\n ", trimStart(u8, " foo\n ", " \n"));
}
std.mem.use_vectors
常量
std.mem.use_vectors_for_comparison
常量
std.mem.ValidationAllocator
类型函数
检测调用方或分配器是否违反 std.mem.Allocator 接口约定, 并在违反时触发断言。
pub fn ValidationAllocator(comptime T: type) type
参数
T: type
字段
underlying_allocator: T
std.mem.ValidationAllocator.alloc
函数
pub fn alloc( ctx: *anyopaque, n: usize, alignment: mem.Alignment, ret_addr: usize, ) ?[*]u8
参数
std.mem.ValidationAllocator.allocator
函数
pub fn allocator(self: *Self) Allocator
参数
self: *Self
std.mem.ValidationAllocator.free
函数
pub fn free( ctx: *anyopaque, buf: []u8, alignment: Alignment, ret_addr: usize, ) void
参数
std.mem.ValidationAllocator.getUnderlyingAllocatorPtr
函数
fn getUnderlyingAllocatorPtr(self: *Self) Allocator
参数
self: *Self
std.mem.ValidationAllocator.init
函数
pub fn init(underlying_allocator: T) @This()
参数
underlying_allocator: T
std.mem.ValidationAllocator.remap
函数
pub fn remap( ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ret_addr: usize, ) ?[*]u8
参数
std.mem.ValidationAllocator.reset
函数
pub fn reset(self: *Self) void
参数
self: *Self
std.mem.ValidationAllocator.resize
函数
pub fn resize( ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ret_addr: usize, ) bool
参数
std.mem.ValidationAllocator.Self
别名
std.mem.validationWrap
函数
为分配器添加基本有效性检查。 断言分配大小大于零,且返回指针的对齐正确。
pub fn validationWrap(allocator: anytype) ValidationAllocator(@TypeOf(allocator))
std.mem.window
函数
返回通过滑动窗口遍历 buffer 切片的迭代器。
窗口长度为 size,每次迭代
向前移动 advance。
提取移动平均值所用数据的示例:
window(u8, "abcdefg", 3, 1) 将按顺序返回切片
"abc"、"bcd"、"cde"、"def"、"efg"、null。
每 N 个元素分块或拆分的示例:
window(u8, "abcdefg", 3, 3) 将按顺序返回切片
"abc"、"def"、"g"、null。
选取每个偶数索引的示例:
window(u8, "abcdefg", 1, 2) 将按顺序返回切片
"a"、"c"、"e"、"g"、null。
size 和 advance 均不得为零。
pub fn window(comptime T: type, buffer: []const T, size: usize, advance: usize) WindowIterator(T)
参数
T: type
buffer: []const T
size: usize
advance: usize
用法示例
test window {
{
// 大小为 3 的移动平均
var it = window(u8, "abcdefg", 3, 1);
try testing.expectEqualSlices(u8, "abc", it.next().?);
try testing.expectEqualSlices(u8, "bcd", it.next().?);
try testing.expectEqualSlices(u8, "cde", it.next().?);
try testing.expectEqualSlices(u8, "def", it.next().?);
try testing.expectEqualSlices(u8, "efg", it.next().?);
try testing.expectEqual(null, it.next());
// 多字节
var it16 = window(u16, std.unicode.utf8ToUtf16LeStringLiteral("abcdefg"), 3, 1);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("abc"), it16.next().?);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("bcd"), it16.next().?);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("cde"), it16.next().?);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("def"), it16.next().?);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("efg"), it16.next().?);
try testing.expectEqual(it16.next(), null);
}
{
// 每 3 个分块/拆分
var it = window(u8, "abcdefg", 3, 3);
try testing.expectEqualSlices(u8, "abc", it.next().?);
try testing.expectEqualSlices(u8, "def", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// 选择偶数
var it = window(u8, "abcdefg", 1, 2);
try testing.expectEqualSlices(u8, "a", it.next().?);
try testing.expectEqualSlices(u8, "c", it.next().?);
try testing.expectEqualSlices(u8, "e", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
it = window(u8, "abcdefgh", 1, 2);
try testing.expectEqualSlices(u8, "a", it.next().?);
try testing.expectEqualSlices(u8, "c", it.next().?);
try testing.expectEqualSlices(u8, "e", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// 空
var it = window(u8, "", 1, 1);
try testing.expectEqual(null, it.next());
it = window(u8, "", 10, 1);
try testing.expectEqual(null, it.next());
it = window(u8, "", 1, 10);
try testing.expectEqual(null, it.next());
it = window(u8, "", 10, 10);
try testing.expectEqual(null, it.next());
}
{
// 首个
var it = window(u8, "abcdefg", 3, 3);
try testing.expectEqualSlices(u8, "abc", it.next().?);
it.reset();
try testing.expectEqualSlices(u8, "abc", it.next().?);
}
{
// 重置
var it = window(u8, "abcdefg", 3, 3);
try testing.expectEqualSlices(u8, "abc", it.next().?);
try testing.expectEqualSlices(u8, "def", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
it.reset();
try testing.expectEqualSlices(u8, "abc", it.next().?);
try testing.expectEqualSlices(u8, "def", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// size > buffer.len
var it = window(u8, "abcdefg", 100, 1);
try testing.expectEqualSlices(u8, "abcdefg", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// advance >= buffer.len
var it = window(u8, "abcdefg", 1, 7);
try testing.expectEqualSlices(u8, "a", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// advance == 1 且 size == 1
var it = window(u8, "abcdefg", 1, 1);
try testing.expectEqualSlices(u8, "a", it.next().?);
try testing.expectEqualSlices(u8, "b", it.next().?);
try testing.expectEqualSlices(u8, "c", it.next().?);
try testing.expectEqualSlices(u8, "d", it.next().?);
try testing.expectEqualSlices(u8, "e", it.next().?);
try testing.expectEqualSlices(u8, "f", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// 前移量 > 大小
var it = window(u8, "abcdefg", 2, 3);
try testing.expectEqualSlices(u8, "ab", it.next().?);
try testing.expectEqualSlices(u8, "de", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
}
std.mem.WindowIterator
类型函数
window 函数为滑动窗口操作返回的迭代器类型。
pub fn WindowIterator(comptime T: type) type
参数
T: type
字段
buffer: []const T
index: ?usize
size: usize
advance: usize
std.mem.WindowIterator.next
函数
返回下一个窗口的切片;若窗口已到末尾,则返回 null。
pub fn next(self: *Self) ?[]const T
参数
self: *Self
std.mem.WindowIterator.reset
函数
将迭代器重置到初始窗口。
pub fn reset(self: *Self) void
参数
self: *Self
std.mem.WindowIterator.Self
别名
std.mem.writeInt
函数
将整数以二进制补码形式写入内存。 此函数始终成功,对所有输入均有定义行为,但 整数位宽必须能被 8 整除。
pub inline fn writeInt(comptime T: type, buffer: *[@divExact(@typeInfo(T).int.bits, 8)]u8, value: T, endian: Endian) void
参数
用法示例
test writeInt {
var buf0: [0]u8 = undefined;
var buf1: [1]u8 = undefined;
var buf2: [2]u8 = undefined;
var buf9: [9]u8 = undefined;
writeInt(u0, &buf0, 0x0, .big);
try testing.expect(eql(u8, buf0[0..], &[_]u8{}));
writeInt(u0, &buf0, 0x0, .little);
try testing.expect(eql(u8, buf0[0..], &[_]u8{}));
writeInt(u8, &buf1, 0x12, .big);
try testing.expect(eql(u8, buf1[0..], &[_]u8{0x12}));
writeInt(u8, &buf1, 0x34, .little);
try testing.expect(eql(u8, buf1[0..], &[_]u8{0x34}));
writeInt(u16, &buf2, 0x1234, .big);
try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0x12, 0x34 }));
writeInt(u16, &buf2, 0x5678, .little);
try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0x78, 0x56 }));
writeInt(u72, &buf9, 0x123456789abcdef024, .big);
try testing.expect(eql(u8, buf9[0..], &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 }));
writeInt(u72, &buf9, 0xfedcba9876543210ec, .little);
try testing.expect(eql(u8, buf9[0..], &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe }));
writeInt(i8, &buf1, -1, .big);
try testing.expect(eql(u8, buf1[0..], &[_]u8{0xff}));
writeInt(i8, &buf1, -2, .little);
try testing.expect(eql(u8, buf1[0..], &[_]u8{0xfe}));
writeInt(i16, &buf2, -3, .big);
try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0xff, 0xfd }));
writeInt(i16, &buf2, -4, .little);
try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0xfc, 0xff }));
}
std.mem.writePackedInt
函数
将整数存储到打包内存中。 断言缓冲区至少包含 bit_offset + @bitSizeOf(T) 位。
pub fn writePackedInt(comptime T: type, bytes: []u8, bit_offset: usize, value: T, endian: Endian) void
参数
用法示例
test writePackedInt {
const T = packed struct(u16) { a: u3, b: u7, c: u6 };
var st = T{ .a = 1, .b = 2, .c = 4 };
writePackedInt(u7, std.mem.asBytes(&st), @bitOffsetOf(T, "b"), 0x7f, builtin.cpu.arch.endian());
try std.testing.expectEqual(T{ .a = 1, .b = 0x7f, .c = 4 }, st);
}
std.mem.writePackedIntBig
函数
fn writePackedIntBig(comptime T: type, bytes: []u8, bit_offset: usize, value: T) void
参数
T: type
bytes: []u8
bit_offset: usize
value: T
std.mem.writePackedIntLittle
函数
fn writePackedIntLittle(comptime T: type, bytes: []u8, bit_offset: usize, value: T) void
参数
T: type
bytes: []u8
bit_offset: usize
value: T
std.mem.writeVarPackedInt
函数
按给定 bit_offset、bit_count 和有符号性,将整数存入紧凑内存。 若为负数,则对写入值进行符号扩展。
pub fn writeVarPackedInt(bytes: []u8, bit_offset: usize, bit_count: usize, value: anytype, endian: std.builtin.Endian) void
参数
用法示例
test writeVarPackedInt {
const T = packed struct(u16) { a: u3, b: u7, c: u6 };
var st = T{ .a = 1, .b = 2, .c = 4 };
const value: u64 = 0x7f;
writeVarPackedInt(std.mem.asBytes(&st), @bitOffsetOf(T, "b"), 7, value, builtin.cpu.arch.endian());
try testing.expectEqual(T{ .a = 1, .b = value, .c = 4 }, st);
}
std.mem.zeroes
函数
通常建议 Zig 用户显式初始化结构体的全部字段,而非使用此函数。 不过,确实存在将所有字段初始化为“零”值的用例,例如 与较常采用并依赖此惯例的 C API 交互。代码审查时若发现调用 此函数,应仔细检查:这可能意味着代码设计存在问题。 将类型初始化为零值。 可用于任何适合零初始化的类型。结构体会递归初始化。
pub fn zeroes(comptime T: type) T
参数
T: type
用法示例
test zeroes {
const C_struct = extern struct {
x: u32,
y: u32 align(128),
};
var a = zeroes(C_struct);
// Extern 结构体的填充应清零。
{
const num_bytes = @sizeOf(@TypeOf(a));
try testing.expectEqualSlices(u8, &@as([num_bytes]u8, @splat(0)), @ptrCast(&a));
}
a.y += 10;
try testing.expect(a.x == 0);
try testing.expect(a.y == 10);
const ZigStruct = struct {
comptime comptime_field: u8 = 5,
integral_types: struct {
integer_8: i8,
integer_16: i16,
integer_32: i32,
integer_64: i64,
integer_128: i128,
unsigned_0: u0,
unsigned_8: u8,
unsigned_16: u16,
unsigned_32: u32,
unsigned_64: u64,
unsigned_128: u128,
float_32: f32,
float_64: f64,
},
pointers: struct {
optional: ?*u8,
c_pointer: [*c]u8,
slice: []u8,
nullTerminatedString: [:0]const u8,
},
array: [2]u32,
vector_u32: @Vector(2, u32),
vector_f32: @Vector(2, f32),
vector_bool: @Vector(2, bool),
optional_int: ?u8,
empty: void,
sentinel: [3:0]u8,
};
const b = zeroes(ZigStruct);
try testing.expectEqual(@as(u8, 5), b.comptime_field);
try testing.expectEqual(@as(i8, 0), b.integral_types.integer_8);
try testing.expectEqual(@as(i16, 0), b.integral_types.integer_16);
try testing.expectEqual(@as(i32, 0), b.integral_types.integer_32);
try testing.expectEqual(@as(i64, 0), b.integral_types.integer_64);
try testing.expectEqual(@as(i128, 0), b.integral_types.integer_128);
try testing.expectEqual(@as(u8, 0), b.integral_types.unsigned_0);
try testing.expectEqual(@as(u8, 0), b.integral_types.unsigned_8);
try testing.expectEqual(@as(u16, 0), b.integral_types.unsigned_16);
try testing.expectEqual(@as(u32, 0), b.integral_types.unsigned_32);
try testing.expectEqual(@as(u64, 0), b.integral_types.unsigned_64);
try testing.expectEqual(@as(u128, 0), b.integral_types.unsigned_128);
try testing.expectEqual(@as(f32, 0), b.integral_types.float_32);
try testing.expectEqual(@as(f64, 0), b.integral_types.float_64);
try testing.expectEqual(@as(?*u8, null), b.pointers.optional);
try testing.expectEqual(@as([*c]u8, null), b.pointers.c_pointer);
try testing.expectEqual(@as([]u8, &[_]u8{}), b.pointers.slice);
try testing.expectEqual(@as([:0]const u8, ""), b.pointers.nullTerminatedString);
for (b.array) |e| {
try testing.expectEqual(@as(u32, 0), e);
}
try testing.expectEqual(@as(@TypeOf(b.vector_u32), @splat(0)), b.vector_u32);
try testing.expectEqual(@as(@TypeOf(b.vector_f32), @splat(0.0)), b.vector_f32);
if (!(builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .hexagon)) {
try testing.expectEqual(@as(@TypeOf(b.vector_bool), @splat(false)), b.vector_bool);
}
try testing.expectEqual(@as(?u8, null), b.optional_int);
for (b.sentinel) |e| {
try testing.expectEqual(@as(u8, 0), e);
}
const C_union = extern union {
a: u8,
b: u32,
};
const c = zeroes(C_union);
try testing.expectEqual(@as(u8, 0), c.a);
try testing.expectEqual(@as(u32, 0), c.b);
const comptime_union = comptime zeroes(C_union);
try testing.expectEqual(@as(u8, 0), comptime_union.a);
try testing.expectEqual(@as(u32, 0), comptime_union.b);
// 确保带字段的零大小结构体正确初始化。
_ = zeroes(struct { handle: void });
}
std.mem.zeroInit
函数
将结构体的所有字段初始化为默认值;未提供默认值时则使用零值。 如果提供的初始值中包含该字段,则使用对应值。 递归初始化结构体。
pub fn zeroInit(comptime T: type, init: anytype) T
参数
T: type
用法示例
test zeroInit {
const I = struct {
d: f64,
};
const S = struct {
a: u32,
b: ?bool,
c: I,
e: [3]u8,
f: i64 = -1,
};
const s = zeroInit(S, .{
.a = 42,
});
try testing.expectEqual(S{
.a = 42,
.b = null,
.c = .{
.d = 0,
},
.e = [3]u8{ 0, 0, 0 },
.f = -1,
}, s);
const Color = struct {
r: u8,
g: u8,
b: u8,
a: u8,
};
const c = zeroInit(Color, .{ 255, 255 });
try testing.expectEqual(Color{
.r = 255,
.g = 255,
.b = 0,
.a = 0,
}, c);
const Foo = struct {
foo: u8 = 69,
bar: u8,
};
const f = zeroInit(Foo, .{});
try testing.expectEqual(Foo{
.foo = 69,
.bar = 0,
}, f);
const Bar = struct {
foo: u32 = 666,
bar: u32 = 420,
};
const b = zeroInit(Bar, .{69});
try testing.expectEqual(Bar{
.foo = 69,
.bar = 420,
}, b);
const Baz = struct {
foo: [:0]const u8 = "bar",
};
const baz1 = zeroInit(Baz, .{});
try testing.expectEqual(Baz{}, baz1);
const baz2 = zeroInit(Baz, .{ .foo = "zab" });
try testing.expectEqualSlices(u8, "zab", baz2.foo);
const NestedBaz = struct {
bbb: Baz,
};
const nested_baz = zeroInit(NestedBaz, .{});
try testing.expectEqual(NestedBaz{
.bbb = Baz{},
}, nested_baz);
}
源码
std/mem.zig
const mem = @This();
const builtin = @import("builtin");
const native_endian = builtin.cpu.arch.endian();
const std = @import("std.zig");
const debug = std.debug;
const assert = debug.assert;
const math = std.math;
const testing = std.testing;
const Endian = std.lang.Endian;
const AbsorbSentinel = std.meta.AbsorbSentinel;
/// 标准库目前全面依赖一个字节为 8 位这一条件。
/// (可见分配代码中广泛使用 u8 作为
/// “字节”类型。)依赖此条件的代码可以引用
/// 此声明。如果将来尝试把标准库移植到
/// 字节并非 8 位的平台,就可以据此搜索
/// 需要更新的位置。
pub const byte_size_in_bits = 8;
pub const Allocator = @import("mem/Allocator.zig");
/// 以 2 的幂形式存储。
pub const Alignment = enum(math.Log2Int(usize)) {
@"1" = 0,
@"2" = 1,
@"4" = 2,
@"8" = 3,
@"16" = 4,
@"32" = 5,
@"64" = 6,
_,
pub fn toByteUnits(a: Alignment) usize {
return @as(usize, 1) << @backingInt(a);
}
pub fn fromByteUnits(n: usize) Alignment {
assert(std.math.isPowerOfTwo(n));
return @fromBackingInt(@intCast(@ctz(n)));
}
pub fn fromByteUnitsOptional(maybe_n: ?usize) ?Alignment {
return if (maybe_n) |n| .fromByteUnits(n) else null;
}
pub inline fn of(comptime T: type) Alignment {
return comptime fromByteUnits(@alignOf(T));
}
pub fn order(lhs: Alignment, rhs: Alignment) std.math.Order {
return std.math.order(@backingInt(lhs), @backingInt(rhs));
}
pub fn compare(lhs: Alignment, op: std.math.CompareOperator, rhs: Alignment) bool {
return std.math.compare(@backingInt(lhs), op, @backingInt(rhs));
}
pub fn max(lhs: Alignment, rhs: Alignment) Alignment {
return @fromBackingInt(@intCast(@max(@backingInt(lhs), @backingInt(rhs))));
}
pub fn min(lhs: Alignment, rhs: Alignment) Alignment {
return @fromBackingInt(@intCast(@min(@backingInt(lhs), @backingInt(rhs))));
}
/// 返回满足此对齐要求的下一个地址。
pub fn forward(a: Alignment, address: usize) usize {
const x = (@as(usize, 1) << @backingInt(a)) - 1;
return (address + x) & ~x;
}
/// 返回满足此对齐要求的前一个地址。
pub fn backward(a: Alignment, address: usize) usize {
const x = (@as(usize, 1) << @backingInt(a)) - 1;
return address & ~x;
}
/// 返回地址是否满足此对齐要求。
pub fn check(a: Alignment, address: usize) bool {
return @ctz(address) >= @backingInt(a);
}
};
/// 检测调用方或分配器是否违反 std.mem.Allocator 接口约定,
/// 并在违反时触发断言。
pub fn ValidationAllocator(comptime T: type) type {
return struct {
const Self = @This();
underlying_allocator: T,
pub fn init(underlying_allocator: T) @This() {
return .{
.underlying_allocator = underlying_allocator,
};
}
pub fn allocator(self: *Self) Allocator {
return .{
.ptr = self,
.vtable = &.{
.alloc = alloc,
.resize = resize,
.remap = remap,
.free = free,
},
};
}
fn getUnderlyingAllocatorPtr(self: *Self) Allocator {
if (T == Allocator) return self.underlying_allocator;
return self.underlying_allocator.allocator();
}
pub fn alloc(
ctx: *anyopaque,
n: usize,
alignment: mem.Alignment,
ret_addr: usize,
) ?[*]u8 {
assert(n > 0);
const self: *Self = @ptrCast(@alignCast(ctx));
const underlying = self.getUnderlyingAllocatorPtr();
const result = underlying.rawAlloc(n, alignment, ret_addr) orelse
return null;
assert(alignment.check(@intFromPtr(result)));
return result;
}
pub fn resize(
ctx: *anyopaque,
buf: []u8,
alignment: Alignment,
new_len: usize,
ret_addr: usize,
) bool {
const self: *Self = @ptrCast(@alignCast(ctx));
assert(buf.len > 0);
const underlying = self.getUnderlyingAllocatorPtr();
return underlying.rawResize(buf, alignment, new_len, ret_addr);
}
pub fn remap(
ctx: *anyopaque,
buf: []u8,
alignment: Alignment,
new_len: usize,
ret_addr: usize,
) ?[*]u8 {
const self: *Self = @ptrCast(@alignCast(ctx));
assert(buf.len > 0);
const underlying = self.getUnderlyingAllocatorPtr();
return underlying.rawRemap(buf, alignment, new_len, ret_addr);
}
pub fn free(
ctx: *anyopaque,
buf: []u8,
alignment: Alignment,
ret_addr: usize,
) void {
const self: *Self = @ptrCast(@alignCast(ctx));
assert(buf.len > 0);
const underlying = self.getUnderlyingAllocatorPtr();
underlying.rawFree(buf, alignment, ret_addr);
}
pub fn reset(self: *Self) void {
self.underlying_allocator.reset();
}
};
}
/// 为分配器添加基本有效性检查。
/// 断言分配大小大于零,且返回指针的对齐正确。
pub fn validationWrap(allocator: anytype) ValidationAllocator(@TypeOf(allocator)) {
return ValidationAllocator(@TypeOf(allocator)).init(allocator);
}
test "Allocator basics" {
try testing.expectError(error.OutOfMemory, testing.failing_allocator.alloc(u8, 1));
try testing.expectError(error.OutOfMemory, testing.failing_allocator.allocSentinel(u8, 1, 0));
}
test "Allocator.resize" {
const primitiveIntTypes = .{
i8,
u8,
i16,
u16,
i32,
u32,
i64,
u64,
i128,
u128,
isize,
usize,
};
inline for (primitiveIntTypes) |T| {
var values = try testing.allocator.alloc(T, 100);
defer testing.allocator.free(values);
for (values, 0..) |*v, i| v.* = @as(T, @intCast(i));
if (testing.allocator.resize(values, values.len + 10)) {
values = values.ptr[0 .. values.len + 10];
try testing.expect(values.len == 110);
} else {
// 即使内存充足,`resize` 也不保证成功。
}
}
const primitiveFloatTypes = .{
f16,
f32,
f64,
f128,
};
inline for (primitiveFloatTypes) |T| {
var values = try testing.allocator.alloc(T, 100);
defer testing.allocator.free(values);
for (values, 0..) |*v, i| v.* = @as(T, @floatFromInt(i));
if (testing.allocator.resize(values, values.len + 10)) {
values = values.ptr[0 .. values.len + 10];
try testing.expect(values.len == 110);
} else {
// 即使内存充足,`resize` 也不保证成功。
}
}
}
test "Allocator alloc and remap with zero-bit type" {
var values = try testing.allocator.alloc(void, 10);
defer testing.allocator.free(values);
try testing.expectEqual(10, values.len);
const remaped = testing.allocator.remap(values, 200);
try testing.expect(remaped != null);
values = remaped.?;
try testing.expectEqual(200, values.len);
}
/// 将整个 source 复制到 dest 的位置 0。
/// dest.len 必须 >= source.len。
/// 若切片重叠,dest.ptr 必须 <= src.ptr。
/// 此函数已弃用;请改用 @memmove。
pub fn copyForwards(comptime T: type, dest: []T, source: []const T) void {
for (dest[0..source.len], source) |*d, s| d.* = s;
}
/// 将全部 source 复制到 dest 的位置 0。
/// dest.len 必须 >= source.len。
/// 若切片重叠,dest.ptr 必须 >= src.ptr。
/// 此函数已弃用;请改用 @memmove。
pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void {
// TODO: 不应手动对整个数组执行此检查并关闭运行时安全检查;
// 编译器应识别此类循环,
// 自动省略循环中的安全检查。
@setRuntimeSafety(false);
assert(dest.len >= source.len);
var i = source.len;
while (i > 0) {
i -= 1;
dest[i] = source[i];
}
}
/// 将 `source` 复制到 `dest`,不包括哨兵元素。
///
/// 断言没有重叠。断言 `dest.len` 大于或等于 source 长度。返回复制的元素数量,
/// 不计哨兵元素。
pub fn copySentinel(comptime T: type, comptime s: T, dest: []T, source: [*:s]const T) usize {
const i = findSentinel(T, s, source);
@memcpy(dest[0..i], source[0..i]);
return i;
}
test copySentinel {
var dst: [11]u8 = @splat(0xff);
const n = copySentinel(u8, 0, &dst, "hello this\x00is my null-terminated string");
try testing.expectEqualStrings("hello this\xff", &dst);
try testing.expectEqual(n, 10);
}
/// 将 `source` 复制到 `dest`,包括哨兵元素。
///
/// 断言没有重叠。断言 `dest.len` 大于或等于 source 长度,且包含哨兵所需空间。
/// 返回已复制元素数量,包括哨兵元素。
pub fn copySentinelInclusive(comptime T: type, comptime s: T, dest: []T, source: [*:s]const T) usize {
const i = findSentinel(T, s, source) + 1;
@memcpy(dest[0..i], source[0..i]);
return i;
}
test copySentinelInclusive {
var dst: [12]u8 = @splat(0xff);
const n = copySentinelInclusive(u8, 0, &dst, "hello this\x00is my null-terminated string");
try testing.expectEqualStrings("hello this\x00\xff", &dst);
try testing.expectEqual(n, 11);
}
/// 通常建议 Zig 用户显式初始化结构体的全部字段,而非使用此函数。
/// 不过,确实存在将所有字段初始化为“零”值的用例,例如
/// 与较常采用并依赖此惯例的 C API 交互。代码审查时若发现调用
/// 此函数,应仔细检查:这可能意味着代码设计存在问题。
/// 将类型初始化为零值。
/// 可用于任何适合零初始化的类型。结构体会递归初始化。
pub fn zeroes(comptime T: type) T {
switch (@typeInfo(T)) {
.comptime_int, .int, .comptime_float, .float => {
return @as(T, 0);
},
.@"enum" => {
return @as(T, @fromBackingInt(@intCast(0)));
},
.void => {
return {};
},
.bool => {
return false;
},
.optional, .null => {
return null;
},
.@"struct" => |struct_info| {
if (@sizeOf(T) == 0) return undefined;
if (struct_info.layout == .@"extern") {
var item: T = undefined;
@memset(asBytes(&item), 0);
return item;
} else {
var structure: T = undefined;
inline for (
struct_info.field_names,
struct_info.field_types,
struct_info.field_attrs,
) |field_name, field_type, field_attrs| {
if (!field_attrs.@"comptime") {
@field(structure, field_name) = zeroes(field_type);
}
}
return structure;
}
},
.pointer => |ptr_info| {
switch (ptr_info.size) {
.slice => {
if (ptr_info.sentinel()) |sentinel| {
if (ptr_info.child == u8 and sentinel == 0) {
return ""; // 针对最常见用例,即以空字符结尾的字符串的特殊处理。
}
@compileError("Can't set a sentinel slice to zero. This would require allocating memory.");
} else {
return &[_]ptr_info.child{};
}
},
.c => {
return null;
},
.one, .many => {
if (ptr_info.attrs.@"allowzero") return @ptrFromInt(0);
@compileError("Only nullable and allowzero pointers can be set to zero.");
},
}
},
.array => |info| {
return @splat(zeroes(info.child));
},
.vector => |info| {
return @splat(zeroes(info.child));
},
.@"union" => |info| {
if (info.layout == .@"extern") {
var item: T = undefined;
@memset(asBytes(&item), 0);
return item;
}
@compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
},
.enum_literal,
.error_union,
.error_set,
.@"fn",
.type,
.noreturn,
.undefined,
.@"opaque",
.spirv,
.frame,
.@"anyframe",
=> {
@compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
},
}
}
test zeroes {
const C_struct = extern struct {
x: u32,
y: u32 align(128),
};
var a = zeroes(C_struct);
// Extern 结构体的填充应清零。
{
const num_bytes = @sizeOf(@TypeOf(a));
try testing.expectEqualSlices(u8, &@as([num_bytes]u8, @splat(0)), @ptrCast(&a));
}
a.y += 10;
try testing.expect(a.x == 0);
try testing.expect(a.y == 10);
const ZigStruct = struct {
comptime comptime_field: u8 = 5,
integral_types: struct {
integer_8: i8,
integer_16: i16,
integer_32: i32,
integer_64: i64,
integer_128: i128,
unsigned_0: u0,
unsigned_8: u8,
unsigned_16: u16,
unsigned_32: u32,
unsigned_64: u64,
unsigned_128: u128,
float_32: f32,
float_64: f64,
},
pointers: struct {
optional: ?*u8,
c_pointer: [*c]u8,
slice: []u8,
nullTerminatedString: [:0]const u8,
},
array: [2]u32,
vector_u32: @Vector(2, u32),
vector_f32: @Vector(2, f32),
vector_bool: @Vector(2, bool),
optional_int: ?u8,
empty: void,
sentinel: [3:0]u8,
};
const b = zeroes(ZigStruct);
try testing.expectEqual(@as(u8, 5), b.comptime_field);
try testing.expectEqual(@as(i8, 0), b.integral_types.integer_8);
try testing.expectEqual(@as(i16, 0), b.integral_types.integer_16);
try testing.expectEqual(@as(i32, 0), b.integral_types.integer_32);
try testing.expectEqual(@as(i64, 0), b.integral_types.integer_64);
try testing.expectEqual(@as(i128, 0), b.integral_types.integer_128);
try testing.expectEqual(@as(u8, 0), b.integral_types.unsigned_0);
try testing.expectEqual(@as(u8, 0), b.integral_types.unsigned_8);
try testing.expectEqual(@as(u16, 0), b.integral_types.unsigned_16);
try testing.expectEqual(@as(u32, 0), b.integral_types.unsigned_32);
try testing.expectEqual(@as(u64, 0), b.integral_types.unsigned_64);
try testing.expectEqual(@as(u128, 0), b.integral_types.unsigned_128);
try testing.expectEqual(@as(f32, 0), b.integral_types.float_32);
try testing.expectEqual(@as(f64, 0), b.integral_types.float_64);
try testing.expectEqual(@as(?*u8, null), b.pointers.optional);
try testing.expectEqual(@as([*c]u8, null), b.pointers.c_pointer);
try testing.expectEqual(@as([]u8, &[_]u8{}), b.pointers.slice);
try testing.expectEqual(@as([:0]const u8, ""), b.pointers.nullTerminatedString);
for (b.array) |e| {
try testing.expectEqual(@as(u32, 0), e);
}
try testing.expectEqual(@as(@TypeOf(b.vector_u32), @splat(0)), b.vector_u32);
try testing.expectEqual(@as(@TypeOf(b.vector_f32), @splat(0.0)), b.vector_f32);
if (!(builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .hexagon)) {
try testing.expectEqual(@as(@TypeOf(b.vector_bool), @splat(false)), b.vector_bool);
}
try testing.expectEqual(@as(?u8, null), b.optional_int);
for (b.sentinel) |e| {
try testing.expectEqual(@as(u8, 0), e);
}
const C_union = extern union {
a: u8,
b: u32,
};
const c = zeroes(C_union);
try testing.expectEqual(@as(u8, 0), c.a);
try testing.expectEqual(@as(u32, 0), c.b);
const comptime_union = comptime zeroes(C_union);
try testing.expectEqual(@as(u8, 0), comptime_union.a);
try testing.expectEqual(@as(u32, 0), comptime_union.b);
// 确保带字段的零大小结构体正确初始化。
_ = zeroes(struct { handle: void });
}
/// 将结构体的所有字段初始化为默认值;未提供默认值时则使用零值。
/// 如果提供的初始值中包含该字段,则使用对应值。
/// 递归初始化结构体。
pub fn zeroInit(comptime T: type, init: anytype) T {
const Init = @TypeOf(init);
switch (@typeInfo(T)) {
.@"struct" => |struct_info| {
switch (@typeInfo(Init)) {
.@"struct" => |init_info| {
if (init_info.is_tuple) {
if (init_info.field_names.len > struct_info.field_names.len) {
@compileError("Tuple initializer has more elements than there are fields in `" ++ @typeName(T) ++ "`");
}
} else {
inline for (init_info.field_names) |field_name| {
if (!@hasField(T, field_name)) {
@compileError("Encountered an initializer for `" ++ field_name ++ "`, but it is not a field of " ++ @typeName(T));
}
}
}
var value: T = if (struct_info.layout == .@"extern") zeroes(T) else undefined;
inline for (
struct_info.field_names,
struct_info.field_types,
struct_info.field_attrs,
0..,
) |f_name, f_type, f_attr, i| {
if (f_attr.@"comptime") {
continue;
}
if (init_info.is_tuple and init_info.field_names.len > i) {
@field(value, f_name) = @field(init, init_info.field_names[i]);
} else if (@hasField(@TypeOf(init), f_name)) {
switch (@typeInfo(f_type)) {
.@"struct" => {
@field(value, f_name) = zeroInit(f_type, @field(init, f_name));
},
else => {
@field(value, f_name) = @field(init, f_name);
},
}
} else if (f_attr.defaultValue(f_type)) |val| {
@field(value, f_name) = val;
} else {
switch (@typeInfo(f_type)) {
.@"struct" => {
@field(value, f_name) = std.mem.zeroInit(f_type, .{});
},
else => {
@field(value, f_name) = std.mem.zeroes(@TypeOf(@field(value, f_name)));
},
}
}
}
return value;
},
else => {
@compileError("The initializer must be a struct");
},
}
},
else => {
@compileError("Can't default init a " ++ @typeName(T));
},
}
}
test zeroInit {
const I = struct {
d: f64,
};
const S = struct {
a: u32,
b: ?bool,
c: I,
e: [3]u8,
f: i64 = -1,
};
const s = zeroInit(S, .{
.a = 42,
});
try testing.expectEqual(S{
.a = 42,
.b = null,
.c = .{
.d = 0,
},
.e = [3]u8{ 0, 0, 0 },
.f = -1,
}, s);
const Color = struct {
r: u8,
g: u8,
b: u8,
a: u8,
};
const c = zeroInit(Color, .{ 255, 255 });
try testing.expectEqual(Color{
.r = 255,
.g = 255,
.b = 0,
.a = 0,
}, c);
const Foo = struct {
foo: u8 = 69,
bar: u8,
};
const f = zeroInit(Foo, .{});
try testing.expectEqual(Foo{
.foo = 69,
.bar = 0,
}, f);
const Bar = struct {
foo: u32 = 666,
bar: u32 = 420,
};
const b = zeroInit(Bar, .{69});
try testing.expectEqual(Bar{
.foo = 69,
.bar = 420,
}, b);
const Baz = struct {
foo: [:0]const u8 = "bar",
};
const baz1 = zeroInit(Baz, .{});
try testing.expectEqual(Baz{}, baz1);
const baz2 = zeroInit(Baz, .{ .foo = "zab" });
try testing.expectEqualSlices(u8, "zab", baz2.foo);
const NestedBaz = struct {
bbb: Baz,
};
const nested_baz = zeroInit(NestedBaz, .{});
try testing.expectEqual(NestedBaz{
.bbb = Baz{},
}, nested_baz);
}
/// 使用稳定算法原地排序切片,保持相等元素的相对顺序。
/// 平均时间复杂度:O(n log n),最坏情况:O(n log n)。
/// 递归调用的空间复杂度:O(log n)。
///
/// 对采用默认顺序的原始类型切片,可考虑直接使用 `std.sort.block`。
/// 不稳定但可能更快的排序参见 `sortUnstable`。
pub fn sort(
comptime T: type,
items: []T,
context: anytype,
comptime lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool,
) void {
std.sort.block(T, items, context, lessThanFn);
}
/// 使用不稳定算法原地排序切片,不保留相等元素的相对顺序。
/// 时间复杂度:最好为 O(n),最坏和平均均为 O(n log n)。
/// 通常比稳定排序快,但相等元素的顺序未定义。
///
/// 使用破坏模式快速排序(PDQ)算法,在多种数据模式下表现良好。
/// 若需要保留相等元素顺序的稳定排序,请使用 `sort`。
pub fn sortUnstable(
comptime T: type,
items: []T,
context: anytype,
comptime lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool,
) void {
std.sort.pdq(T, items, context, lessThanFn);
}
/// TODO: 目前仅调用 `insertionSortContext`。此文件中的块排序实现
/// 需要调整为使用排序上下文。
pub fn sortContext(a: usize, b: usize, context: anytype) void {
std.sort.insertionContext(a, b, context);
}
/// 使用带自定义上下文的不稳定算法,对范围 [a, b) 排序。
/// 这是使用索引而非切片的底层排序接口。
/// 不保留相等元素的相对顺序。
///
/// 上下文必须提供 lessThan(a_idx, b_idx) 和 swap(a_idx, b_idx) 方法。
/// 使用模式规避快速排序 PDQ 算法。
pub fn sortUnstableContext(a: usize, b: usize, context: anytype) void {
std.sort.pdqContext(a, b, context);
}
/// 按字典序比较两个数值切片。O(n)。
pub fn order(comptime T: type, lhs: []const T, rhs: []const T) math.Order {
if (lhs.ptr != rhs.ptr) {
const n = @min(lhs.len, rhs.len);
for (lhs[0..n], rhs[0..n]) |lhs_elem, rhs_elem| {
switch (math.order(lhs_elem, rhs_elem)) {
.eq => continue,
.lt => return .lt,
.gt => return .gt,
}
}
}
return math.order(lhs.len, rhs.len);
}
/// 按字典序比较两个以 NUL 结尾的多元素指针。
pub fn orderZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T) math.Order {
return boundedOrderZ(T, lhs, rhs, std.math.maxInt(usize));
}
/// 按字典序比较两个以 NUL 结尾的多元素指针,直到指定边界。
pub fn boundedOrderZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T, bound: usize) math.Order {
if (lhs == rhs) return .eq;
var i: usize = 0;
while (lhs[i] == rhs[i] and lhs[i] != 0 and i < bound) : (i += 1) {}
return if (i < bound) math.order(lhs[i], rhs[i]) else .eq;
}
test order {
try testing.expect(order(u8, "abcd", "bee") == .lt);
try testing.expect(order(u8, "abc", "abc") == .eq);
try testing.expect(order(u8, "abc", "abc0") == .lt);
try testing.expect(order(u8, "", "") == .eq);
try testing.expect(order(u8, "", "a") == .lt);
const s: []const u8 = "abc";
try testing.expect(order(u8, s, s) == .eq);
try testing.expect(order(u8, s[0..2], s) == .lt);
}
test orderZ {
try testing.expect(orderZ(u8, "abcd", "bee") == .lt);
try testing.expect(orderZ(u8, "abc", "abc") == .eq);
try testing.expect(orderZ(u8, "abc", "abc0") == .lt);
try testing.expect(orderZ(u8, "", "") == .eq);
try testing.expect(orderZ(u8, "", "a") == .lt);
const s: [*:0]const u8 = "abc";
try testing.expect(orderZ(u8, s, s) == .eq);
}
/// 若 lhs < rhs 则返回 true,否则返回 false
pub fn lessThan(comptime T: type, lhs: []const T, rhs: []const T) bool {
return order(T, lhs, rhs) == .lt;
}
test lessThan {
try testing.expect(lessThan(u8, "abcd", "bee"));
try testing.expect(!lessThan(u8, "abc", "abc"));
try testing.expect(lessThan(u8, "abc", "abc0"));
try testing.expect(!lessThan(u8, "", ""));
try testing.expect(lessThan(u8, "", "a"));
}
/// 当 `lhs < rhs` 时返回 `true`,否则返回 `false`;操作对象为以空字符终止的数组。
pub fn lessThanZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T) bool {
return orderZ(T, lhs, rhs) == .lt;
}
test lessThanZ {
try testing.expect(lessThanZ(u8, "abcd", "bee"));
try testing.expect(!lessThanZ(u8, "abc", "abc"));
try testing.expect(lessThanZ(u8, "abc", "abc0"));
try testing.expect(!lessThanZ(u8, "", ""));
try testing.expect(lessThanZ(u8, "", "a"));
}
const use_vectors = switch (builtin.zig_backend) {
// 这些后端尚不支持向量。
.stage2_aarch64,
.stage2_loongarch,
.stage2_powerpc,
.stage2_riscv64,
=> false,
// SPIR-V 后端尚不支持优化路径。
.stage2_spirv => false,
else => true,
};
// 朴素的内存比较实现更有利于模糊测试器找到有价值的输入。
const use_vectors_for_comparison = use_vectors and !builtin.fuzz;
/// 当且仅当切片长度相同,且全部元素通过相等运算符
/// 比较均为 true 时,返回 true。
pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
if (!@inComptime() and @sizeOf(T) != 0 and std.meta.hasUniqueRepresentation(T) and
use_vectors_for_comparison)
{
return eqlBytes(sliceAsBytes(a), sliceAsBytes(b));
}
if (a.len != b.len) return false;
if (a.len == 0) return true;
if (@typeInfo(T) != .float and a.ptr == b.ptr) return true;
for (a, b) |a_elem, b_elem| {
if (a_elem != b_elem) return false;
}
return true;
}
test eql {
try testing.expect(eql(u8, "abcd", "abcd"));
try testing.expect(!eql(u8, "abcdef", "abZdef"));
try testing.expect(!eql(u8, "abcdefg", "abcdef"));
comptime {
try testing.expect(eql(type, &.{ bool, f32 }, &.{ bool, f32 }));
try testing.expect(!eql(type, &.{ bool, f32 }, &.{ f32, bool }));
try testing.expect(!eql(type, &.{ bool, f32 }, &.{bool}));
try testing.expect(eql(comptime_int, &.{ 1, 2, 3 }, &.{ 1, 2, 3 }));
try testing.expect(!eql(comptime_int, &.{ 1, 2, 3 }, &.{ 3, 2, 1 }));
try testing.expect(!eql(comptime_int, &.{1}, &.{ 1, 2 }));
}
try testing.expect(eql(void, &.{ {}, {} }, &.{ {}, {} }));
try testing.expect(!eql(void, &.{{}}, &.{ {}, {} }));
const x: [3]f64 = .{ 42.0, math.nan(f64), 3.1415 };
try testing.expect(!eql(f64, &x, &x));
}
/// std.mem.eql 对字节切片进行了充分优化。
fn eqlBytes(a: []const u8, b: []const u8) bool {
comptime assert(use_vectors_for_comparison);
if (a.len != b.len) return false;
if (a.len == 0 or a.ptr == b.ptr) return true;
if (a.len <= 16) {
if (a.len < 4) {
const x = (a[0] ^ b[0]) | (a[a.len - 1] ^ b[a.len - 1]) | (a[a.len / 2] ^ b[a.len / 2]);
return x == 0;
}
var x: u32 = 0;
for ([_]usize{ 0, a.len - 4, (a.len / 8) * 4, a.len - 4 - ((a.len / 8) * 4) }) |n| {
x |= @as(u32, @bitCast(a[n..][0..4].*)) ^ @as(u32, @bitCast(b[n..][0..4].*));
}
return x == 0;
}
// 确定最快的分块扫描输入方式。
// 支持时使用向量,否则退回 usize/机器字。
const Scan = if (std.simd.suggestVectorLength(u8)) |vec_size|
struct {
pub const size = vec_size;
pub const Chunk = @Vector(size, u8);
pub inline fn isNotEqual(chunk_a: Chunk, chunk_b: Chunk) bool {
return @reduce(.Or, chunk_a != chunk_b);
}
}
else
struct {
pub const size = @sizeOf(usize);
pub const Chunk = usize;
pub inline fn isNotEqual(chunk_a: Chunk, chunk_b: Chunk) bool {
return chunk_a != chunk_b;
}
};
inline for (1..6) |s| {
const n = 16 << s;
if (n <= Scan.size and a.len <= n) {
const V = @Vector(n / 2, u8);
var x = @as(V, a[0 .. n / 2].*) ^ @as(V, b[0 .. n / 2].*);
x |= @as(V, a[a.len - n / 2 ..][0 .. n / 2].*) ^ @as(V, b[a.len - n / 2 ..][0 .. n / 2].*);
const zero: V = @splat(0);
return !@reduce(.Or, x != zero);
}
}
// 分块比较输入(不含最后一块)。
for (0..(a.len - 1) / Scan.size) |i| {
const a_chunk: Scan.Chunk = @bitCast(a[i * Scan.size ..][0..Scan.size].*);
const b_chunk: Scan.Chunk = @bitCast(b[i * Scan.size ..][0..Scan.size].*);
if (Scan.isNotEqual(a_chunk, b_chunk)) return false;
}
// 使用重叠读取比较最后一个块,类似于先前针对其他大小的策略。
const last_a_chunk: Scan.Chunk = @bitCast(a[a.len - Scan.size ..][0..Scan.size].*);
const last_b_chunk: Scan.Chunk = @bitCast(b[a.len - Scan.size ..][0..Scan.size].*);
return !Scan.isNotEqual(last_a_chunk, last_b_chunk);
}
/// 已弃用,改用 `findDiff`。
pub const indexOfDiff = findDiff;
/// 比较两个切片,返回首个不相等位置的索引。
/// 切片相等则返回 null。
pub fn findDiff(comptime T: type, a: []const T, b: []const T) ?usize {
const shorter = @min(a.len, b.len);
if (@typeInfo(T) != .float and a.ptr == b.ptr) {
return if (a.len == b.len) null else shorter;
}
for (a[0..shorter], b[0..shorter], 0..) |a_elem, b_elem, i| {
if (a_elem != b_elem) return i;
}
return if (a.len == b.len) null else shorter;
}
test findDiff {
try testing.expectEqual(null, findDiff(u8, "one", "one"));
try testing.expectEqual(3, findDiff(u8, "one two", "one"));
try testing.expectEqual(3, findDiff(u8, "one", "one two"));
try testing.expectEqual(6, findDiff(u8, "one twx", "one two"));
try testing.expectEqual(0, findDiff(u8, "xne", "one"));
const x: [3]f64 = .{ 42.0, math.nan(f64), 3.1415 };
try testing.expectEqual(1, findDiff(f64, &x, &x));
}
/// 接受以哨兵值结尾的指针,返回保留指针属性的切片。
/// 假定 `[*c]` 指针以 0 结尾,且不具有 allowzero 属性。
fn Span(comptime T: type) type {
switch (@typeInfo(T)) {
.optional => |optional_info| {
return ?Span(optional_info.child);
},
.pointer => |ptr_info| {
const new_sentinel: ?ptr_info.child = switch (ptr_info.size) {
.one, .slice => @compileError("invalid type given to std.mem.span: " ++ @typeName(T)),
.many => ptr_info.sentinel() orelse @compileError("invalid type given to std.mem.span: " ++ @typeName(T)),
.c => 0,
};
var attrs = ptr_info.attrs;
attrs.@"allowzero" = attrs.@"allowzero" and ptr_info.size != .c;
return @Pointer(.slice, attrs, ptr_info.child, new_sentinel);
},
else => {},
}
@compileError("invalid type given to std.mem.span: " ++ @typeName(T));
}
test Span {
try testing.expect(Span([*:1]u16) == [:1]u16);
try testing.expect(Span(?[*:1]u16) == ?[:1]u16);
try testing.expect(Span([*:1]const u8) == [:1]const u8);
try testing.expect(Span(?[*:1]const u8) == ?[:1]const u8);
try testing.expect(Span([*c]u16) == [:0]u16);
try testing.expect(Span(?[*c]u16) == ?[:0]u16);
try testing.expect(Span([*c]const u8) == [:0]const u8);
try testing.expect(Span(?[*c]const u8) == ?[:0]const u8);
}
/// 接受一个以哨兵值结尾的指针,并遍历内存找到哨兵值、确定长度,
/// 然后返回切片。
/// 保留指针属性,例如 const。
/// 假定 `[*c]` 指针非空且以 0 结尾。
pub fn span(ptr: anytype) Span(@TypeOf(ptr)) {
if (@typeInfo(@TypeOf(ptr)) == .optional) {
if (ptr) |non_null| {
return span(non_null);
} else {
return null;
}
}
const Result = Span(@TypeOf(ptr));
const l = len(ptr);
const ptr_info = @typeInfo(Result).pointer;
if (ptr_info.sentinel()) |s| {
return ptr[0..l :s];
} else {
return ptr[0..l];
}
}
test span {
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
const ptr = @as([*:3]u16, array[0..2 :3]);
try testing.expect(eql(u16, span(ptr), &[_]u16{ 1, 2 }));
try testing.expectEqual(@as(?[:0]u16, null), span(@as(?[*:0]u16, null)));
}
/// sliceTo() 返回类型的辅助函数
fn SliceTo(comptime T: type, comptime end: std.meta.Elem(T)) type {
switch (@typeInfo(T)) {
.optional => |optional_info| {
return ?SliceTo(optional_info.child, end);
},
.pointer => |ptr_info| {
const Elem = std.meta.Elem(T);
const have_sentinel: bool = switch (ptr_info.size) {
.one, .slice => if (std.meta.sentinel(T)) |s| s == end else false,
.many => if (std.meta.sentinel(T)) |s| s == end else true,
.c => true,
};
var attrs = ptr_info.attrs;
attrs.@"allowzero" = attrs.@"allowzero" and ptr_info.size != .c;
return @Pointer(.slice, attrs, Elem, if (have_sentinel) end else null);
},
else => {},
}
@compileError("invalid type given to std.mem.sliceTo: " ++ @typeName(T));
}
/// 接受数组指针、多元素指针或切片,返回截止第一次出现 `end` 之前的元素切片。
/// 若未找到 `end`,结果切片包含直到输入长度或哨兵之前的全部元素。
/// 若指针类型没有边界,即没有长度或哨兵,则 `end` 将作为结果切片的哨兵。
/// 若指针类型以 `end` 作为终止哨兵,结果切片也以 `end` 作为终止哨兵。
/// 保留可变性、对齐等指针属性。
/// 假定 C 指针非空。
///
///
///
///
pub fn sliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) SliceTo(@TypeOf(ptr), end) {
if (@typeInfo(@TypeOf(ptr)) == .optional) {
const non_null = ptr orelse return null;
return sliceTo(non_null, end);
}
const Result = SliceTo(@TypeOf(ptr), end);
const length = lenSliceTo(ptr, end);
const ptr_info = @typeInfo(Result).pointer;
if (ptr_info.sentinel()) |s| {
return ptr[0..length :s];
} else {
return ptr[0..length];
}
}
test sliceTo {
try testing.expectEqualSlices(u8, "aoeu", sliceTo("aoeu", 0));
{
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqualSlices(u16, &array, sliceTo(&array, 0));
try testing.expectEqualSlices(u16, array[0..3], sliceTo(array[0..3], 0));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(&array, 3));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(array[0..3], 3));
const many_ptr: [*]u16 = &array;
try testing.expectEqualSlices(u16, array[0..2], sliceTo(many_ptr, 3));
try testing.expectEqual([:3]u16, @TypeOf(sliceTo(many_ptr, 3)));
const sentinel_ptr = @as([*:5]u16, @ptrCast(&array));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(sentinel_ptr, 3));
try testing.expectEqual([]u16, @TypeOf(sliceTo(sentinel_ptr, 3)));
try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_ptr, 5));
try testing.expectEqual([:5]u16, @TypeOf(sliceTo(sentinel_ptr, 5)));
try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_ptr, 99));
const optional_sentinel_ptr = @as(?[*:5]u16, @ptrCast(&array));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(optional_sentinel_ptr, 3).?);
try testing.expectEqualSlices(u16, array[0..4], sliceTo(optional_sentinel_ptr, 99).?);
const c_ptr = @as([*c]u16, &array);
try testing.expectEqualSlices(u16, array[0..2], sliceTo(c_ptr, 3));
try testing.expectEqual([:3]u16, @TypeOf(sliceTo(c_ptr, 3)));
const slice: []u16 = &array;
try testing.expectEqualSlices(u16, array[0..2], sliceTo(slice, 3));
try testing.expectEqualSlices(u16, &array, sliceTo(slice, 99));
const sentinel_slice: [:5]u16 = array[0..4 :5];
try testing.expectEqualSlices(u16, array[0..2], sliceTo(sentinel_slice, 3));
try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_slice, 99));
}
{
var sentinel_array: [5:0]u16 = [_:0]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqualSlices(u16, sentinel_array[0..2], sliceTo(&sentinel_array, 3));
try testing.expectEqualSlices(u16, &sentinel_array, sliceTo(&sentinel_array, 0));
try testing.expectEqualSlices(u16, &sentinel_array, sliceTo(&sentinel_array, 99));
}
try testing.expectEqual(@as(?[]u8, null), sliceTo(@as(?[]u8, null), 0));
}
/// sliceTo() 的私有辅助函数。若需要长度,请使用 sliceTo(foo, x).len。
fn lenSliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) usize {
switch (@typeInfo(@TypeOf(ptr))) {
.pointer => |ptr_info| switch (ptr_info.size) {
.one => switch (@typeInfo(ptr_info.child)) {
.array => |array_info| {
if (array_info.sentinel()) |s| {
if (s == end) {
return findSentinel(array_info.child, end, ptr);
}
}
return findScalar(array_info.child, ptr, end) orelse array_info.len;
},
else => {},
},
.many => if (ptr_info.sentinel()) |s| {
if (s == end) {
return findSentinel(ptr_info.child, end, ptr);
}
// 我们要查找哨兵以外的值,但迭代越过哨兵会构成错误,因此必须同时检查两者。
//
//
var i: usize = 0;
while (ptr[i] != end and ptr[i] != s) i += 1;
return i;
} else {
return findSentinel(ptr_info.child, end, @ptrCast(ptr));
},
.c => {
assert(ptr != null);
return findSentinel(ptr_info.child, end, ptr);
},
.slice => {
if (ptr_info.sentinel()) |s| {
if (s == end) {
return findSentinel(ptr_info.child, s, ptr);
}
}
return findScalar(ptr_info.child, ptr, end) orelse ptr.len;
},
},
else => {},
}
@compileError("invalid type given to std.mem.sliceTo: " ++ @typeName(@TypeOf(ptr)));
}
test lenSliceTo {
try testing.expect(lenSliceTo("aoeu", 0) == 4);
{
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqual(@as(usize, 5), lenSliceTo(&array, 0));
try testing.expectEqual(@as(usize, 3), lenSliceTo(array[0..3], 0));
try testing.expectEqual(@as(usize, 2), lenSliceTo(&array, 3));
try testing.expectEqual(@as(usize, 2), lenSliceTo(array[0..3], 3));
const sentinel_ptr = @as([*:5]u16, @ptrCast(&array));
try testing.expectEqual(@as(usize, 2), lenSliceTo(sentinel_ptr, 3));
try testing.expectEqual(@as(usize, 4), lenSliceTo(sentinel_ptr, 99));
const c_ptr = @as([*c]u16, &array);
try testing.expectEqual(@as(usize, 2), lenSliceTo(c_ptr, 3));
const slice: []u16 = &array;
try testing.expectEqual(@as(usize, 2), lenSliceTo(slice, 3));
try testing.expectEqual(@as(usize, 5), lenSliceTo(slice, 99));
const sentinel_slice: [:5]u16 = array[0..4 :5];
try testing.expectEqual(@as(usize, 2), lenSliceTo(sentinel_slice, 3));
try testing.expectEqual(@as(usize, 4), lenSliceTo(sentinel_slice, 99));
}
{
var sentinel_array: [5:0]u16 = [_:0]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqual(@as(usize, 2), lenSliceTo(&sentinel_array, 3));
try testing.expectEqual(@as(usize, 5), lenSliceTo(&sentinel_array, 0));
try testing.expectEqual(@as(usize, 5), lenSliceTo(&sentinel_array, 99));
}
}
/// 接收哨兵终止指针,遍历内存以查找
/// 哨兵并确定长度。
/// 假定 `[*c]` 指针非空且以 0 终止。
pub fn len(value: anytype) usize {
switch (@typeInfo(@TypeOf(value))) {
.pointer => |info| switch (info.size) {
.many => {
const sentinel = info.sentinel() orelse
@compileError("invalid type given to std.mem.len: " ++ @typeName(@TypeOf(value)));
return findSentinel(info.child, sentinel, value);
},
.c => {
assert(value != null);
return findSentinel(info.child, 0, value);
},
else => @compileError("invalid type given to std.mem.len: " ++ @typeName(@TypeOf(value))),
},
else => @compileError("invalid type given to std.mem.len: " ++ @typeName(@TypeOf(value))),
}
}
test len {
var array: [5]u16 = [_]u16{ 1, 2, 0, 4, 5 };
const ptr = @as([*:4]u16, array[0..3 :4]);
try testing.expect(len(ptr) == 3);
const c_ptr = @as([*c]u16, ptr);
try testing.expect(len(c_ptr) == 2);
}
/// 已弃用,改用 `findSentinel`。
pub const indexOfSentinel = findSentinel;
/// 返回以哨兵终止的指针中哨兵值的索引。
/// 线性搜索内存,直到找到哨兵。
pub fn findSentinel(comptime T: type, comptime sentinel: T, p: [*:sentinel]const T) usize {
var i: usize = 0;
while (p[i] != sentinel) {
i += 1;
}
return i;
}
test "findSentinel vector paths" {
const Types = [_]type{ u8, u16, u32, u64 };
const allocator = std.testing.allocator;
const page_size = std.heap.page_size_min;
inline for (Types) |T| {
const block_len = std.simd.suggestVectorLength(T) orelse continue;
// 分配三页,以保证存在跨页地址,且其后仍有完整一页
const memory = try allocator.alloc(T, 3 * page_size / @sizeOf(T));
defer allocator.free(memory);
@memset(memory, 0xaa);
// 查找起始页对齐值 = 0
var start: usize = 0;
const start_addr = @intFromPtr(&memory);
start += (std.mem.alignForward(usize, start_addr, page_size) - start_addr) / @sizeOf(T);
try testing.expect(start < page_size / @sizeOf(T));
// 验证所有子块的对齐情况
const search_len = page_size / @sizeOf(T);
memory[start + search_len] = 0;
for (0..block_len) |offset| {
try testing.expectEqual(search_len - offset, findSentinel(T, 0, @ptrCast(&memory[start + offset])));
}
memory[start + search_len] = 0xaa;
// 验证跨越页边界的情况
const start_page_boundary = start + (page_size / @sizeOf(T));
memory[start_page_boundary + block_len] = 0;
for (0..block_len) |offset| {
try testing.expectEqual(2 * block_len - offset, findSentinel(T, 0, @ptrCast(&memory[start_page_boundary - block_len + offset])));
}
}
}
/// 如果切片中的所有元素均等于给定标量值,则返回 true。
pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool {
for (slice) |item| {
if (item != scalar) return false;
}
return true;
}
/// 从切片开头移除一组值。
pub fn trimStart(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var begin: usize = 0;
while (begin < slice.len and findScalar(T, values_to_strip, slice[begin]) != null) : (begin += 1) {}
return slice[begin..];
}
test trimStart {
try testing.expectEqualSlices(u8, "foo\n ", trimStart(u8, " foo\n ", " \n"));
}
/// 从切片末尾移除一组值。
pub fn trimEnd(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var end: usize = slice.len;
while (end > 0 and findScalar(T, values_to_strip, slice[end - 1]) != null) : (end -= 1) {}
return slice[0..end];
}
test trimEnd {
try testing.expectEqualSlices(u8, " foo", trimEnd(u8, " foo\n ", " \n"));
}
/// 从切片首尾移除属于某值集合的元素。
pub fn trim(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var begin: usize = 0;
var end: usize = slice.len;
while (begin < end and findScalar(T, values_to_strip, slice[begin]) != null) : (begin += 1) {}
while (end > begin and findScalar(T, values_to_strip, slice[end - 1]) != null) : (end -= 1) {}
return slice[begin..end];
}
test trim {
try testing.expectEqualSlices(u8, "foo", trim(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, "foo", trim(u8, "foo", " \n"));
}
/// 已弃用,改用 `findScalar`。
pub const indexOfScalar = findScalar;
/// 线性查找切片中标量值的索引。
pub fn findScalar(comptime T: type, slice: []const T, value: T) ?usize {
return findScalarPos(T, slice, 0, value);
}
/// 已弃用,请改用 `findScalarLast`。
pub const lastIndexOfScalar = findScalarLast;
/// 线性搜索标量值在切片中最后一次出现的索引。
pub fn findScalarLast(comptime T: type, slice: []const T, value: T) ?usize {
var i: usize = slice.len;
while (i != 0) {
i -= 1;
if (slice[i] == value) return i;
}
return null;
}
/// 已弃用,改用 `findScalarPos`。
pub const indexOfScalarPos = findScalarPos;
/// 从给定位置开始,线性查找切片中标量值的索引。
/// 未找到该值则返回 null。
pub fn findScalarPos(comptime T: type, slice: []const T, start_index: usize, value: T) ?usize {
if (start_index >= slice.len) return null;
var i: usize = start_index;
if (use_vectors_for_comparison and
!std.debug.inValgrind() and // https://github.com/ziglang/zig/issues/17717
!@inComptime() and
(@typeInfo(T) == .int or @typeInfo(T) == .float) and std.math.isPowerOfTwo(@bitSizeOf(T)))
{
if (std.simd.suggestVectorLength(T)) |block_len| {
// 在 Intel Nehalem(2009 年)、AMD Bulldozer(2012 年)及其后续架构上,对齐数据的非对齐加载与对齐加载执行方式相同。这里忽略更旧架构,不额外预先对齐。
//
// 使用 `std.simd.suggestVectorLength(T)` 可获得与此函数相同的对齐要求;除非目标架构因此产生性能损失,否则通常无需这样做。
//
// 其他架构可能不同。例如 Arm 上跨缓存行加载会增加一个周期,因此值得研究显式对齐的前导处理。
//
//
//
// 在此展开循环可提高约 10% 的性能。这样每两个块只需做一次边界检查,
// 而不是每个块一次,累计收益可观。
const Block = @Vector(block_len, T);
if (i + 2 * block_len < slice.len) {
const mask: Block = @splat(value);
while (true) {
inline for (0..2) |_| {
const block: Block = slice[i..][0..block_len].*;
const matches = block == mask;
if (@reduce(.Or, matches)) {
return i + std.simd.firstTrue(matches).?;
}
i += block_len;
}
if (i + 2 * block_len >= slice.len) break;
}
}
// 检查 {block_len, block_len / 2}
inline for (0..2) |j| {
const block_x_len = block_len / (1 << j);
comptime if (block_x_len < 4) break;
const BlockX = @Vector(block_x_len, T);
if (i + block_x_len < slice.len) {
const mask: BlockX = @splat(value);
const block: BlockX = slice[i..][0..block_x_len].*;
const matches = block == mask;
if (@reduce(.Or, matches)) {
return i + std.simd.firstTrue(matches).?;
}
i += block_x_len;
}
}
}
}
for (slice[i..], i..) |c, j| {
if (c == value) return j;
}
return null;
}
test findScalarPos {
const Types = [_]type{ u8, u16, u32, u64 };
inline for (Types) |T| {
var memory: [64 / @sizeOf(T)]T = undefined;
@memset(&memory, 0xaa);
memory[memory.len - 1] = 0;
for (0..memory.len) |i| {
try testing.expectEqual(memory.len - i - 1, findScalarPos(T, memory[i..], 0, 0).?);
}
}
}
/// 已弃用,改用 `findAny`。
pub const indexOfAny = findAny;
/// 线性查找切片中任意给定列表值的索引。
/// 未找到任何值则返回 null。
pub fn findAny(comptime T: type, slice: []const T, values: []const T) ?usize {
return findAnyPos(T, slice, 0, values);
}
/// 已弃用,改用 `findLastAny`。
pub const lastIndexOfAny = findLastAny;
/// 线性搜索切片中所提供列表内任一值的最后一个索引。
/// 若未找到任何值,则返回 null。
pub fn findLastAny(comptime T: type, slice: []const T, values: []const T) ?usize {
var i: usize = slice.len;
while (i != 0) {
i -= 1;
for (values) |value| {
if (slice[i] == value) return i;
}
}
return null;
}
/// 已弃用,请改用 `findAnyPos`。
pub const indexOfAnyPos = findAnyPos;
/// 从给定位置开始,在线性搜索中查找切片内所提供列表中任一值的索引。
/// 若未找到任何值,则返回 null。
pub fn findAnyPos(comptime T: type, slice: []const T, start_index: usize, values: []const T) ?usize {
if (start_index >= slice.len) return null;
for (slice[start_index..], start_index..) |c, i| {
for (values) |value| {
if (c == value) return i;
}
}
return null;
}
/// 已弃用,请使用 `findNone`。
pub const indexOfNone = findNone;
/// 查找 `slice` 中首个不包含于 `values` 的元素。
///
/// 类似 C 标准库中的 `strspn`。
pub fn findNone(comptime T: type, slice: []const T, values: []const T) ?usize {
return findNonePos(T, slice, 0, values);
}
test findNone {
try testing.expect(findNone(u8, "abc123", "123").? == 0);
try testing.expect(findLastNone(u8, "abc123", "123").? == 2);
try testing.expect(findNone(u8, "123abc", "123").? == 3);
try testing.expect(findLastNone(u8, "123abc", "123").? == 5);
try testing.expect(findNone(u8, "123123", "123") == null);
try testing.expect(findNone(u8, "333333", "123") == null);
try testing.expect(findNonePos(u8, "abc123", 3, "321") == null);
}
/// 已弃用,请改用 `findLastNone`。
pub const lastIndexOfNone = findLastNone;
/// 查找 `slice` 中最后一个不包含在 `values` 中的元素。
///
/// 类似于 C 标准库的 `strspn`,但从末尾搜索。
pub fn findLastNone(comptime T: type, slice: []const T, values: []const T) ?usize {
var i: usize = slice.len;
outer: while (i != 0) {
i -= 1;
for (values) |value| {
if (slice[i] == value) continue :outer;
}
return i;
}
return null;
}
pub const indexOfNonePos = findNonePos;
/// 查找 `slice[start_index..]` 中第一个不包含在 `values` 内的元素。
/// 返回索引相对于 `slice` 的起始位置,绝不会小于 `start_index`。
///
/// 类似于 C 标准库的 `strspn`。
pub fn findNonePos(comptime T: type, slice: []const T, start_index: usize, values: []const T) ?usize {
if (start_index >= slice.len) return null;
outer: for (slice[start_index..], start_index..) |c, i| {
for (values) |value| {
if (c == value) continue :outer;
}
return i;
}
return null;
}
/// 已弃用,请使用 `find`。
pub const indexOf = find;
/// 在 haystack 中查找 needle,返回首次出现位置的索引。
/// 对较大输入使用 Boyer-Moore-Horspool 算法,对较小输入使用线性搜索。
/// 若未找到 needle,则返回 null。
pub fn find(comptime T: type, haystack: []const T, needle: []const T) ?usize {
return findPos(T, haystack, 0, needle);
}
/// 已弃用,改用 `findLastLinear`。
pub const lastIndexOfLinear = findLastLinear;
/// 从末尾向前搜索,查找子切片在切片中的索引。
/// 若要从其他索引开始搜索,请先对被搜索切片进行切片。
/// 可考虑改用 `lastIndexOf`,它会在输入较大时
/// 自动采用更精细的算法。
pub fn findLastLinear(comptime T: type, haystack: []const T, needle: []const T) ?usize {
if (needle.len > haystack.len) return null;
var i: usize = haystack.len - needle.len;
while (true) : (i -= 1) {
if (mem.eql(T, haystack[i..][0..needle.len], needle)) return i;
if (i == 0) return null;
}
}
pub const indexOfPosLinear = findPosLinear;
/// 可考虑改用 `findPos`,它会对较大的输入
/// 自动使用更精细的算法。
pub fn findPosLinear(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {
if (needle.len > haystack.len) return null;
var i: usize = start_index;
const end = haystack.len - needle.len;
while (i <= end) : (i += 1) {
if (eql(T, haystack[i..][0..needle.len], needle)) return i;
}
return null;
}
test findPosLinear {
try testing.expectEqual(0, findPosLinear(u8, "", 0, ""));
try testing.expectEqual(0, findPosLinear(u8, "123", 0, ""));
try testing.expectEqual(null, findPosLinear(u8, "", 0, "1"));
try testing.expectEqual(0, findPosLinear(u8, "1", 0, "1"));
try testing.expectEqual(null, findPosLinear(u8, "2", 0, "1"));
try testing.expectEqual(1, findPosLinear(u8, "21", 0, "1"));
try testing.expectEqual(null, findPosLinear(u8, "222", 0, "1"));
try testing.expectEqual(null, findPosLinear(u8, "", 0, "12"));
try testing.expectEqual(null, findPosLinear(u8, "1", 0, "12"));
try testing.expectEqual(null, findPosLinear(u8, "2", 0, "12"));
try testing.expectEqual(0, findPosLinear(u8, "12", 0, "12"));
try testing.expectEqual(null, findPosLinear(u8, "21", 0, "12"));
try testing.expectEqual(1, findPosLinear(u8, "212", 0, "12"));
try testing.expectEqual(0, findPosLinear(u8, "122", 0, "12"));
try testing.expectEqual(1, findPosLinear(u8, "212112", 0, "12"));
}
fn boyerMooreHorspoolPreprocessReverse(pattern: []const u8, table: *[256]usize) void {
for (table) |*c| {
c.* = pattern.len;
}
var i: usize = pattern.len - 1;
// 有意忽略首个元素,跳跃大小为 pattern.len。
// 这是 Boyer-Moore-Horspool 的标准实现方式。
while (i > 0) : (i -= 1) {
table[pattern[i]] = i;
}
}
fn boyerMooreHorspoolPreprocess(pattern: []const u8, table: *[256]usize) void {
for (table) |*c| {
c.* = pattern.len;
}
var i: usize = 0;
// 有意忽略最后一个元素,跳跃大小为 pattern.len。
// 这是 Boyer-Moore-Horspool 的标准实现方式。
while (i < pattern.len - 1) : (i += 1) {
table[pattern[i]] = pattern.len - 1 - i;
}
}
/// 已弃用,请使用 `find`。
pub const lastIndexOf = findLast;
/// 从末尾向前搜索,查找子切片在切片中的索引。
/// 要从其他索引开始搜索,请先对待搜索数据取切片。
/// 较大输入使用反向 Boyer-Moore-Horspool 算法;
/// 较小输入使用 `lastIndexOfLinear`。
pub fn findLast(comptime T: type, haystack: []const T, needle: []const T) ?usize {
if (needle.len > haystack.len) return null;
if (needle.len == 0) return haystack.len;
if (!std.meta.hasUniqueRepresentation(T) or haystack.len < 52 or needle.len <= 4)
return findLastLinear(T, haystack, needle);
const haystack_bytes = sliceAsBytes(haystack);
const needle_bytes = sliceAsBytes(needle);
var skip_table: [256]usize = undefined;
boyerMooreHorspoolPreprocessReverse(needle_bytes, skip_table[0..]);
var i: usize = haystack_bytes.len - needle_bytes.len;
while (true) {
if (i % @sizeOf(T) == 0 and mem.eql(u8, haystack_bytes[i .. i + needle_bytes.len], needle_bytes)) {
return @divExact(i, @sizeOf(T));
}
const skip = skip_table[haystack_bytes[i]];
if (skip > i) break;
i -= skip;
}
return null;
}
/// 已弃用,改用 `findPos`。
pub const indexOfPos = findPos;
/// 对大输入使用 Boyer-Moore-Horspool 算法;对小输入使用 `findPosLinear`。
pub fn findPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {
if (needle.len > haystack.len) return null;
if (needle.len < 2) {
if (needle.len == 0) return start_index;
// findScalarPos 明显快于 findPosLinear。
return findScalarPos(T, haystack, start_index, needle[0]);
}
if (!std.meta.hasUniqueRepresentation(T) or haystack.len < 52 or needle.len <= 4)
return findPosLinear(T, haystack, start_index, needle);
const haystack_bytes = sliceAsBytes(haystack);
const needle_bytes = sliceAsBytes(needle);
var skip_table: [256]usize = undefined;
boyerMooreHorspoolPreprocess(needle_bytes, skip_table[0..]);
var i: usize = start_index * @sizeOf(T);
while (i <= haystack_bytes.len - needle_bytes.len) {
if (i % @sizeOf(T) == 0 and mem.eql(u8, haystack_bytes[i .. i + needle_bytes.len], needle_bytes)) {
return @divExact(i, @sizeOf(T));
}
i += skip_table[haystack_bytes[i + needle_bytes.len - 1]];
}
return null;
}
test find {
try testing.expect(find(u8, "one two three four five six seven eight nine ten eleven", "three four").? == 8);
try testing.expect(findLast(u8, "one two three four five six seven eight nine ten eleven", "three four").? == 8);
try testing.expect(find(u8, "one two three four five six seven eight nine ten eleven", "two two") == null);
try testing.expect(findLast(u8, "one two three four five six seven eight nine ten eleven", "two two") == null);
try testing.expect(find(u8, "one two three four five six seven eight nine ten", "").? == 0);
try testing.expect(findLast(u8, "one two three four five six seven eight nine ten", "").? == 48);
try testing.expect(find(u8, "one two three four", "four").? == 14);
try testing.expect(findLast(u8, "one two three two four", "two").? == 14);
try testing.expect(find(u8, "one two three four", "gour") == null);
try testing.expect(findLast(u8, "one two three four", "gour") == null);
try testing.expect(find(u8, "foo", "foo").? == 0);
try testing.expect(findLast(u8, "foo", "foo").? == 0);
try testing.expect(find(u8, "foo", "fool") == null);
try testing.expect(findLast(u8, "foo", "lfoo") == null);
try testing.expect(findLast(u8, "foo", "fool") == null);
try testing.expect(find(u8, "foo foo", "foo").? == 0);
try testing.expect(findLast(u8, "foo foo", "foo").? == 4);
try testing.expect(findLastAny(u8, "boo, cat", "abo").? == 6);
try testing.expect(findScalarLast(u8, "boo", 'o').? == 2);
}
test "find multibyte" {
{
// 使 haystack 和 needle 足够长,以触发 Boyer-Moore-Horspool 算法
const haystack = @as([100]u16, @splat(0)) ++ [_]u16{ 0xbbaa, 0xccbb, 0xddcc, 0xeedd, 0xffee, 0x00ff };
const needle = [_]u16{ 0xbbaa, 0xccbb, 0xddcc, 0xeedd, 0xffee };
try testing.expectEqual(findPos(u16, &haystack, 0, &needle), 100);
// 检查未对齐时的误报(小端和大端)
const needleLE = [_]u16{ 0xbbbb, 0xcccc, 0xdddd, 0xeeee, 0xffff };
try testing.expectEqual(findPos(u16, &haystack, 0, &needleLE), null);
const needleBE = [_]u16{ 0xaacc, 0xbbdd, 0xccee, 0xddff, 0xee00 };
try testing.expectEqual(findPos(u16, &haystack, 0, &needleBE), null);
}
{
// 使 haystack 和 needle 足够长,以触发 Boyer-Moore-Horspool 算法
const haystack = [_]u16{ 0xbbaa, 0xccbb, 0xddcc, 0xeedd, 0xffee, 0x00ff } ++ @as([100]u16, @splat(0));
const needle = [_]u16{ 0xbbaa, 0xccbb, 0xddcc, 0xeedd, 0xffee };
try testing.expectEqual(findLast(u16, &haystack, &needle), 0);
// 检查未对齐时的误报(小端和大端)
const needleLE = [_]u16{ 0xbbbb, 0xcccc, 0xdddd, 0xeeee, 0xffff };
try testing.expectEqual(findLast(u16, &haystack, &needleLE), null);
const needleBE = [_]u16{ 0xaacc, 0xbbdd, 0xccee, 0xddff, 0xee00 };
try testing.expectEqual(findLast(u16, &haystack, &needleBE), null);
}
}
test "findPos empty needle" {
try testing.expectEqual(findPos(u8, "abracadabra", 5, ""), 5);
}
/// 返回 haystack 中 needle 的数量
/// needle.len 必须 > 0
/// 不计入重叠的 needle
pub fn count(comptime T: type, haystack: []const T, needle: []const T) usize {
if (needle.len == 1) return countScalar(T, haystack, needle[0]);
assert(needle.len > 0);
var i: usize = 0;
var found: usize = 0;
while (findPos(T, haystack, i, needle)) |idx| {
i = idx + needle.len;
found += 1;
}
return found;
}
test count {
try testing.expect(count(u8, "", "h") == 0);
try testing.expect(count(u8, "h", "h") == 1);
try testing.expect(count(u8, "hh", "h") == 2);
try testing.expect(count(u8, "world!", "hello") == 0);
try testing.expect(count(u8, "hello world!", "hello") == 1);
try testing.expect(count(u8, " abcabc abc", "abc") == 3);
try testing.expect(count(u8, "udexdcbvbruhasdrw", "bruh") == 1);
try testing.expect(count(u8, "foo bar", "o bar") == 1);
try testing.expect(count(u8, "foofoofoo", "foo") == 3);
try testing.expect(count(u8, "fffffff", "ff") == 3);
try testing.expect(count(u8, "owowowu", "owowu") == 1);
}
/// 返回 `element` 在内存切片中的出现次数。
pub fn countScalar(comptime T: type, list: []const T, element: T) usize {
const n = list.len;
var i: usize = 0;
var found: usize = 0;
if (use_vectors_for_comparison and
(@typeInfo(T) == .int or @typeInfo(T) == .float) and std.math.isPowerOfTwo(@bitSizeOf(T)))
{
if (std.simd.suggestVectorLength(T)) |block_size| {
const Block = @Vector(block_size, T);
const letter_mask: Block = @splat(element);
while (n - i >= block_size) : (i += block_size) {
const haystack_block: Block = list[i..][0..block_size].*;
found += std.simd.countTrues(letter_mask == haystack_block);
}
}
}
for (list[i..n]) |item| {
found += @intFromBool(item == element);
}
return found;
}
test countScalar {
try testing.expectEqual(0, countScalar(u8, "", 'h'));
try testing.expectEqual(1, countScalar(u8, "h", 'h'));
try testing.expectEqual(2, countScalar(u8, "hh", 'h'));
try testing.expectEqual(2, countScalar(u8, "ahhb", 'h'));
try testing.expectEqual(3, countScalar(u8, " abcabc abc", 'b'));
}
/// 若 haystack 中至少存在 expected_count 个 needle,则返回 true
/// needle.len 必须 > 0
/// 不计算重叠匹配
//
/// 另见:`containsAtLeastScalar`
pub fn containsAtLeast(comptime T: type, haystack: []const T, expected_count: usize, needle: []const T) bool {
if (needle.len == 1) return containsAtLeastScalar(T, haystack, needle[0], expected_count);
assert(needle.len > 0);
if (expected_count == 0) return true;
var i: usize = 0;
var found: usize = 0;
while (findPos(T, haystack, i, needle)) |idx| {
i = idx + needle.len;
found += 1;
if (found == expected_count) return true;
}
return false;
}
test containsAtLeast {
try testing.expect(containsAtLeast(u8, "aa", 0, "a"));
try testing.expect(containsAtLeast(u8, "aa", 1, "a"));
try testing.expect(containsAtLeast(u8, "aa", 2, "a"));
try testing.expect(!containsAtLeast(u8, "aa", 3, "a"));
try testing.expect(containsAtLeast(u8, "radaradar", 1, "radar"));
try testing.expect(!containsAtLeast(u8, "radaradar", 2, "radar"));
try testing.expect(containsAtLeast(u8, "radarradaradarradar", 3, "radar"));
try testing.expect(!containsAtLeast(u8, "radarradaradarradar", 4, "radar"));
try testing.expect(containsAtLeast(u8, " radar radar ", 2, "radar"));
try testing.expect(!containsAtLeast(u8, " radar radar ", 3, "radar"));
}
/// 若 `element` 在 `list` 中至少出现 `minimum` 次,则返回 true。
//
/// 相关接口:
/// * `containsAtLeast`
/// * `countScalar`
pub fn containsAtLeastScalar(comptime T: type, list: []const T, element: T, minimum: usize) bool {
const n = list.len;
var i: usize = 0;
var found: usize = 0;
if (use_vectors_for_comparison and
(@typeInfo(T) == .int or @typeInfo(T) == .float) and std.math.isPowerOfTwo(@bitSizeOf(T)))
{
if (std.simd.suggestVectorLength(T)) |block_size| {
const Block = @Vector(block_size, T);
const letter_mask: Block = @splat(element);
while (n - i >= block_size) : (i += block_size) {
const haystack_block: Block = list[i..][0..block_size].*;
found += std.simd.countTrues(letter_mask == haystack_block);
if (found >= minimum) return true;
}
}
}
for (list[i..n]) |item| {
found += @intFromBool(item == element);
if (found >= minimum) return true;
}
return false;
}
test containsAtLeastScalar {
try testing.expect(containsAtLeastScalar(u8, "aa", 'a', 0));
try testing.expect(containsAtLeastScalar(u8, "aa", 'a', 1));
try testing.expect(containsAtLeastScalar(u8, "aa", 'a', 2));
try testing.expect(!containsAtLeastScalar(u8, "aa", 'a', 3));
try testing.expect(containsAtLeastScalar(u8, "adadda", 'd', 3));
try testing.expect(!containsAtLeastScalar(u8, "adadda", 'd', 4));
}
/// 从内存中读取大小等于 bytes.len 的整数。
/// ReturnType 指定返回类型,且必须足够大以存储结果。
///
pub fn readVarInt(comptime ReturnType: type, bytes: []const u8, endian: Endian) ReturnType {
assert(@typeInfo(ReturnType).int.bits >= bytes.len * 8);
const bits = @typeInfo(ReturnType).int.bits;
const signedness = @typeInfo(ReturnType).int.signedness;
const WorkType = @Int(signedness, @max(16, bits));
var result: WorkType = 0;
switch (endian) {
.big => {
for (bytes) |b| {
result = (result << 8) | b;
}
},
.little => {
const ShiftType = math.Log2Int(WorkType);
for (bytes, 0..) |b, index| {
result = result | (@as(WorkType, b) << @as(ShiftType, @intCast(index * 8)));
}
},
}
return @truncate(result);
}
test readVarInt {
try testing.expect(readVarInt(u0, &[_]u8{}, .big) == 0x0);
try testing.expect(readVarInt(u0, &[_]u8{}, .little) == 0x0);
try testing.expect(readVarInt(u8, &[_]u8{0x12}, .big) == 0x12);
try testing.expect(readVarInt(u8, &[_]u8{0xde}, .little) == 0xde);
try testing.expect(readVarInt(u16, &[_]u8{ 0x12, 0x34 }, .big) == 0x1234);
try testing.expect(readVarInt(u16, &[_]u8{ 0x12, 0x34 }, .little) == 0x3412);
try testing.expect(readVarInt(i8, &[_]u8{0xff}, .big) == -1);
try testing.expect(readVarInt(i8, &[_]u8{0xfe}, .little) == -2);
try testing.expect(readVarInt(i16, &[_]u8{ 0xff, 0xfd }, .big) == -3);
try testing.expect(readVarInt(i16, &[_]u8{ 0xfc, 0xff }, .little) == -4);
// 返回类型可以大于所需大小(bytes.len * 8 < @typeInfo(ReturnType).int.bits)
try testing.expect(readVarInt(u9, &[_]u8{0x12}, .little) == 0x12);
try testing.expect(readVarInt(u9, &[_]u8{0xde}, .big) == 0xde);
try testing.expect(readVarInt(u80, &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 }, .big) == 0x123456789abcdef024);
try testing.expect(readVarInt(u80, &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe }, .little) == 0xfedcba9876543210ec);
try testing.expect(readVarInt(i9, &[_]u8{0xff}, .big) == 0xff);
try testing.expect(readVarInt(i9, &[_]u8{0xfe}, .little) == 0xfe);
}
/// 按给定 bit_count、bit_offset 和有符号性,从紧凑内存加载整数。
/// 断言 T 足够大,能存储读取的值。
pub fn readVarPackedInt(
comptime T: type,
bytes: []const u8,
bit_offset: usize,
bit_count: usize,
endian: std.builtin.Endian,
signedness: std.builtin.Signedness,
) T {
const uN = @Int(.unsigned, @bitSizeOf(T));
const iN = @Int(.signed, @bitSizeOf(T));
const Log2N = std.math.Log2Int(T);
const read_size = (bit_count + (bit_offset % 8) + 7) / 8;
const bit_shift = @as(u3, @intCast(bit_offset % 8));
const pad = @as(Log2N, @intCast(@bitSizeOf(T) - bit_count));
const lowest_byte = switch (endian) {
.big => bytes.len - (bit_offset / 8) - read_size,
.little => bit_offset / 8,
};
const read_bytes = bytes[lowest_byte..][0..read_size];
if (@bitSizeOf(T) <= 8) {
// 与下面执行的移位/掩码操作相同,但在必要处添加 `@truncate`/`@intCast`,
// 因为 int 小于一个字节。
const value: uN = if (read_size == 1) b: {
break :b @truncate(read_bytes[0] >> bit_shift);
} else b: {
const i: u1 = @intFromBool(endian == .big);
const head: uN = @truncate(read_bytes[i] >> bit_shift);
const tail_shift: Log2N = @intCast(@as(u4, 8) - bit_shift);
const tail: uN = @truncate(read_bytes[1 - i]);
break :b (tail << tail_shift) | head;
};
switch (signedness) {
.signed => return @intCast((@as(iN, @bitCast(value)) << pad) >> pad),
.unsigned => return @intCast((value << pad) >> pad),
}
}
// 按正确端序复制出值,并计入 bit_shift
var int: uN = 0;
switch (endian) {
.big => {
for (read_bytes[0 .. read_size - 1]) |elem| {
int = elem | (int << 8);
}
int = (read_bytes[read_size - 1] >> bit_shift) | (int << (@as(u4, 8) - bit_shift));
},
.little => {
int = read_bytes[0] >> bit_shift;
for (read_bytes[1..], 0..) |elem, i| {
int |= (@as(uN, elem) << @as(Log2N, @intCast((8 * (i + 1) - bit_shift))));
}
},
}
switch (signedness) {
.signed => return @intCast((@as(iN, @bitCast(int)) << pad) >> pad),
.unsigned => return @intCast((int << pad) >> pad),
}
}
test readVarPackedInt {
const T = packed struct(u16) { a: u3, b: u7, c: u6 };
var st = T{ .a = 1, .b = 2, .c = 4 };
const b_field = readVarPackedInt(u64, std.mem.asBytes(&st), @bitOffsetOf(T, "b"), 7, builtin.cpu.arch.endian(), .unsigned);
try std.testing.expectEqual(st.b, b_field);
}
/// 从内存读取整数,其比特数由 T 指定。
/// T 的比特数必须可被 8 整除。
/// 此函数不会失败,也不会导致未定义行为。
pub inline fn readInt(comptime T: type, buffer: *const [@divExact(@typeInfo(T).int.bits, 8)]u8, endian: Endian) T {
// Zig 的逻辑位序与小端字节数组一致,因此以大端序读取时,
// 必须先用 `@bitCast` 转为整数,再执行 `@byteSwap`。
const little_val: T = @bitCast(buffer.*);
return switch (endian) {
.little => little_val,
.big => @byteSwap(little_val),
};
}
test readInt {
try testing.expect(readInt(u0, &[_]u8{}, .big) == 0x0);
try testing.expect(readInt(u0, &[_]u8{}, .little) == 0x0);
try testing.expect(readInt(u8, &[_]u8{0x32}, .big) == 0x32);
try testing.expect(readInt(u8, &[_]u8{0x12}, .little) == 0x12);
try testing.expect(readInt(u16, &[_]u8{ 0x12, 0x34 }, .big) == 0x1234);
try testing.expect(readInt(u16, &[_]u8{ 0x12, 0x34 }, .little) == 0x3412);
try testing.expect(readInt(u72, &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 }, .big) == 0x123456789abcdef024);
try testing.expect(readInt(u72, &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe }, .little) == 0xfedcba9876543210ec);
try testing.expect(readInt(i8, &[_]u8{0xff}, .big) == -1);
try testing.expect(readInt(i8, &[_]u8{0xfe}, .little) == -2);
try testing.expect(readInt(i16, &[_]u8{ 0xff, 0xfd }, .big) == -3);
try testing.expect(readInt(i16, &[_]u8{ 0xfc, 0xff }, .little) == -4);
try moreReadIntTests();
try comptime moreReadIntTests();
}
fn readPackedIntLittle(comptime T: type, bytes: []const u8, bit_offset: usize) T {
const uN = @Int(.unsigned, @bitSizeOf(T));
const Log2N = std.math.Log2Int(T);
const bit_count = @as(usize, @bitSizeOf(T));
const bit_shift = @as(u3, @intCast(bit_offset % 8));
const load_size = @divCeil(bit_count, 8);
const load_tail_bits = @as(u3, @intCast((load_size * 8) - bit_count));
const LoadInt = @Int(.unsigned, load_size * 8);
if (bit_count == 0)
return 0;
// 先加载 LoadInt 以读取;若 bit_offset 使读取跨越字节边界,
// 再读取 1 字节尾部。
const read_bytes = bytes[bit_offset / 8 ..];
const val: uN = @truncate(readInt(LoadInt, read_bytes[0..load_size], .little) >> bit_shift);
if (bit_shift > load_tail_bits) {
const tail_bits = @as(Log2N, @intCast(bit_shift - load_tail_bits));
const tail_byte = read_bytes[load_size];
const tail_truncated = if (bit_count < 8) @as(uN, @truncate(tail_byte)) else @as(uN, tail_byte);
return @bitCast(val | (tail_truncated << (@as(Log2N, @truncate(bit_count)) -% tail_bits)));
} else {
return @bitCast(val);
}
}
fn readPackedIntBig(comptime T: type, bytes: []const u8, bit_offset: usize) T {
const uN = @Int(.unsigned, @bitSizeOf(T));
const Log2N = std.math.Log2Int(T);
const bit_count = @as(usize, @bitSizeOf(T));
const bit_shift = @as(u3, @intCast(bit_offset % 8));
const byte_count = @divCeil(@as(usize, bit_shift) + bit_count, 8);
const load_size = @divCeil(bit_count, 8);
const load_tail_bits = @as(u3, @intCast((load_size * 8) - bit_count));
const LoadInt = @Int(.unsigned, load_size * 8);
if (bit_count == 0)
return 0;
// 先加载 LoadInt 以读取;若 bit_offset 使读取跨越字节边界,
// 再读取 1 字节尾部。
const end = bytes.len - (bit_offset / 8);
const read_bytes = bytes[(end - byte_count)..end];
const val = @as(uN, @truncate(readInt(LoadInt, bytes[(end - load_size)..end][0..load_size], .big) >> bit_shift));
if (bit_shift > load_tail_bits) {
const tail_bits = @as(Log2N, @intCast(bit_shift - load_tail_bits));
const tail_byte = if (bit_count < 8) @as(uN, @truncate(read_bytes[0])) else @as(uN, read_bytes[0]);
return @bitCast(val | (tail_byte << (@as(Log2N, @truncate(bit_count)) -% tail_bits)));
} else {
return @bitCast(val);
}
}
/// 从打包内存中加载整数。
/// 断言缓冲区至少包含 bit_offset + @bitSizeOf(T) 位。
pub fn readPackedInt(comptime T: type, bytes: []const u8, bit_offset: usize, endian: Endian) T {
switch (endian) {
.little => return readPackedIntLittle(T, bytes, bit_offset),
.big => return readPackedIntBig(T, bytes, bit_offset),
}
}
test readPackedInt {
const T = packed struct(u16) { a: u3, b: u7, c: u6 };
var st = T{ .a = 1, .b = 2, .c = 4 };
const b_field = readPackedInt(u7, std.mem.asBytes(&st), @bitOffsetOf(T, "b"), builtin.cpu.arch.endian());
try std.testing.expectEqual(st.b, b_field);
}
test "comptime read/write int" {
comptime {
var bytes: [2]u8 = undefined;
writeInt(u16, &bytes, 0x1234, .little);
const result = readInt(u16, &bytes, .big);
try testing.expect(result == 0x3412);
}
comptime {
var bytes: [2]u8 = undefined;
writeInt(u16, &bytes, 0x1234, .big);
const result = readInt(u16, &bytes, .little);
try testing.expect(result == 0x3412);
}
}
/// 将整数以二进制补码形式写入内存。
/// 此函数始终成功,对所有输入均有定义行为,但
/// 整数位宽必须能被 8 整除。
pub inline fn writeInt(comptime T: type, buffer: *[@divExact(@typeInfo(T).int.bits, 8)]u8, value: T, endian: Endian) void {
// Zig 的逻辑位序与小端字节数组一致,因此以大端序写入时,
// 必须先对整数执行 `@byteSwap`,再用 `@bitCast` 转换为数组。
buffer.* = switch (endian) {
.little => @bitCast(value),
.big => @bitCast(@byteSwap(value)),
};
}
test writeInt {
var buf0: [0]u8 = undefined;
var buf1: [1]u8 = undefined;
var buf2: [2]u8 = undefined;
var buf9: [9]u8 = undefined;
writeInt(u0, &buf0, 0x0, .big);
try testing.expect(eql(u8, buf0[0..], &[_]u8{}));
writeInt(u0, &buf0, 0x0, .little);
try testing.expect(eql(u8, buf0[0..], &[_]u8{}));
writeInt(u8, &buf1, 0x12, .big);
try testing.expect(eql(u8, buf1[0..], &[_]u8{0x12}));
writeInt(u8, &buf1, 0x34, .little);
try testing.expect(eql(u8, buf1[0..], &[_]u8{0x34}));
writeInt(u16, &buf2, 0x1234, .big);
try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0x12, 0x34 }));
writeInt(u16, &buf2, 0x5678, .little);
try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0x78, 0x56 }));
writeInt(u72, &buf9, 0x123456789abcdef024, .big);
try testing.expect(eql(u8, buf9[0..], &[_]u8{ 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x24 }));
writeInt(u72, &buf9, 0xfedcba9876543210ec, .little);
try testing.expect(eql(u8, buf9[0..], &[_]u8{ 0xec, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe }));
writeInt(i8, &buf1, -1, .big);
try testing.expect(eql(u8, buf1[0..], &[_]u8{0xff}));
writeInt(i8, &buf1, -2, .little);
try testing.expect(eql(u8, buf1[0..], &[_]u8{0xfe}));
writeInt(i16, &buf2, -3, .big);
try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0xff, 0xfd }));
writeInt(i16, &buf2, -4, .little);
try testing.expect(eql(u8, buf2[0..], &[_]u8{ 0xfc, 0xff }));
}
fn writePackedIntLittle(comptime T: type, bytes: []u8, bit_offset: usize, value: T) void {
const uN = @Int(.unsigned, @bitSizeOf(T));
const Log2N = std.math.Log2Int(T);
const bit_count = @as(usize, @bitSizeOf(T));
const bit_shift = @as(u3, @intCast(bit_offset % 8));
const store_size = (@bitSizeOf(T) + 7) / 8;
const store_tail_bits = @as(u3, @intCast((store_size * 8) - bit_count));
const StoreInt = @Int(.unsigned, store_size * 8);
if (bit_count == 0)
return;
// 先存储 StoreInt 以写入;若 bit_offset 使写入跨越字节边界,
// 再写入 1 字节尾部。
const write_bytes = bytes[bit_offset / 8 ..];
const head = write_bytes[0] & ((@as(u8, 1) << bit_shift) - 1);
var write_value = (@as(StoreInt, @as(uN, @bitCast(value))) << bit_shift) | @as(StoreInt, @intCast(head));
if (bit_shift > store_tail_bits) {
const tail_len = @as(Log2N, @intCast(bit_shift - store_tail_bits));
write_bytes[store_size] &= ~((@as(u8, 1) << @as(u3, @intCast(tail_len))) - 1);
write_bytes[store_size] |= @as(u8, @intCast((@as(uN, @bitCast(value)) >> (@as(Log2N, @truncate(bit_count)) -% tail_len))));
} else if (bit_shift < store_tail_bits) {
const tail_len = store_tail_bits - bit_shift;
const tail = write_bytes[store_size - 1] & (@as(u8, 0xfe) << (7 - tail_len));
write_value |= @as(StoreInt, tail) << (8 * (store_size - 1));
}
writeInt(StoreInt, write_bytes[0..store_size], write_value, .little);
}
fn writePackedIntBig(comptime T: type, bytes: []u8, bit_offset: usize, value: T) void {
const uN = @Int(.unsigned, @bitSizeOf(T));
const Log2N = std.math.Log2Int(T);
const bit_count = @as(usize, @bitSizeOf(T));
const bit_shift = @as(u3, @intCast(bit_offset % 8));
const byte_count = (bit_shift + bit_count + 7) / 8;
const store_size = (@bitSizeOf(T) + 7) / 8;
const store_tail_bits = @as(u3, @intCast((store_size * 8) - bit_count));
const StoreInt = @Int(.unsigned, store_size * 8);
if (bit_count == 0)
return;
// 先存储 StoreInt 以写入;若 bit_offset 使写入跨越字节边界,
// 再写入 1 字节尾部。
const end = bytes.len - (bit_offset / 8);
const write_bytes = bytes[(end - byte_count)..end];
const head = write_bytes[byte_count - 1] & ((@as(u8, 1) << bit_shift) - 1);
var write_value = (@as(StoreInt, @as(uN, @bitCast(value))) << bit_shift) | @as(StoreInt, @intCast(head));
if (bit_shift > store_tail_bits) {
const tail_len = @as(Log2N, @intCast(bit_shift - store_tail_bits));
write_bytes[0] &= ~((@as(u8, 1) << @as(u3, @intCast(tail_len))) - 1);
write_bytes[0] |= @as(u8, @intCast((@as(uN, @bitCast(value)) >> (@as(Log2N, @truncate(bit_count)) -% tail_len))));
} else if (bit_shift < store_tail_bits) {
const tail_len = store_tail_bits - bit_shift;
const tail = write_bytes[0] & (@as(u8, 0xfe) << (7 - tail_len));
write_value |= @as(StoreInt, tail) << (8 * (store_size - 1));
}
writeInt(StoreInt, write_bytes[(byte_count - store_size)..][0..store_size], write_value, .big);
}
/// 将整数存储到打包内存中。
/// 断言缓冲区至少包含 bit_offset + @bitSizeOf(T) 位。
pub fn writePackedInt(comptime T: type, bytes: []u8, bit_offset: usize, value: T, endian: Endian) void {
switch (endian) {
.little => writePackedIntLittle(T, bytes, bit_offset, value),
.big => writePackedIntBig(T, bytes, bit_offset, value),
}
}
test writePackedInt {
const T = packed struct(u16) { a: u3, b: u7, c: u6 };
var st = T{ .a = 1, .b = 2, .c = 4 };
writePackedInt(u7, std.mem.asBytes(&st), @bitOffsetOf(T, "b"), 0x7f, builtin.cpu.arch.endian());
try std.testing.expectEqual(T{ .a = 1, .b = 0x7f, .c = 4 }, st);
}
/// 按给定 bit_offset、bit_count 和有符号性,将整数存入紧凑内存。
/// 若为负数,则对写入值进行符号扩展。
pub fn writeVarPackedInt(bytes: []u8, bit_offset: usize, bit_count: usize, value: anytype, endian: std.builtin.Endian) void {
const T = @TypeOf(value);
const uN = @Int(.unsigned, @bitSizeOf(T));
const bit_shift = @as(u3, @intCast(bit_offset % 8));
const write_size = (bit_count + bit_shift + 7) / 8;
const lowest_byte = switch (endian) {
.big => bytes.len - (bit_offset / 8) - write_size,
.little => bit_offset / 8,
};
const write_bytes = bytes[lowest_byte..][0..write_size];
if (write_size == 0) {
return;
} else if (write_size == 1) {
// 单字节写入单独处理,因为需要对该字节
// 两端的位进行掩码处理。
const mask = (@as(u8, 0xff) >> @as(u3, @intCast(8 - bit_count)));
const new_bits = @as(u8, @intCast(@as(uN, @bitCast(value)) & mask)) << bit_shift;
write_bytes[0] = (write_bytes[0] & ~(mask << bit_shift)) | new_bits;
return;
}
var remaining: T = value;
// 小端序时正向遍历字节,大端序时反向遍历
const delta: i2 = if (endian == .big) -1 else 1;
const start = if (endian == .big) @as(isize, @intCast(write_bytes.len - 1)) else 0;
var i: isize = start; // isize 用于有符号索引运算
// 写入首字节,使用掩码保护 bit_offset 之前的位
const head_mask = @as(u8, 0xff) >> bit_shift;
write_bytes[@intCast(i)] &= ~(head_mask << bit_shift);
write_bytes[@intCast(i)] |= @as(u8, @intCast(@as(uN, @bitCast(remaining)) & head_mask)) << bit_shift;
remaining = math.shr(T, remaining, @as(u4, 8) - bit_shift);
i += delta;
// 写入 bytes[1..bytes.len - 1]
if (@bitSizeOf(T) > 8) {
const loop_end = start + delta * (@as(isize, @intCast(write_size)) - 1);
while (i != loop_end) : (i += delta) {
write_bytes[@as(usize, @intCast(i))] = @as(u8, @truncate(@as(uN, @bitCast(remaining))));
remaining >>= 8;
}
}
// 写入最后一个字节,使用掩码保护 bit_offset + bit_count 之后的位
const following_bits = -%@as(u3, @truncate(bit_shift + bit_count));
const tail_mask = (@as(u8, 0xff) << following_bits) >> following_bits;
write_bytes[@as(usize, @intCast(i))] &= ~tail_mask;
write_bytes[@as(usize, @intCast(i))] |= @as(u8, @intCast(@as(uN, @bitCast(remaining)) & tail_mask));
}
test writeVarPackedInt {
const T = packed struct(u16) { a: u3, b: u7, c: u6 };
var st = T{ .a = 1, .b = 2, .c = 4 };
const value: u64 = 0x7f;
writeVarPackedInt(std.mem.asBytes(&st), @bitOffsetOf(T, "b"), 7, value, builtin.cpu.arch.endian());
try testing.expectEqual(T{ .a = 1, .b = value, .c = 4 }, st);
}
/// 已弃用:改用 `byteSwap`。
pub const byteSwapAllFields = byteSwap;
/// 已弃用:改用 `byteSwapAligned`。
pub const byteSwapAllFieldsAligned = byteSwapAligned;
/// 反转字节顺序。
/// 递归处理结构体、联合体、数组、枚举、浮点数和整数。
/// extern 结构体字段和数组元素的顺序保持不变,
/// 并递归交换其字节顺序。
/// 可用于在小端和大端表示之间转换。
pub fn byteSwap(comptime S: type, ptr: *S) void {
byteSwapAligned(S, .of(S), ptr);
}
/// 反转字节顺序。
/// 递归处理结构体、联合体、数组、枚举、浮点数和整数。
/// extern 结构体字段和数组元素的顺序保持不变,
/// 并递归交换其字节顺序。
/// 可用于在小端和大端表示之间转换。
pub fn byteSwapAligned(
comptime S: type,
comptime a: Alignment,
ptr: *align(a.toByteUnits()) S,
) void {
switch (@typeInfo(S)) {
.@"struct" => |@"struct"| {
if (@"struct".backing_integer) |Int| {
ptr.* = @bitCast(@byteSwap(@as(Int, @bitCast(ptr.*))));
} else {
if (@"struct".layout != .@"extern") {
@compileError("byteSwapAligned expects a packed or extern struct");
}
inline for (@"struct".field_types, @"struct".field_names, @"struct".field_attrs) |f_type, f_name, f_attr| {
switch (@typeInfo(f_type)) {
.@"struct" => byteSwapAligned(f_type, .fromByteUnits(f_attr.@"align" orelse @alignOf(f_type)), &@field(ptr, f_name)),
.@"union", .array => byteSwapAligned(f_type, .fromByteUnits(f_attr.@"align" orelse @alignOf(f_type)), &@field(ptr, f_name)),
.@"enum" => {
@field(ptr, f_name) = @fromBackingInt(@byteSwap(@backingInt(@field(ptr, f_name))));
},
.bool => {},
.float => |float| {
@field(ptr, f_name) = @bitCast(@byteSwap(@as(@Int(.unsigned, float.bits), @bitCast(@field(ptr, f_name)))));
},
else => {
@field(ptr, f_name) = @byteSwap(@field(ptr, f_name));
},
}
}
}
},
.@"union" => |@"union"| if (@"union".backing_integer) |Int| {
ptr.* = @bitCast(@byteSwap(@as(Int, @bitCast(ptr.*))));
} else {
if (@"union".layout != .@"extern") {
@compileError("byteSwapAligned expects a packed or extern union");
}
const first_size = @bitSizeOf(@"union".field_types[0]);
inline for (@"union".field_types) |field_type| {
if (@bitSizeOf(field_type) != first_size) {
@compileError("Unable to byte-swap unions with varying field sizes");
}
}
const FieldInt = @Int(.unsigned, first_size);
const field_ptr = &@field(ptr, @"union".field_names[0]);
field_ptr.* = @bitCast(@byteSwap(@as(FieldInt, @bitCast(field_ptr.*))));
},
.array => |array| {
byteSwapAllElements(array.child, ptr);
},
.@"enum" => {
ptr.* = @fromBackingInt(@byteSwap(@backingInt(ptr.*)));
},
.bool => {},
.float => |float| {
const int_repr: @Int(.unsigned, float.bits) = @bitCast(ptr.*);
ptr.* = @bitCast(@byteSwap(int_repr));
},
else => {
ptr.* = @byteSwap(ptr.*);
},
}
}
test byteSwap {
const T = extern struct {
f0: u8,
f1: u16,
f2: u32,
f3: [1]u8,
f4: bool,
f5: f32,
f6: extern union { f0: u16, f1: u16 },
};
const K = extern struct {
f0: u8,
f1: T,
f2: u16,
f3: [1]u8,
f4: bool,
f5: f32,
};
const P = packed struct(u32) {
f0: u1,
f1: u7,
f2: u4,
f3: u4,
f4: u16,
};
const A = extern struct {
f0: u32,
f1: extern struct {
f0: u64,
} align(4),
f2: u32,
};
const E = enum(u32) {
_,
};
var s = T{
.f0 = 0x12,
.f1 = 0x1234,
.f2 = 0x12345678,
.f3 = .{0x12},
.f4 = true,
.f5 = @bitCast(@as(u32, 0x4640e400)),
.f6 = .{ .f0 = 0x1234 },
};
var k = K{
.f0 = 0x12,
.f1 = s,
.f2 = 0x1234,
.f3 = .{0x12},
.f4 = false,
.f5 = @bitCast(@as(u32, 0x45d42800)),
};
var p: P = @bitCast(@as(u32, 0x01234567));
var a: A = A{
.f0 = 0x12345678,
.f1 = .{ .f0 = 0x123456789ABCDEF0 },
.f2 = 0x87654321,
};
var e: E = @fromBackingInt(0x12345678);
var f: f32 = @bitCast(@as(u32, 0x4640e400));
byteSwap(T, &s);
byteSwap(K, &k);
byteSwap(P, &p);
byteSwap(A, &a);
byteSwap(E, &e);
byteSwap(f32, &f);
try std.testing.expectEqual(T{
.f0 = 0x12,
.f1 = 0x3412,
.f2 = 0x78563412,
.f3 = .{0x12},
.f4 = true,
.f5 = @bitCast(@as(u32, 0x00e44046)),
.f6 = .{ .f0 = 0x3412 },
}, s);
try std.testing.expectEqual(K{
.f0 = 0x12,
.f1 = s,
.f2 = 0x3412,
.f3 = .{0x12},
.f4 = false,
.f5 = @bitCast(@as(u32, 0x0028d445)),
}, k);
try std.testing.expectEqual(@as(P, @bitCast(@as(u32, 0x67452301))), p);
try std.testing.expectEqual(A{
.f0 = 0x78563412,
.f1 = .{ .f0 = 0xF0DEBC9A78563412 },
.f2 = 0x21436587,
}, a);
try std.testing.expectEqual(@as(E, @fromBackingInt(0x78563412)), e);
try std.testing.expectEqual(@as(f32, @bitCast(@as(u32, 0x00e44046))), f);
}
/// 反转切片中所有元素的字节顺序。
/// 递归处理结构体、联合体、数组、枚举、浮点数和整数。
/// 可用于在小端和大端表示之间转换。
pub fn byteSwapAllElements(comptime Elem: type, slice: []Elem) void {
for (slice) |*elem| byteSwap(Elem, elem);
}
/// 返回迭代器,遍历 `buffer` 中不属于 `delimiters` 任一元素的切片。
///
/// `tokenizeAny(u8, " abc|def || ghi ", " |")` 将依次返回对应“abc”“def”“ghi”的切片,最后返回 null。
///
/// 若 `buffer` 为空,迭代器返回 null。
/// 若缓冲区中没有出现任何 `delimiters`,迭代器依次返回 `buffer` 和 null。
///
/// 另见:`tokenizeSequence`、`tokenizeScalar`、
/// `splitSequence`、`splitAny`、`splitScalar`、
/// `splitBackwardsSequence`、`splitBackwardsAny` 和 `splitBackwardsScalar`
///
///
///
pub fn tokenizeAny(comptime T: type, buffer: []const T, delimiters: []const T) TokenIterator(T, .any) {
return .{
.index = 0,
.buffer = buffer,
.delimiter = delimiters,
};
}
/// 返回迭代器,遍历 `buffer` 中不是
/// `delimiter` 所示序列的切片。
///
/// `tokenizeSequence(u8, "<>abc><def<><>ghi", "<>")` 将按顺序返回
/// 切片 "abc><def"、"ghi"、null。
///
/// 如果 `buffer` 为空,迭代器返回 null。
/// 如果 buffer 中不存在 `delimiter`,
/// 迭代器将依次返回 `buffer`、null。
/// 分隔符长度不得为零。
///
/// 另请参见:`tokenizeAny`、`tokenizeScalar`、
/// `splitSequence`、`splitAny`、`splitScalar`、
/// `splitBackwardsSequence`、`splitBackwardsAny`、`splitBackwardsScalar`。
pub fn tokenizeSequence(comptime T: type, buffer: []const T, delimiter: []const T) TokenIterator(T, .sequence) {
assert(delimiter.len != 0);
return .{
.index = 0,
.buffer = buffer,
.delimiter = delimiter,
};
}
/// 返回迭代器,遍历 `buffer` 中不等于 `delimiter` 的切片。
///
/// `tokenizeScalar(u8, " abc def ghi ", ' ')` 将依次返回对应“abc”“def”“ghi”的切片,最后返回 null。
///
/// 若 `buffer` 为空,迭代器返回 null。
/// 若缓冲区中不存在 `delimiter`,迭代器依次返回 `buffer` 和 null。
///
/// 另见:`tokenizeAny`、`tokenizeSequence`、
/// `splitSequence`、`splitAny` 和 `splitScalar`、
/// `splitBackwardsSequence`、`splitBackwardsAny` 和 `splitBackwardsScalar`
///
///
///
pub fn tokenizeScalar(comptime T: type, buffer: []const T, delimiter: T) TokenIterator(T, .scalar) {
return .{
.index = 0,
.buffer = buffer,
.delimiter = delimiter,
};
}
test tokenizeScalar {
var it = tokenizeScalar(u8, " abc def ghi ", ' ');
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(eql(u8, it.peek().?, "def"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
try testing.expect(it.next() == null);
it = tokenizeScalar(u8, "..\\bob", '\\');
try testing.expect(eql(u8, it.next().?, ".."));
try testing.expect(eql(u8, "..", "..\\bob"[0..it.index]));
try testing.expect(eql(u8, it.next().?, "bob"));
try testing.expect(it.next() == null);
it = tokenizeScalar(u8, "//a/b", '/');
try testing.expect(eql(u8, it.next().?, "a"));
try testing.expect(eql(u8, it.next().?, "b"));
try testing.expect(eql(u8, "//a/b", "//a/b"[0..it.index]));
try testing.expect(it.next() == null);
it = tokenizeScalar(u8, "|", '|');
try testing.expect(it.next() == null);
try testing.expect(it.peek() == null);
it = tokenizeScalar(u8, "", '|');
try testing.expect(it.next() == null);
try testing.expect(it.peek() == null);
it = tokenizeScalar(u8, "hello", ' ');
try testing.expect(eql(u8, it.next().?, "hello"));
try testing.expect(it.next() == null);
var it16 = tokenizeScalar(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("hello"),
' ',
);
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("hello")));
try testing.expect(it16.next() == null);
}
test tokenizeAny {
var it = tokenizeAny(u8, "a|b,c/d e", " /,|");
try testing.expect(eql(u8, it.next().?, "a"));
try testing.expect(eql(u8, it.peek().?, "b"));
try testing.expect(eql(u8, it.next().?, "b"));
try testing.expect(eql(u8, it.next().?, "c"));
try testing.expect(eql(u8, it.next().?, "d"));
try testing.expect(eql(u8, it.next().?, "e"));
try testing.expect(it.next() == null);
try testing.expect(it.peek() == null);
it = tokenizeAny(u8, "hello", "");
try testing.expect(eql(u8, it.next().?, "hello"));
try testing.expect(it.next() == null);
var it16 = tokenizeAny(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a|b,c/d e"),
std.unicode.utf8ToUtf16LeStringLiteral(" /,|"),
);
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("a")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("e")));
try testing.expect(it16.next() == null);
}
test tokenizeSequence {
var it = tokenizeSequence(u8, "a<>b<><>c><>d><", "<>");
try testing.expectEqualStrings("a", it.next().?);
try testing.expectEqualStrings("b", it.peek().?);
try testing.expectEqualStrings("b", it.next().?);
try testing.expectEqualStrings("c>", it.next().?);
try testing.expectEqualStrings("d><", it.next().?);
try testing.expect(it.next() == null);
try testing.expect(it.peek() == null);
var it16 = tokenizeSequence(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a<>b<><>c><>d><"),
std.unicode.utf8ToUtf16LeStringLiteral("<>"),
);
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("a")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c>")));
try testing.expect(eql(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d><")));
try testing.expect(it16.next() == null);
}
test "tokenize (reset)" {
{
var it = tokenizeAny(u8, " abc def ghi ", " ");
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
it.reset();
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
try testing.expect(it.next() == null);
}
{
var it = tokenizeSequence(u8, "<><>abc<>def<><>ghi<>", "<>");
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
it.reset();
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
try testing.expect(it.next() == null);
}
{
var it = tokenizeScalar(u8, " abc def ghi ", ' ');
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
it.reset();
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
try testing.expect(it.next() == null);
}
}
/// 返回迭代器,遍历 `buffer` 中
/// 由 `delimiter` 字节序列分隔的切片。
///
/// `splitSequence(u8, "abc||def||||ghi", "||")` 会依次返回
/// "abc"、"def"、""、"ghi" 的切片,最后返回 null。
///
/// 若缓冲区中不存在 `delimiter`,
/// 迭代器依次返回 `buffer`、null。
/// 分隔符长度不得为零。
///
/// 另请参见:`splitAny`、`splitScalar`、`splitBackwardsSequence`、
/// `splitBackwardsAny`、`splitBackwardsScalar`、
/// `tokenizeAny`、`tokenizeSequence`、`tokenizeScalar`。
pub fn splitSequence(comptime T: type, buffer: []const T, delimiter: []const T) SplitIterator(T, .sequence) {
assert(delimiter.len != 0);
return .{
.index = 0,
.buffer = buffer,
.delimiter = delimiter,
};
}
/// 返回迭代器,遍历 `buffer` 中由
/// `delimiters` 中任意元素分隔的切片。
///
/// `splitAny(u8, "abc,def||ghi", "|,")` 将按顺序返回
/// 切片 "abc"、"def"、""、"ghi"、null。
///
/// 如果 buffer 中不存在 `delimiters` 中的任何元素,
/// 迭代器将依次返回 `buffer`、null。
///
/// 另请参见:`splitSequence`、`splitScalar`、`splitBackwardsSequence`、
/// `splitBackwardsAny`、`splitBackwardsScalar`、
/// `tokenizeAny`、`tokenizeSequence`、`tokenizeScalar`。
pub fn splitAny(comptime T: type, buffer: []const T, delimiters: []const T) SplitIterator(T, .any) {
return .{
.index = 0,
.buffer = buffer,
.delimiter = delimiters,
};
}
/// 返回迭代器,遍历 `buffer` 中由 `delimiter` 分隔的切片。
///
/// `splitScalar(u8, "abc|def||ghi", '|')` 将依次返回对应“abc”“def”“”“ghi”的切片,最后返回 null。
///
/// 若缓冲区中不存在 `delimiter`,迭代器依次返回 `buffer` 和 null。
///
/// 另见:`splitSequence`、`splitAny`、`splitBackwardsSequence`、
/// `splitBackwardsAny`、`splitBackwardsScalar`、
/// `tokenizeAny`、`tokenizeSequence` 和 `tokenizeScalar`。
///
///
///
pub fn splitScalar(comptime T: type, buffer: []const T, delimiter: T) SplitIterator(T, .scalar) {
return .{
.index = 0,
.buffer = buffer,
.delimiter = delimiter,
};
}
test splitScalar {
var it = splitScalar(u8, "abc|def||ghi", '|');
try testing.expectEqualSlices(u8, it.rest(), "abc|def||ghi");
try testing.expectEqualSlices(u8, it.first(), "abc");
try testing.expectEqualSlices(u8, it.rest(), "def||ghi");
try testing.expectEqualSlices(u8, it.peek().?, "def");
try testing.expectEqualSlices(u8, it.next().?, "def");
try testing.expectEqualSlices(u8, it.rest(), "|ghi");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expectEqualSlices(u8, it.rest(), "ghi");
try testing.expectEqualSlices(u8, it.peek().?, "ghi");
try testing.expectEqualSlices(u8, it.next().?, "ghi");
try testing.expectEqualSlices(u8, it.rest(), "");
try testing.expect(it.peek() == null);
try testing.expect(it.next() == null);
it = splitScalar(u8, "", '|');
try testing.expectEqualSlices(u8, it.first(), "");
try testing.expect(it.next() == null);
it = splitScalar(u8, "|", '|');
try testing.expectEqualSlices(u8, it.first(), "");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expect(it.peek() == null);
try testing.expect(it.next() == null);
it = splitScalar(u8, "hello", ' ');
try testing.expectEqualSlices(u8, it.first(), "hello");
try testing.expect(it.next() == null);
var it16 = splitScalar(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("hello"),
' ',
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("hello"));
try testing.expect(it16.next() == null);
}
test splitSequence {
var it = splitSequence(u8, "a, b ,, c, d, e", ", ");
try testing.expectEqualSlices(u8, it.first(), "a");
try testing.expectEqualSlices(u8, it.rest(), "b ,, c, d, e");
try testing.expectEqualSlices(u8, it.next().?, "b ,");
try testing.expectEqualSlices(u8, it.next().?, "c");
try testing.expectEqualSlices(u8, it.next().?, "d");
try testing.expectEqualSlices(u8, it.next().?, "e");
try testing.expect(it.next() == null);
var it16 = splitSequence(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a, b ,, c, d, e"),
std.unicode.utf8ToUtf16LeStringLiteral(", "),
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("a"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b ,"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("e"));
try testing.expect(it16.next() == null);
}
test splitAny {
var it = splitAny(u8, "a,b, c d e", ", ");
try testing.expectEqualSlices(u8, it.first(), "a");
try testing.expectEqualSlices(u8, it.rest(), "b, c d e");
try testing.expectEqualSlices(u8, it.next().?, "b");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expectEqualSlices(u8, it.next().?, "c");
try testing.expectEqualSlices(u8, it.next().?, "d");
try testing.expectEqualSlices(u8, it.next().?, "e");
try testing.expect(it.next() == null);
it = splitAny(u8, "hello", "");
try testing.expect(eql(u8, it.next().?, "hello"));
try testing.expect(it.next() == null);
var it16 = splitAny(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a,b, c d e"),
std.unicode.utf8ToUtf16LeStringLiteral(", "),
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("a"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral(""));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("e"));
try testing.expect(it16.next() == null);
}
test "split (reset)" {
{
var it = splitSequence(u8, "abc def ghi", " ");
try testing.expect(eql(u8, it.first(), "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
it.reset();
try testing.expect(eql(u8, it.first(), "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
try testing.expect(it.next() == null);
}
{
var it = splitAny(u8, "abc def,ghi", " ,");
try testing.expect(eql(u8, it.first(), "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
it.reset();
try testing.expect(eql(u8, it.first(), "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
try testing.expect(it.next() == null);
}
{
var it = splitScalar(u8, "abc def ghi", ' ');
try testing.expect(eql(u8, it.first(), "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
it.reset();
try testing.expect(eql(u8, it.first(), "abc"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "ghi"));
try testing.expect(it.next() == null);
}
}
/// 返回迭代器,反向遍历 `buffer` 中由
/// `delimiter` 所示序列分隔的切片。
///
/// `splitBackwardsSequence(u8, "abc||def||||ghi", "||")` 将按顺序返回
/// 切片 "ghi"、""、"def"、"abc"、null。
///
/// 如果 buffer 中不存在 `delimiter`,
/// 迭代器将依次返回 `buffer`、null。
/// 分隔符长度不得为零。
///
/// 另请参见:`splitBackwardsAny`、`splitBackwardsScalar`、
/// `splitSequence`、`splitAny`、`splitScalar`、
/// `tokenizeAny`、`tokenizeSequence`、`tokenizeScalar`。
pub fn splitBackwardsSequence(comptime T: type, buffer: []const T, delimiter: []const T) SplitBackwardsIterator(T, .sequence) {
assert(delimiter.len != 0);
return .{
.index = buffer.len,
.buffer = buffer,
.delimiter = delimiter,
};
}
/// 返回迭代器,反向遍历 `buffer` 中由
/// `delimiters` 中任意元素分隔的切片。
///
/// `splitBackwardsAny(u8, "abc,def||ghi", "|,")` 将按顺序返回
/// 切片 "ghi"、""、"def"、"abc"、null。
///
/// 如果 buffer 中不存在 `delimiters` 中的任何元素,
/// 迭代器将依次返回 `buffer`、null。
///
/// 另请参见:`splitBackwardsSequence`、`splitBackwardsScalar`、
/// `splitSequence`、`splitAny`、`splitScalar`、
/// `tokenizeAny`、`tokenizeSequence`、`tokenizeScalar`。
pub fn splitBackwardsAny(comptime T: type, buffer: []const T, delimiters: []const T) SplitBackwardsIterator(T, .any) {
return .{
.index = buffer.len,
.buffer = buffer,
.delimiter = delimiters,
};
}
/// 返回迭代器,反向遍历 `buffer` 中由
/// `delimiter` 分隔的切片。
///
/// `splitBackwardsScalar(u8, "abc|def||ghi", '|')` 将按顺序返回
/// 切片 "ghi"、""、"def"、"abc"、null。
///
/// 如果 buffer 中不存在 `delimiter`,
/// 迭代器将依次返回 `buffer`、null。
///
/// 另请参见:`splitBackwardsSequence`、`splitBackwardsAny`、
/// `splitSequence`、`splitAny`、`splitScalar`、
/// `tokenizeAny`、`tokenizeSequence`、`tokenizeScalar`。
pub fn splitBackwardsScalar(comptime T: type, buffer: []const T, delimiter: T) SplitBackwardsIterator(T, .scalar) {
return .{
.index = buffer.len,
.buffer = buffer,
.delimiter = delimiter,
};
}
test splitBackwardsScalar {
var it = splitBackwardsScalar(u8, "abc|def||ghi", '|');
try testing.expectEqualSlices(u8, it.rest(), "abc|def||ghi");
try testing.expectEqualSlices(u8, it.first(), "ghi");
try testing.expectEqualSlices(u8, it.rest(), "abc|def|");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expectEqualSlices(u8, it.rest(), "abc|def");
try testing.expectEqualSlices(u8, it.next().?, "def");
try testing.expectEqualSlices(u8, it.rest(), "abc");
try testing.expectEqualSlices(u8, it.next().?, "abc");
try testing.expectEqualSlices(u8, it.rest(), "");
try testing.expect(it.next() == null);
it = splitBackwardsScalar(u8, "", '|');
try testing.expectEqualSlices(u8, it.first(), "");
try testing.expect(it.next() == null);
it = splitBackwardsScalar(u8, "|", '|');
try testing.expectEqualSlices(u8, it.first(), "");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expect(it.next() == null);
it = splitBackwardsScalar(u8, "hello", ' ');
try testing.expectEqualSlices(u8, it.first(), "hello");
try testing.expect(it.next() == null);
var it16 = splitBackwardsScalar(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("hello"),
' ',
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("hello"));
try testing.expect(it16.next() == null);
}
test splitBackwardsSequence {
var it = splitBackwardsSequence(u8, "a, b ,, c, d, e", ", ");
try testing.expectEqualSlices(u8, it.rest(), "a, b ,, c, d, e");
try testing.expectEqualSlices(u8, it.first(), "e");
try testing.expectEqualSlices(u8, it.rest(), "a, b ,, c, d");
try testing.expectEqualSlices(u8, it.next().?, "d");
try testing.expectEqualSlices(u8, it.rest(), "a, b ,, c");
try testing.expectEqualSlices(u8, it.next().?, "c");
try testing.expectEqualSlices(u8, it.rest(), "a, b ,");
try testing.expectEqualSlices(u8, it.next().?, "b ,");
try testing.expectEqualSlices(u8, it.rest(), "a");
try testing.expectEqualSlices(u8, it.next().?, "a");
try testing.expectEqualSlices(u8, it.rest(), "");
try testing.expect(it.next() == null);
var it16 = splitBackwardsSequence(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a, b ,, c, d, e"),
std.unicode.utf8ToUtf16LeStringLiteral(", "),
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("e"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b ,"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("a"));
try testing.expect(it16.next() == null);
}
test splitBackwardsAny {
var it = splitBackwardsAny(u8, "a,b, c d e", ", ");
try testing.expectEqualSlices(u8, it.rest(), "a,b, c d e");
try testing.expectEqualSlices(u8, it.first(), "e");
try testing.expectEqualSlices(u8, it.rest(), "a,b, c d");
try testing.expectEqualSlices(u8, it.next().?, "d");
try testing.expectEqualSlices(u8, it.rest(), "a,b, c");
try testing.expectEqualSlices(u8, it.next().?, "c");
try testing.expectEqualSlices(u8, it.rest(), "a,b,");
try testing.expectEqualSlices(u8, it.next().?, "");
try testing.expectEqualSlices(u8, it.rest(), "a,b");
try testing.expectEqualSlices(u8, it.next().?, "b");
try testing.expectEqualSlices(u8, it.rest(), "a");
try testing.expectEqualSlices(u8, it.next().?, "a");
try testing.expectEqualSlices(u8, it.rest(), "");
try testing.expect(it.next() == null);
var it16 = splitBackwardsAny(
u16,
std.unicode.utf8ToUtf16LeStringLiteral("a,b, c d e"),
std.unicode.utf8ToUtf16LeStringLiteral(", "),
);
try testing.expectEqualSlices(u16, it16.first(), std.unicode.utf8ToUtf16LeStringLiteral("e"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("d"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("c"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral(""));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("b"));
try testing.expectEqualSlices(u16, it16.next().?, std.unicode.utf8ToUtf16LeStringLiteral("a"));
try testing.expect(it16.next() == null);
}
test "splitBackwards (reset)" {
{
var it = splitBackwardsSequence(u8, "abc def ghi", " ");
try testing.expect(eql(u8, it.first(), "ghi"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "abc"));
it.reset();
try testing.expect(eql(u8, it.first(), "ghi"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(it.next() == null);
}
{
var it = splitBackwardsAny(u8, "abc def,ghi", " ,");
try testing.expect(eql(u8, it.first(), "ghi"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "abc"));
it.reset();
try testing.expect(eql(u8, it.first(), "ghi"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(it.next() == null);
}
{
var it = splitBackwardsScalar(u8, "abc def ghi", ' ');
try testing.expect(eql(u8, it.first(), "ghi"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "abc"));
it.reset();
try testing.expect(eql(u8, it.first(), "ghi"));
try testing.expect(eql(u8, it.next().?, "def"));
try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(it.next() == null);
}
}
/// 返回通过滑动窗口遍历 `buffer` 切片的迭代器。
/// 窗口长度为 `size`,每次迭代
/// 向前移动 `advance`。
///
/// 提取移动平均值所用数据的示例:
/// `window(u8, "abcdefg", 3, 1)` 将按顺序返回切片
/// "abc"、"bcd"、"cde"、"def"、"efg"、null。
///
/// 每 N 个元素分块或拆分的示例:
/// `window(u8, "abcdefg", 3, 3)` 将按顺序返回切片
/// "abc"、"def"、"g"、null。
///
/// 选取每个偶数索引的示例:
/// `window(u8, "abcdefg", 1, 2)` 将按顺序返回切片
/// "a"、"c"、"e"、"g"、null。
///
/// `size` 和 `advance` 均不得为零。
pub fn window(comptime T: type, buffer: []const T, size: usize, advance: usize) WindowIterator(T) {
assert(size != 0);
assert(advance != 0);
return .{
.index = if (buffer.len > 0) 0 else null,
.buffer = buffer,
.size = size,
.advance = advance,
};
}
test window {
{
// 大小为 3 的移动平均
var it = window(u8, "abcdefg", 3, 1);
try testing.expectEqualSlices(u8, "abc", it.next().?);
try testing.expectEqualSlices(u8, "bcd", it.next().?);
try testing.expectEqualSlices(u8, "cde", it.next().?);
try testing.expectEqualSlices(u8, "def", it.next().?);
try testing.expectEqualSlices(u8, "efg", it.next().?);
try testing.expectEqual(null, it.next());
// 多字节
var it16 = window(u16, std.unicode.utf8ToUtf16LeStringLiteral("abcdefg"), 3, 1);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("abc"), it16.next().?);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("bcd"), it16.next().?);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("cde"), it16.next().?);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("def"), it16.next().?);
try testing.expectEqualSlices(u16, std.unicode.utf8ToUtf16LeStringLiteral("efg"), it16.next().?);
try testing.expectEqual(it16.next(), null);
}
{
// 每 3 个分块/拆分
var it = window(u8, "abcdefg", 3, 3);
try testing.expectEqualSlices(u8, "abc", it.next().?);
try testing.expectEqualSlices(u8, "def", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// 选择偶数
var it = window(u8, "abcdefg", 1, 2);
try testing.expectEqualSlices(u8, "a", it.next().?);
try testing.expectEqualSlices(u8, "c", it.next().?);
try testing.expectEqualSlices(u8, "e", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
it = window(u8, "abcdefgh", 1, 2);
try testing.expectEqualSlices(u8, "a", it.next().?);
try testing.expectEqualSlices(u8, "c", it.next().?);
try testing.expectEqualSlices(u8, "e", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// 空
var it = window(u8, "", 1, 1);
try testing.expectEqual(null, it.next());
it = window(u8, "", 10, 1);
try testing.expectEqual(null, it.next());
it = window(u8, "", 1, 10);
try testing.expectEqual(null, it.next());
it = window(u8, "", 10, 10);
try testing.expectEqual(null, it.next());
}
{
// 首个
var it = window(u8, "abcdefg", 3, 3);
try testing.expectEqualSlices(u8, "abc", it.next().?);
it.reset();
try testing.expectEqualSlices(u8, "abc", it.next().?);
}
{
// 重置
var it = window(u8, "abcdefg", 3, 3);
try testing.expectEqualSlices(u8, "abc", it.next().?);
try testing.expectEqualSlices(u8, "def", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
it.reset();
try testing.expectEqualSlices(u8, "abc", it.next().?);
try testing.expectEqualSlices(u8, "def", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// size > buffer.len
var it = window(u8, "abcdefg", 100, 1);
try testing.expectEqualSlices(u8, "abcdefg", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// advance >= buffer.len
var it = window(u8, "abcdefg", 1, 7);
try testing.expectEqualSlices(u8, "a", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// advance == 1 且 size == 1
var it = window(u8, "abcdefg", 1, 1);
try testing.expectEqualSlices(u8, "a", it.next().?);
try testing.expectEqualSlices(u8, "b", it.next().?);
try testing.expectEqualSlices(u8, "c", it.next().?);
try testing.expectEqualSlices(u8, "d", it.next().?);
try testing.expectEqualSlices(u8, "e", it.next().?);
try testing.expectEqualSlices(u8, "f", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
{
// 前移量 > 大小
var it = window(u8, "abcdefg", 2, 3);
try testing.expectEqualSlices(u8, "ab", it.next().?);
try testing.expectEqualSlices(u8, "de", it.next().?);
try testing.expectEqualSlices(u8, "g", it.next().?);
try testing.expectEqual(null, it.next());
}
}
/// `window` 函数为滑动窗口操作返回的迭代器类型。
pub fn WindowIterator(comptime T: type) type {
return struct {
buffer: []const T,
index: ?usize,
size: usize,
advance: usize,
const Self = @This();
/// 返回下一个窗口的切片;若窗口已到末尾,则返回 null。
pub fn next(self: *Self) ?[]const T {
const start = self.index orelse return null;
const next_index = start + self.advance;
const end = if (start + self.size < self.buffer.len) blk: {
self.index = if (next_index < self.buffer.len) next_index else null;
break :blk start + self.size;
} else blk: {
self.index = null;
break :blk self.buffer.len;
};
return self.buffer[start..end];
}
/// 将迭代器重置到初始窗口。
pub fn reset(self: *Self) void {
self.index = 0;
}
};
}
/// 如果 haystack 以 needle 开头,则返回 true。
/// 时间复杂度:O(needle.len)。
pub fn startsWith(comptime T: type, haystack: []const T, needle: []const T) bool {
return if (needle.len > haystack.len) false else eql(T, haystack[0..needle.len], needle);
}
test startsWith {
try testing.expect(startsWith(u8, "Bob", "Bo"));
try testing.expect(!startsWith(u8, "Needle in haystack", "haystack"));
}
/// 如果 haystack 以 needle 结尾,则返回 true。
/// 时间复杂度:O(needle.len)。
pub fn endsWith(comptime T: type, haystack: []const T, needle: []const T) bool {
return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len ..], needle);
}
test endsWith {
try testing.expect(endsWith(u8, "Needle in haystack", "haystack"));
try testing.expect(!endsWith(u8, "Bob", "Bo"));
}
/// 如果 `slice` 以 `prefix` 开头,则返回 `slice` 从 `prefix.len` 开始的剩余部分。
pub fn cutPrefix(comptime T: type, slice: []const T, prefix: []const T) ?[]const T {
return if (startsWith(T, slice, prefix)) slice[prefix.len..] else null;
}
test cutPrefix {
try testing.expectEqualStrings("foo", cutPrefix(u8, "--example=foo", "--example=").?);
try testing.expectEqual(null, cutPrefix(u8, "--example=foo", "-example="));
}
/// 若 `slice` 以 `suffix` 结尾,则返回 `slice` 从开头到 `suffix` 起始处的部分。
pub fn cutSuffix(comptime T: type, slice: []const T, suffix: []const T) ?[]const T {
return if (endsWith(T, slice, suffix)) slice[0 .. slice.len - suffix.len] else null;
}
test cutSuffix {
try testing.expectEqualStrings("foo", cutSuffix(u8, "foobar", "bar").?);
try testing.expectEqual(null, cutSuffix(u8, "foobar", "baz"));
}
/// 返回 `haystack` 中 `needle` 首次出现位置之前和之后的切片;
/// 若未找到,则返回 `null`。
///
/// 另见:
/// * `cutScalar`
/// * `split`
/// * `tokenizeAny`
pub fn cut(comptime T: type, haystack: []const T, needle: []const T) ?struct { []const T, []const T } {
const index = find(T, haystack, needle) orelse return null;
return .{ haystack[0..index], haystack[index + needle.len ..] };
}
test cut {
try testing.expectEqual(null, cut(u8, "a b c", "B"));
const before, const after = cut(u8, "a be c", "be") orelse return error.TestFailed;
try testing.expectEqualStrings("a ", before);
try testing.expectEqualStrings(" c", after);
}
/// 返回 `haystack` 中 `needle` 最后一次出现位置之前和之后的切片;
/// 若未找到,则返回 `null`。
///
/// 另见:
/// * `cut`
/// * `cutScalarLast`
pub fn cutLast(comptime T: type, haystack: []const T, needle: []const T) ?struct { []const T, []const T } {
const index = findLast(T, haystack, needle) orelse return null;
return .{ haystack[0..index], haystack[index + needle.len ..] };
}
test cutLast {
try testing.expectEqual(null, cutLast(u8, "a b c", "B"));
const before, const after = cutLast(u8, "a be c be d", "be") orelse return error.TestFailed;
try testing.expectEqualStrings("a be c ", before);
try testing.expectEqualStrings(" d", after);
}
/// 返回 `haystack` 在 `needle` 首次出现位置前后的切片,
/// 未找到则返回 `null`。
///
/// 另请参见:
/// * `cut`
/// * `splitScalar`
/// * `tokenizeScalar`
pub fn cutScalar(comptime T: type, haystack: []const T, needle: T) ?struct { []const T, []const T } {
const index = findScalar(T, haystack, needle) orelse return null;
return .{ haystack[0..index], haystack[index + 1 ..] };
}
test cutScalar {
try testing.expectEqual(null, cutScalar(u8, "a b c", 'B'));
const before, const after = cutScalar(u8, "a b c", 'b') orelse return error.TestFailed;
try testing.expectEqualStrings("a ", before);
try testing.expectEqualStrings(" c", after);
}
/// 返回 `haystack` 在 `needle` 最后一次出现位置前后的切片,
/// 未找到则返回 `null`。
///
/// 另请参见:
/// * `cut`
/// * `splitScalar`
/// * `tokenizeScalar`
pub fn cutScalarLast(comptime T: type, haystack: []const T, needle: T) ?struct { []const T, []const T } {
const index = findScalarLast(T, haystack, needle) orelse return null;
return .{ haystack[0..index], haystack[index + 1 ..] };
}
test cutScalarLast {
try testing.expectEqual(null, cutScalarLast(u8, "a b c", 'B'));
const before, const after = cutScalarLast(u8, "a b c b d", 'b') orelse return error.TestFailed;
try testing.expectEqualStrings("a b c ", before);
try testing.expectEqualStrings(" d", after);
}
/// 分词和拆分操作的分隔符类型。
pub const DelimiterType = enum { sequence, any, scalar };
/// 用于词元化操作的迭代器类型,会跳过空序列和分隔符序列。
pub fn TokenIterator(comptime T: type, comptime delimiter_type: DelimiterType) type {
return struct {
buffer: []const T,
delimiter: switch (delimiter_type) {
.sequence, .any => []const T,
.scalar => T,
},
index: usize,
const Self = @This();
/// 返回当前词法标记的切片;若词法分析已完成,则返回 null,
/// 并前进到下一个词法标记。
pub fn next(self: *Self) ?[]const T {
const result = self.peek() orelse return null;
self.index += result.len;
return result;
}
/// 返回当前词元的切片;如果词法分析已结束,则返回 null。
/// 不会前进到下一个词元。
pub fn peek(self: *Self) ?[]const T {
// 移动至词法标记开头
while (self.index < self.buffer.len and self.isDelimiter(self.index)) : (self.index += switch (delimiter_type) {
.sequence => self.delimiter.len,
.any, .scalar => 1,
}) {}
const start = self.index;
if (start == self.buffer.len) {
return null;
}
// 移动至词法标记末尾
var end = start;
while (end < self.buffer.len and !self.isDelimiter(end)) : (end += 1) {}
return self.buffer[start..end];
}
/// 返回剩余字节的切片。不影响迭代器状态。
pub fn rest(self: Self) []const T {
// 移动至词法标记开头
var index: usize = self.index;
while (index < self.buffer.len and self.isDelimiter(index)) : (index += switch (delimiter_type) {
.sequence => self.delimiter.len,
.any, .scalar => 1,
}) {}
return self.buffer[index..];
}
/// 将迭代器重置到初始词法标记。
pub fn reset(self: *Self) void {
self.index = 0;
}
fn isDelimiter(self: Self, index: usize) bool {
switch (delimiter_type) {
.sequence => return startsWith(T, self.buffer[index..], self.delimiter),
.any => {
const item = self.buffer[index];
for (self.delimiter) |delimiter_item| {
if (item == delimiter_item) {
return true;
}
}
return false;
},
.scalar => return self.buffer[index] == self.delimiter,
}
}
};
}
/// 拆分操作的迭代器类型,包含分隔符之间的空序列。
pub fn SplitIterator(comptime T: type, comptime delimiter_type: DelimiterType) type {
return struct {
buffer: []const T,
index: ?usize,
delimiter: switch (delimiter_type) {
.sequence, .any => []const T,
.scalar => T,
},
const Self = @This();
/// 返回第一个字段的切片。
/// 仅用于获取第一个字段,后续字段均通过 `next` 获取。
/// 断言迭代尚未开始。
pub fn first(self: *Self) []const T {
assert(self.index.? == 0);
return self.next().?;
}
/// 返回下一个字段的切片;若拆分已完成,则返回 null。
pub fn next(self: *Self) ?[]const T {
const start = self.index orelse return null;
const end = if (switch (delimiter_type) {
.sequence => findPos(T, self.buffer, start, self.delimiter),
.any => findAnyPos(T, self.buffer, start, self.delimiter),
.scalar => findScalarPos(T, self.buffer, start, self.delimiter),
}) |delim_start| blk: {
self.index = delim_start + switch (delimiter_type) {
.sequence => self.delimiter.len,
.any, .scalar => 1,
};
break :blk delim_start;
} else blk: {
self.index = null;
break :blk self.buffer.len;
};
return self.buffer[start..end];
}
/// 返回下一个字段的切片;若拆分完成,则返回 null。
/// 此方法不改变 self.index。
pub fn peek(self: *const Self) ?[]const T {
const start = self.index orelse return null;
const end = if (switch (delimiter_type) {
.sequence => findPos(T, self.buffer, start, self.delimiter),
.any => findAnyPos(T, self.buffer, start, self.delimiter),
.scalar => findScalarPos(T, self.buffer, start, self.delimiter),
}) |delim_start| delim_start else self.buffer.len;
return self.buffer[start..end];
}
/// 返回剩余字节的切片。不影响迭代器状态。
pub fn rest(self: Self) []const T {
const end = self.buffer.len;
const start = self.index orelse end;
return self.buffer[start..end];
}
/// 将迭代器重置到初始切片。
pub fn reset(self: *Self) void {
self.index = 0;
}
};
}
/// 从末尾向前拆分操作的迭代器类型,包括空序列。
pub fn SplitBackwardsIterator(comptime T: type, comptime delimiter_type: DelimiterType) type {
return struct {
buffer: []const T,
index: ?usize,
delimiter: switch (delimiter_type) {
.sequence, .any => []const T,
.scalar => T,
},
const Self = @This();
/// 返回第一个字段的切片。
/// 仅用于获取第一个字段,后续字段均通过 `next` 获取。
/// 断言迭代尚未开始。
pub fn first(self: *Self) []const T {
assert(self.index.? == self.buffer.len);
return self.next().?;
}
/// 返回下一个字段的切片;若拆分已完成,则返回 null。
pub fn next(self: *Self) ?[]const T {
const end = self.index orelse return null;
const start = if (switch (delimiter_type) {
.sequence => findLast(T, self.buffer[0..end], self.delimiter),
.any => findLastAny(T, self.buffer[0..end], self.delimiter),
.scalar => findScalarLast(T, self.buffer[0..end], self.delimiter),
}) |delim_start| blk: {
self.index = delim_start;
break :blk delim_start + switch (delimiter_type) {
.sequence => self.delimiter.len,
.any, .scalar => 1,
};
} else blk: {
self.index = null;
break :blk 0;
};
return self.buffer[start..end];
}
/// 返回剩余字节的切片。不影响迭代器状态。
pub fn rest(self: Self) []const T {
const end = self.index orelse 0;
return self.buffer[0..end];
}
/// 将迭代器重置到初始切片。
pub fn reset(self: *Self) void {
self.index = self.buffer.len;
}
};
}
/// 直接使用分隔符合并一系列切片。
/// 为结果分配内存,必须由调用者释放。
pub fn join(allocator: Allocator, separator: []const u8, slices: []const []const u8) Allocator.Error![]u8 {
return joinMaybeZ(allocator, separator, slices, false);
}
/// 直接用分隔符连接一系列切片,并添加空终止符。
/// 为结果分配内存,调用方必须释放。
pub fn joinZ(allocator: Allocator, separator: []const u8, slices: []const []const u8) Allocator.Error![:0]u8 {
const out = try joinMaybeZ(allocator, separator, slices, true);
return out[0 .. out.len - 1 :0];
}
fn joinMaybeZ(allocator: Allocator, separator: []const u8, slices: []const []const u8, zero: bool) Allocator.Error![]u8 {
if (slices.len == 0) return if (zero) try allocator.dupe(u8, &[1]u8{0}) else &[0]u8{};
const total_len = blk: {
var sum: usize = separator.len * (slices.len - 1);
for (slices) |slice| sum += slice.len;
if (zero) sum += 1;
break :blk sum;
};
const buf = try allocator.alloc(u8, total_len);
errdefer allocator.free(buf);
@memcpy(buf[0..slices[0].len], slices[0]);
var buf_index: usize = slices[0].len;
for (slices[1..]) |slice| {
@memcpy(buf[buf_index .. buf_index + separator.len], separator);
buf_index += separator.len;
@memcpy(buf[buf_index .. buf_index + slice.len], slice);
buf_index += slice.len;
}
if (zero) buf[buf.len - 1] = 0;
// 无需缩减,因为 buf 的大小恰好正确。
return buf;
}
test join {
{
const str = try join(testing.allocator, ",", &[_][]const u8{});
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, ""));
}
{
const str = try join(testing.allocator, ",", &[_][]const u8{ "a", "b", "c" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a,b,c"));
}
{
const str = try join(testing.allocator, ",", &[_][]const u8{"a"});
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a"));
}
{
const str = try join(testing.allocator, ",", &[_][]const u8{ "a", "", "b", "", "c" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a,,b,,c"));
}
}
test joinZ {
{
const str = try joinZ(testing.allocator, ",", &[_][]const u8{});
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, ""));
try testing.expectEqual(str[str.len], 0);
}
{
const str = try joinZ(testing.allocator, ",", &[_][]const u8{ "a", "b", "c" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a,b,c"));
try testing.expectEqual(str[str.len], 0);
}
{
const str = try joinZ(testing.allocator, ",", &[_][]const u8{"a"});
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a"));
try testing.expectEqual(str[str.len], 0);
}
{
const str = try joinZ(testing.allocator, ",", &[_][]const u8{ "a", "", "b", "", "c" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "a,,b,,c"));
try testing.expectEqual(str[str.len], 0);
}
}
/// 将各切片中的 T 复制到一个恰好容纳所有元素的新切片中。
pub fn concat(allocator: Allocator, comptime T: type, slices: []const []const T) Allocator.Error![]T {
return concatMaybeSentinel(allocator, T, slices, null);
}
/// 将各切片中的 T 复制到一个恰好容纳所有元素的新切片中。
pub fn concatWithSentinel(allocator: Allocator, comptime T: type, slices: []const []const T, comptime s: T) Allocator.Error![:s]T {
const ret = try concatMaybeSentinel(allocator, T, slices, s);
return ret[0 .. ret.len - 1 :s];
}
/// 将各切片中的每个 T 复制到新切片中,该切片恰好容纳所有元素及哨兵。
pub fn concatMaybeSentinel(allocator: Allocator, comptime T: type, slices: []const []const T, comptime s: ?T) Allocator.Error![]T {
if (slices.len == 0) return if (s) |sentinel| try allocator.dupe(T, &[1]T{sentinel}) else &[0]T{};
const total_len = blk: {
var sum: usize = 0;
for (slices) |slice| {
sum += slice.len;
}
if (s) |_| {
sum += 1;
}
break :blk sum;
};
const buf = try allocator.alloc(T, total_len);
errdefer allocator.free(buf);
var buf_index: usize = 0;
for (slices) |slice| {
@memcpy(buf[buf_index .. buf_index + slice.len], slice);
buf_index += slice.len;
}
if (s) |sentinel| {
buf[buf.len - 1] = sentinel;
}
// 无需缩减,因为 buf 的大小恰好正确。
return buf;
}
test concat {
{
const str = try concat(testing.allocator, u8, &[_][]const u8{ "abc", "def", "ghi" });
defer testing.allocator.free(str);
try testing.expect(eql(u8, str, "abcdefghi"));
}
{
const str = try concat(testing.allocator, u32, &[_][]const u32{
&[_]u32{ 0, 1 },
&[_]u32{ 2, 3, 4 },
&[_]u32{},
&[_]u32{5},
});
defer testing.allocator.free(str);
try testing.expect(eql(u32, str, &[_]u32{ 0, 1, 2, 3, 4, 5 }));
}
{
const str = try concatWithSentinel(testing.allocator, u8, &[_][]const u8{ "abc", "def", "ghi" }, 0);
defer testing.allocator.free(str);
try testing.expectEqualSentinel(u8, 0, str, "abcdefghi");
}
{
const slice = try concatWithSentinel(testing.allocator, u8, &[_][]const u8{}, 0);
defer testing.allocator.free(slice);
try testing.expectEqualSentinel(u8, 0, slice, &[_:0]u8{});
}
{
const slice = try concatWithSentinel(testing.allocator, u32, &[_][]const u32{
&[_]u32{ 0, 1 },
&[_]u32{ 2, 3, 4 },
&[_]u32{},
&[_]u32{5},
}, 2);
defer testing.allocator.free(slice);
try testing.expectEqualSentinel(u32, 2, slice, &[_:2]u32{ 0, 1, 2, 3, 4, 5 });
}
}
fn moreReadIntTests() !void {
{
const bytes = [_]u8{
0x12,
0x34,
0x56,
0x78,
};
try testing.expect(readInt(u32, &bytes, .big) == 0x12345678);
try testing.expect(readInt(u32, &bytes, .big) == 0x12345678);
try testing.expect(readInt(i32, &bytes, .big) == 0x12345678);
try testing.expect(readInt(u32, &bytes, .little) == 0x78563412);
try testing.expect(readInt(u32, &bytes, .little) == 0x78563412);
try testing.expect(readInt(i32, &bytes, .little) == 0x78563412);
}
{
const buf = [_]u8{
0x00,
0x00,
0x12,
0x34,
};
const answer = readInt(u32, &buf, .big);
try testing.expect(answer == 0x00001234);
}
{
const buf = [_]u8{
0x12,
0x34,
0x00,
0x00,
};
const answer = readInt(u32, &buf, .little);
try testing.expect(answer == 0x00003412);
}
{
const bytes = [_]u8{
0xff,
0xfe,
};
try testing.expect(readInt(u16, &bytes, .big) == 0xfffe);
try testing.expect(readInt(i16, &bytes, .big) == -0x0002);
try testing.expect(readInt(u16, &bytes, .little) == 0xfeff);
try testing.expect(readInt(i16, &bytes, .little) == -0x0101);
}
}
/// 返回切片中的最小值。时间复杂度 O(n)。
/// `slice` 不得为空。
pub fn min(comptime T: type, slice: []const T) T {
assert(slice.len > 0);
var best = slice[0];
for (slice[1..]) |item| {
best = @min(best, item);
}
return best;
}
test min {
try testing.expectEqual(min(u8, "abcdefg"), 'a');
try testing.expectEqual(min(u8, "bcdefga"), 'a');
try testing.expectEqual(min(u8, "a"), 'a');
}
/// 返回切片中的最大数。O(n)。
/// `slice` 不得为空。
pub fn max(comptime T: type, slice: []const T) T {
assert(slice.len > 0);
var best = slice[0];
for (slice[1..]) |item| {
best = @max(best, item);
}
return best;
}
test max {
try testing.expectEqual(max(u8, "abcdefg"), 'g');
try testing.expectEqual(max(u8, "gabcdef"), 'g');
try testing.expectEqual(max(u8, "g"), 'g');
}
/// 查找切片中的最小值和最大值。O(n)。
/// 返回具有 `min` 和 `max` 字段的匿名结构体。
/// `slice` 不得为空。
pub fn minMax(comptime T: type, slice: []const T) struct { T, T } {
assert(slice.len > 0);
var running_minimum = slice[0];
var running_maximum = slice[0];
for (slice[1..]) |item| {
running_minimum = @min(running_minimum, item);
running_maximum = @max(running_maximum, item);
}
return .{ running_minimum, running_maximum };
}
test minMax {
{
const actual_min, const actual_max = minMax(u8, "abcdefg");
try testing.expectEqual(@as(u8, 'a'), actual_min);
try testing.expectEqual(@as(u8, 'g'), actual_max);
}
{
const actual_min, const actual_max = minMax(u8, "bcdefga");
try testing.expectEqual(@as(u8, 'a'), actual_min);
try testing.expectEqual(@as(u8, 'g'), actual_max);
}
{
const actual_min, const actual_max = minMax(u8, "a");
try testing.expectEqual(@as(u8, 'a'), actual_min);
try testing.expectEqual(@as(u8, 'a'), actual_max);
}
}
/// 已弃用,改用 `findMin`。
pub const indexOfMin = findMin;
/// 返回切片中最小数的索引。O(n)。
/// `slice` 不得为空。
pub fn findMin(comptime T: type, slice: []const T) usize {
assert(slice.len > 0);
var best = slice[0];
var index: usize = 0;
for (slice[1..], 0..) |item, i| {
if (item < best) {
best = item;
index = i + 1;
}
}
return index;
}
test findMin {
try testing.expectEqual(findMin(u8, "abcdefg"), 0);
try testing.expectEqual(findMin(u8, "bcdefga"), 6);
try testing.expectEqual(findMin(u8, "a"), 0);
}
pub const indexOfMax = findMax;
/// 返回切片中最大数的索引。O(n)。
/// `slice` 不得为空。
pub fn findMax(comptime T: type, slice: []const T) usize {
assert(slice.len > 0);
var best = slice[0];
var index: usize = 0;
for (slice[1..], 0..) |item, i| {
if (item > best) {
best = item;
index = i + 1;
}
}
return index;
}
test findMax {
try testing.expectEqual(findMax(u8, "abcdefg"), 6);
try testing.expectEqual(findMax(u8, "gabcdef"), 0);
try testing.expectEqual(findMax(u8, "a"), 0);
}
/// 已弃用,改用 `findMinMax`。
pub const indexOfMinMax = findMinMax;
/// 查找切片中最小值和最大值的索引。O(n)。
/// 按最小值索引、最大值索引的顺序返回。
/// `slice` 不得为空。
pub fn findMinMax(comptime T: type, slice: []const T) struct { usize, usize } {
assert(slice.len > 0);
var minVal = slice[0];
var maxVal = slice[0];
var minIdx: usize = 0;
var maxIdx: usize = 0;
for (slice[1..], 0..) |item, i| {
if (item < minVal) {
minVal = item;
minIdx = i + 1;
}
if (item > maxVal) {
maxVal = item;
maxIdx = i + 1;
}
}
return .{ minIdx, maxIdx };
}
test findMinMax {
try testing.expectEqual(.{ 0, 6 }, findMinMax(u8, "abcdefg"));
try testing.expectEqual(.{ 1, 0 }, findMinMax(u8, "gabcdef"));
try testing.expectEqual(.{ 0, 0 }, findMinMax(u8, "a"));
}
/// 交换两个内存位置中的内容。
pub fn swap(comptime T: type, noalias a: *T, noalias b: *T) void {
if (@inComptime()) {
// 编译期访问没有已定义布局的值的字节会产生编译错误。
const tmp = a.*;
a.* = b.*;
b.* = tmp;
} else {
// 从头到尾以流式方式交换,而非一步交换
// 全部内容,更便于优化并减少栈使用。
const a_bytes: []align(@alignOf(T)) u8 = @ptrCast(a);
const b_bytes: []align(@alignOf(T)) u8 = @ptrCast(b);
for (a_bytes, b_bytes) |*ab, *bb| {
const tmp = ab.*;
ab.* = bb.*;
bb.* = tmp;
}
}
}
test "swap works at comptime with types with no defined layout" {
comptime {
const T = struct { val: u64 };
var a: T = .{ .val = 0 };
var b: T = .{ .val = 1 };
swap(T, &a, &b);
try testing.expectEqual(T{ .val = 1 }, a);
try testing.expectEqual(T{ .val = 0 }, b);
}
}
inline fn reverseVector(comptime N: usize, comptime T: type, a: []T) [N]T {
var res: [N]T = undefined;
inline for (0..N) |i| {
res[i] = a[N - i - 1];
}
return res;
}
/// 原地反转切片顺序
pub fn reverse(comptime T: type, items: []T) void {
var i: usize = 0;
const end = items.len / 2;
vec: {
if (!use_vectors) break :vec;
if (@inComptime()) break :vec;
switch (@typeInfo(T)) {
.int, .float => {},
.pointer => |pointer| if (pointer.size == .slice) break :vec,
else => break :vec,
}
if (@bitSizeOf(T) == 0 or !comptime std.math.isPowerOfTwo(@bitSizeOf(T))) break :vec;
const simd_size = std.simd.suggestVectorLength(T) orelse break :vec;
if (simd_size > end) break :vec;
const simd_end = end - (simd_size - 1);
while (i < simd_end) : (i += simd_size) {
const left_slice = items[i .. i + simd_size];
const right_slice = items[items.len - i - simd_size .. items.len - i];
const left_shuffled: [simd_size]T = reverseVector(simd_size, T, left_slice);
const right_shuffled: [simd_size]T = reverseVector(simd_size, T, right_slice);
@memcpy(right_slice, &left_shuffled);
@memcpy(left_slice, &right_shuffled);
}
}
while (i < end) : (i += 1) {
swap(T, &items[i], &items[items.len - i - 1]);
}
}
test reverse {
{
var arr = [_]i32{ 5, 3, 1, 2, 4 };
reverse(i32, arr[0..]);
try testing.expectEqualSlices(i32, &arr, &.{ 4, 2, 1, 3, 5 });
}
{
var arr = [_]u0{};
reverse(u0, arr[0..]);
try testing.expectEqualSlices(u0, &arr, &.{});
}
{
var arr = [_]i64{ 19, 17, 15, 13, 11, 9, 7, 5, 3, 1, 2, 4, 6, 8, 10, 12, 14, 16, 18 };
reverse(i64, arr[0..]);
try testing.expectEqualSlices(i64, &arr, &.{ 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 });
}
{
var arr = [_][]const u8{ "a", "b", "c", "d" };
reverse([]const u8, arr[0..]);
try testing.expectEqualSlices([]const u8, &arr, &.{ "d", "c", "b", "a" });
}
{
const MyType = union(enum) {
a: [3]u8,
b: u24,
c,
};
var arr = [_]MyType{ .{ .a = .{ 0, 0, 0 } }, .{ .b = 0 }, .c };
reverse(MyType, arr[0..]);
try testing.expectEqualSlices(MyType, &arr, &([_]MyType{ .c, .{ .b = 0 }, .{ .a = .{ 0, 0, 0 } } }));
}
}
/// 由 `reverseIterator` 返回。
pub fn ReverseIterator(comptime T: type) type {
const ptr = switch (@typeInfo(T)) {
.pointer => |ptr| ptr,
else => @compileError("expected slice or pointer to array, found '" ++ @typeName(T) ++ "'"),
};
switch (ptr.size) {
.slice => {},
.one => if (@typeInfo(ptr.child) != .array) @compileError("expected slice or pointer to array, found '" ++ @typeName(T) ++ "'"),
.many, .c => @compileError("expected slice or pointer to array, found '" ++ @typeName(T) ++ "'"),
}
const Element = std.meta.Elem(T);
const Pointer = @Pointer(.many, ptr.attrs, Element, std.meta.sentinel(T));
const ElementPointer = @Pointer(.one, ptr.attrs, Element, null);
return struct {
ptr: Pointer,
index: usize,
pub fn next(self: *@This()) ?Element {
if (self.index == 0) return null;
self.index -= 1;
return self.ptr[self.index];
}
pub fn nextPtr(self: *@This()) ?ElementPointer {
if (self.index == 0) return null;
self.index -= 1;
return &self.ptr[self.index];
}
};
}
/// 反向遍历切片。
pub fn reverseIterator(slice: anytype) ReverseIterator(@TypeOf(slice)) {
return .{ .ptr = slice.ptr, .index = slice.len };
}
test reverseIterator {
{
var it = reverseIterator("abc");
try testing.expectEqual(@as(?u8, 'c'), it.next());
try testing.expectEqual(@as(?u8, 'b'), it.next());
try testing.expectEqual(@as(?u8, 'a'), it.next());
try testing.expectEqual(@as(?u8, null), it.next());
}
{
var array = [2]i32{ 3, 7 };
const slice: []const i32 = &array;
var it = reverseIterator(slice);
try testing.expectEqual(@as(?i32, 7), it.next());
try testing.expectEqual(@as(?i32, 3), it.next());
try testing.expectEqual(@as(?i32, null), it.next());
it = reverseIterator(slice);
try testing.expect(*const i32 == @TypeOf(it.nextPtr().?));
try testing.expectEqual(@as(?i32, 7), it.nextPtr().?.*);
try testing.expectEqual(@as(?i32, 3), it.nextPtr().?.*);
try testing.expectEqual(@as(?*const i32, null), it.nextPtr());
const mut_slice: []i32 = &array;
var mut_it = reverseIterator(mut_slice);
mut_it.nextPtr().?.* += 1;
mut_it.nextPtr().?.* += 2;
try testing.expectEqual([2]i32{ 5, 8 }, array);
}
{
var array = [2]i32{ 3, 7 };
const ptr_to_array: *const [2]i32 = &array;
var it = reverseIterator(ptr_to_array);
try testing.expectEqual(@as(?i32, 7), it.next());
try testing.expectEqual(@as(?i32, 3), it.next());
try testing.expectEqual(@as(?i32, null), it.next());
it = reverseIterator(ptr_to_array);
try testing.expect(*const i32 == @TypeOf(it.nextPtr().?));
try testing.expectEqual(@as(?i32, 7), it.nextPtr().?.*);
try testing.expectEqual(@as(?i32, 3), it.nextPtr().?.*);
try testing.expectEqual(@as(?*const i32, null), it.nextPtr());
const mut_ptr_to_array: *[2]i32 = &array;
var mut_it = reverseIterator(mut_ptr_to_array);
mut_it.nextPtr().?.* += 1;
mut_it.nextPtr().?.* += 2;
try testing.expectEqual([2]i32{ 5, 8 }, array);
}
}
/// 原地旋转数组中的值(旋转 1 位时,[0 1 2 3] 变为 [1 2 3 0])
/// 假定 0 <= amount <= items.len
pub fn rotate(comptime T: type, items: []T, amount: usize) void {
reverse(T, items[0..amount]);
reverse(T, items[amount..]);
reverse(T, items);
}
test rotate {
var arr = [_]i32{ 5, 3, 1, 2, 4 };
rotate(i32, arr[0..], 2);
try testing.expect(eql(i32, &arr, &[_]i32{ 1, 2, 4, 5, 3 }));
}
/// 尽可能多次将 needle 替换为 replacement,并写入假定大小合适的输出缓冲区。使用 replacementSize 计算适当缓冲区大小。
/// `input` 与 `output` 切片不得重叠。
/// needle 不得为空。
/// 返回实际替换次数。
///
pub fn replace(comptime T: type, input: []const T, needle: []const T, replacement: []const T, output: []T) usize {
// 空查找串将导致循环,直到输出缓冲区溢出。
assert(needle.len > 0);
var i: usize = 0;
var slide: usize = 0;
var replacements: usize = 0;
while (slide < input.len) {
if (mem.startsWith(T, input[slide..], needle)) {
@memcpy(output[i..][0..replacement.len], replacement);
i += replacement.len;
slide += needle.len;
replacements += 1;
} else {
output[i] = input[slide];
i += 1;
slide += 1;
}
}
return replacements;
}
test replace {
var output: [29]u8 = undefined;
var replacements = replace(u8, "All your base are belong to us", "base", "Zig", output[0..]);
var expected: []const u8 = "All your Zig are belong to us";
try testing.expect(replacements == 1);
try testing.expectEqualStrings(expected, output[0..expected.len]);
replacements = replace(u8, "Favor reading code over writing code.", "code", "", output[0..]);
expected = "Favor reading over writing .";
try testing.expect(replacements == 2);
try testing.expectEqualStrings(expected, output[0..expected.len]);
// 不允许空 needle,但输入可以为空。
replacements = replace(u8, "", "x", "y", output[0..0]);
expected = "";
try testing.expect(replacements == 0);
try testing.expectEqualStrings(expected, output[0..expected.len]);
// 相邻替换。
replacements = replace(u8, "\\n\\n", "\\n", "\n", output[0..]);
expected = "\n\n";
try testing.expect(replacements == 2);
try testing.expectEqualStrings(expected, output[0..expected.len]);
replacements = replace(u8, "abbba", "b", "cd", output[0..]);
expected = "acdcdcda";
try testing.expect(replacements == 3);
try testing.expectEqualStrings(expected, output[0..expected.len]);
}
/// 将所有 `match` 替换为 `replacement`。
pub fn replaceScalar(comptime T: type, slice: []T, match: T, replacement: T) void {
for (slice) |*e| {
if (e.* == match)
e.* = replacement;
}
}
/// 将连续重复元素合并为一个条目。
pub fn collapseRepeatsLen(comptime T: type, slice: []T, elem: T) usize {
if (slice.len == 0) return 0;
var write_idx: usize = 1;
var read_idx: usize = 1;
while (read_idx < slice.len) : (read_idx += 1) {
if (slice[read_idx - 1] != elem or slice[read_idx] != elem) {
slice[write_idx] = slice[read_idx];
write_idx += 1;
}
}
return write_idx;
}
/// 将连续重复元素合并为一个条目。
pub fn collapseRepeats(comptime T: type, slice: []T, elem: T) []T {
return slice[0..collapseRepeatsLen(T, slice, elem)];
}
fn testCollapseRepeats(str: []const u8, elem: u8, expected: []const u8) !void {
const mutable = try std.testing.allocator.dupe(u8, str);
defer std.testing.allocator.free(mutable);
try testing.expect(std.mem.eql(u8, collapseRepeats(u8, mutable, elem), expected));
}
test collapseRepeats {
try testCollapseRepeats("", '/', "");
try testCollapseRepeats("a", '/', "a");
try testCollapseRepeats("/", '/', "/");
try testCollapseRepeats("//", '/', "/");
try testCollapseRepeats("/a", '/', "/a");
try testCollapseRepeats("//a", '/', "/a");
try testCollapseRepeats("a/", '/', "a/");
try testCollapseRepeats("a//", '/', "a/");
try testCollapseRepeats("a/a", '/', "a/a");
try testCollapseRepeats("a//a", '/', "a/a");
try testCollapseRepeats("//a///a////", '/', "/a/a/");
}
/// 计算执行替换所需的输出缓冲区大小。
/// 待查找内容不得为空。
pub fn replacementSize(comptime T: type, input: []const T, needle: []const T, replacement: []const T) usize {
// 空查找串会导致无限循环。
assert(needle.len > 0);
var i: usize = 0;
var size: usize = input.len;
while (i < input.len) {
if (mem.startsWith(T, input[i..], needle)) {
size = size - needle.len + replacement.len;
i += needle.len;
} else {
i += 1;
}
}
return size;
}
test replacementSize {
try testing.expect(replacementSize(u8, "All your base are belong to us", "base", "Zig") == 29);
try testing.expect(replacementSize(u8, "Favor reading code over writing code.", "code", "") == 29);
try testing.expect(replacementSize(u8, "Only one obvious way to do things.", "things.", "things in Zig.") == 41);
// 不允许空 needle,但输入可以为空。
try testing.expect(replacementSize(u8, "", "x", "y") == 0);
// 相邻替换。
try testing.expect(replacementSize(u8, "\\n\\n", "\\n", "\n") == 2);
try testing.expect(replacementSize(u8, "abbba", "b", "cd") == 8);
}
/// 在预先确定大小的已分配缓冲区上执行替换。调用方必须释放返回的内存。
pub fn replaceOwned(comptime T: type, allocator: Allocator, input: []const T, needle: []const T, replacement: []const T) Allocator.Error![]T {
const output = try allocator.alloc(T, replacementSize(T, input, needle, replacement));
_ = replace(T, input, needle, replacement, output);
return output;
}
test replaceOwned {
const gpa = std.testing.allocator;
const base_replace = replaceOwned(u8, gpa, "All your base are belong to us", "base", "Zig") catch @panic("out of memory");
defer gpa.free(base_replace);
try testing.expect(eql(u8, base_replace, "All your Zig are belong to us"));
const zen_replace = replaceOwned(u8, gpa, "Favor reading code over writing code.", " code", "") catch @panic("out of memory");
defer gpa.free(zen_replace);
try testing.expect(eql(u8, zen_replace, "Favor reading over writing."));
}
/// 将小端序整数转换为主机字节序。
pub fn littleToNative(comptime T: type, x: T) T {
return switch (native_endian) {
.little => x,
.big => @byteSwap(x),
};
}
/// 将大端整数转换为主机字节序。
pub fn bigToNative(comptime T: type, x: T) T {
return switch (native_endian) {
.little => @byteSwap(x),
.big => x,
};
}
/// 将整数从指定字节序转换为主机字节序。
pub fn toNative(comptime T: type, x: T, endianness_of_x: Endian) T {
return switch (endianness_of_x) {
.little => littleToNative(T, x),
.big => bigToNative(T, x),
};
}
/// 将采用宿主端序的整数转换为所需端序。
pub fn nativeTo(comptime T: type, x: T, desired_endianness: Endian) T {
return switch (desired_endianness) {
.little => nativeToLittle(T, x),
.big => nativeToBig(T, x),
};
}
/// 将采用宿主端序的整数转换为小端序。
pub fn nativeToLittle(comptime T: type, x: T) T {
return switch (native_endian) {
.little => x,
.big => @byteSwap(x),
};
}
/// 将采用主机字节序的整数转换为大端字节序。
pub fn nativeToBig(comptime T: type, x: T) T {
return switch (native_endian) {
.little => @byteSwap(x),
.big => x,
};
}
/// 返回需要加到给定指针上的元素数量,使指针对齐到指定数量的倍数。
/// 满足以下任一条件时返回 `null`:
/// - 对齐后的指针超出地址空间。
/// - 对齐所需的偏移量不是所指类型大小的整数倍。
///
///
pub fn alignPointerOffset(ptr: anytype, align_to: usize) ?usize {
assert(isValidAlign(align_to));
const T = @TypeOf(ptr);
const info = @typeInfo(T);
if (info != .pointer or info.pointer.size != .many)
@compileError("expected many item pointer, got " ++ @typeName(T));
// 如果指针已正确对齐,则不进行操作。
if (align_to <= info.pointer.attrs.@"align" orelse @alignOf(info.pointer.child))
return 0;
// 计算对齐后的基址,注意检查溢出。
const addr = @intFromPtr(ptr);
var ov = @addWithOverflow(addr, align_to - 1);
if (ov[1] != 0) return null;
ov[0] &= ~@as(usize, align_to - 1);
// 增量以字节表示,
// 将其转换为子类型元素数量。
const delta = ov[0] - addr;
const pointee_size = @sizeOf(info.pointer.child);
if (delta % pointee_size != 0) return null;
return delta / pointee_size;
}
/// 将给定指针值按指定对齐因子对齐。
/// 返回对齐后的指针;满足以下任一条件时
/// 返回 null:
/// - 对齐后的指针超出地址空间;
/// - 为对齐指针所需的位移不是所指类型
/// 大小的整数倍。
pub fn alignPointer(ptr: anytype, align_to: usize) ?@TypeOf(ptr) {
const adjust_off = alignPointerOffset(ptr, align_to) orelse return null;
// 避免使用 ptrFromInt,以免丢失指针来源信息。
return @alignCast(ptr + adjust_off);
}
test alignPointer {
const S = struct {
fn checkAlign(comptime T: type, base: usize, align_to: usize, expected: usize) !void {
const ptr: T = @ptrFromInt(base);
const aligned = alignPointer(ptr, align_to);
try testing.expectEqual(expected, @intFromPtr(aligned));
}
};
try S.checkAlign([*]u8, 0x123, 0x200, 0x200);
try S.checkAlign([*]align(4) u8, 0x10, 2, 0x10);
try S.checkAlign([*]u32, 0x10, 2, 0x10);
try S.checkAlign([*]u32, 0x4, 16, 0x10);
// 未对齐。
try S.checkAlign([*]align(1) u32, 0x3, 2, 0);
// 溢出。
try S.checkAlign([*]u32, math.maxInt(usize) - 3, 8, 0);
}
fn CopyPtrAttrs(
comptime source: type,
comptime size: std.builtin.Type.Pointer.Size,
comptime child: type,
) type {
const ptr = @typeInfo(source).pointer;
var attrs = ptr.attrs;
if (attrs.@"align" == null) {
const want = @alignOf(ptr.child);
if (@alignOf(child) != want) {
attrs.@"align" = want;
}
}
return @Pointer(size, attrs, child, null);
}
fn AsBytesReturnType(comptime P: type) type {
const pointer = @typeInfo(P).pointer;
assert(pointer.size == .one);
const size = @sizeOf(pointer.child);
return CopyPtrAttrs(P, .one, [size]u8);
}
/// 给定指向单个元素的指针,返回底层字节的切片,并保留指针属性。
pub fn asBytes(ptr: anytype) AsBytesReturnType(@TypeOf(ptr)) {
return @ptrCast(@alignCast(ptr));
}
test asBytes {
const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xEF\xBE\xAD\xDE",
};
try testing.expect(eql(u8, asBytes(&deadbeef), deadbeef_bytes));
var codeface = @as(u32, 0xC0DEFACE);
for (asBytes(&codeface)) |*b|
b.* = 0;
try testing.expect(codeface == 0);
const S = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
};
const inst = S{
.a = 0xBE,
.b = 0xEF,
.c = 0xDE,
.d = 0xA1,
};
switch (native_endian) {
.little => {
try testing.expect(eql(u8, asBytes(&inst), "\xBE\xEF\xDE\xA1"));
},
.big => {
try testing.expect(eql(u8, asBytes(&inst), "\xA1\xDE\xEF\xBE"));
},
}
const ZST = struct {};
const zero = ZST{};
try testing.expect(eql(u8, asBytes(&zero), ""));
}
test "asBytes preserves pointer attributes" {
const inArr: u32 align(16) = 0xDEADBEEF;
const inPtr = @as(*align(16) const volatile u32, @ptrCast(&inArr));
const outSlice = asBytes(inPtr);
const in = @typeInfo(@TypeOf(inPtr)).pointer;
const out = @typeInfo(@TypeOf(outSlice)).pointer;
const in_attrs = in.attrs;
const out_attrs = out.attrs;
try testing.expectEqual(in_attrs.@"const", out_attrs.@"const");
try testing.expectEqual(in_attrs.@"volatile", out_attrs.@"volatile");
try testing.expectEqual(in_attrs.@"allowzero", out_attrs.@"allowzero");
try testing.expectEqual(in_attrs.@"align", out_attrs.@"align");
}
/// 接受任意值,以数组形式返回其字节的副本。
pub fn toBytes(value: anytype) [@sizeOf(@TypeOf(value))]u8 {
return asBytes(&value).*;
}
test toBytes {
var my_bytes = toBytes(@as(u32, 0x12345678));
switch (native_endian) {
.big => try testing.expect(eql(u8, &my_bytes, "\x12\x34\x56\x78")),
.little => try testing.expect(eql(u8, &my_bytes, "\x78\x56\x34\x12")),
}
my_bytes[0] = '\x99';
switch (native_endian) {
.big => try testing.expect(eql(u8, &my_bytes, "\x99\x34\x56\x78")),
.little => try testing.expect(eql(u8, &my_bytes, "\x99\x56\x34\x12")),
}
}
fn BytesAsValueReturnType(comptime T: type, comptime B: type) type {
return CopyPtrAttrs(B, .one, T);
}
/// 给定字节数组指针,返回指向由这些字节作为存储的指定类型值的指针,并保留指针属性。
///
pub fn bytesAsValue(comptime T: type, bytes: anytype) BytesAsValueReturnType(T, @TypeOf(bytes)) {
return @ptrCast(bytes);
}
test bytesAsValue {
const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xEF\xBE\xAD\xDE",
};
try testing.expect(deadbeef == bytesAsValue(u32, deadbeef_bytes).*);
var codeface_bytes: [4]u8 = switch (native_endian) {
.big => "\xC0\xDE\xFA\xCE",
.little => "\xCE\xFA\xDE\xC0",
}.*;
const codeface = bytesAsValue(u32, &codeface_bytes);
try testing.expect(codeface.* == 0xC0DEFACE);
codeface.* = 0;
for (codeface_bytes) |b|
try testing.expect(b == 0);
const S = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
};
const inst = S{
.a = 0xBE,
.b = 0xEF,
.c = 0xDE,
.d = 0xA1,
};
const inst_bytes = switch (native_endian) {
.little => "\xBE\xEF\xDE\xA1",
.big => "\xA1\xDE\xEF\xBE",
};
const inst2 = bytesAsValue(S, inst_bytes);
try testing.expect(std.meta.eql(inst, inst2.*));
}
test "bytesAsValue preserves pointer attributes" {
const inArr align(16) = [4]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
const inSlice = @as(*align(16) const volatile [4]u8, @ptrCast(&inArr))[0..];
const outPtr = bytesAsValue(u32, inSlice);
const in_attrs = @typeInfo(@TypeOf(inSlice)).pointer.attrs;
const out_attrs = @typeInfo(@TypeOf(outPtr)).pointer.attrs;
try testing.expectEqual(in_attrs.@"const", out_attrs.@"const");
try testing.expectEqual(in_attrs.@"volatile", out_attrs.@"volatile");
try testing.expectEqual(in_attrs.@"allowzero", out_attrs.@"allowzero");
try testing.expectEqual(in_attrs.@"align", out_attrs.@"align");
}
/// 给定字节数组指针,返回指定类型的值,
/// 其底层数据为这些字节的副本。
pub fn bytesToValue(comptime T: type, bytes: anytype) T {
return bytesAsValue(T, bytes).*;
}
test bytesToValue {
const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xEF\xBE\xAD\xDE",
};
const deadbeef = bytesToValue(u32, deadbeef_bytes);
try testing.expect(deadbeef == @as(u32, 0xDEADBEEF));
}
fn BytesAsSliceReturnType(comptime T: type, comptime bytesType: type) type {
return CopyPtrAttrs(bytesType, .slice, T);
}
/// 给定字节切片,返回由这些字节作为底层存储、
/// 元素为指定类型的切片,保留指针属性。
/// 若 `T` 的大小为零字节,则返回切片的 len 为零。
pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T, @TypeOf(bytes)) {
// 不要将未定义指针传给 @ptrCast,
// 因为它可能等于零,从而无法通过空指针检查。
if (bytes.len == 0 or @sizeOf(T) == 0) {
return &[0]T{};
}
const cast_target = CopyPtrAttrs(@TypeOf(bytes), .many, T);
return @as(cast_target, @ptrCast(bytes))[0..@divExact(bytes.len, @sizeOf(T))];
}
test bytesAsSlice {
{
const bytes = [_]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
const slice = bytesAsSlice(u16, bytes[0..]);
try testing.expect(slice.len == 2);
try testing.expect(bigToNative(u16, slice[0]) == 0xDEAD);
try testing.expect(bigToNative(u16, slice[1]) == 0xBEEF);
}
{
const bytes = [_]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
var runtime_zero: usize = 0;
_ = &runtime_zero;
const slice = bytesAsSlice(u16, bytes[runtime_zero..]);
try testing.expect(slice.len == 2);
try testing.expect(bigToNative(u16, slice[0]) == 0xDEAD);
try testing.expect(bigToNative(u16, slice[1]) == 0xBEEF);
}
}
test "bytesAsSlice keeps pointer alignment" {
{
var bytes = [_]u8{ 0x01, 0x02, 0x03, 0x04 };
const numbers = bytesAsSlice(u32, bytes[0..]);
try comptime testing.expect(@TypeOf(numbers) == []align(@alignOf(@TypeOf(bytes))) u32);
}
{
var bytes = [_]u8{ 0x01, 0x02, 0x03, 0x04 };
var runtime_zero: usize = 0;
_ = &runtime_zero;
const numbers = bytesAsSlice(u32, bytes[runtime_zero..]);
try comptime testing.expect(@TypeOf(numbers) == []align(@alignOf(@TypeOf(bytes))) u32);
}
}
test "bytesAsSlice on a packed struct" {
const F = packed struct {
a: u8,
};
const b: [1]u8 = .{9};
const f = bytesAsSlice(F, &b);
try testing.expect(f[0].a == 9);
}
test "bytesAsSlice with specified alignment" {
var bytes align(4) = [_]u8{
0x33,
0x33,
0x33,
0x33,
};
const slice: []u32 = std.mem.bytesAsSlice(u32, bytes[0..]);
try testing.expect(slice[0] == 0x33333333);
}
test "bytesAsSlice preserves pointer attributes" {
const inArr align(16) = [4]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
const inSlice = @as(*align(16) const volatile [4]u8, @ptrCast(&inArr))[0..];
const outSlice = bytesAsSlice(u16, inSlice);
const in_attrs = @typeInfo(@TypeOf(inSlice)).pointer.attrs;
const out_attrs = @typeInfo(@TypeOf(outSlice)).pointer.attrs;
try testing.expectEqual(in_attrs.@"const", out_attrs.@"const");
try testing.expectEqual(in_attrs.@"volatile", out_attrs.@"volatile");
try testing.expectEqual(in_attrs.@"allowzero", out_attrs.@"allowzero");
try testing.expectEqual(in_attrs.@"align", out_attrs.@"align");
}
test "bytesAsSlice with zero-bit element type" {
{
const bytes = [_]u8{};
const slice = bytesAsSlice(void, &bytes);
try testing.expectEqual(0, slice.len);
}
{
const bytes = [_]u8{ 0x01, 0x02, 0x03, 0x04 };
const slice = bytesAsSlice(u0, &bytes);
try testing.expectEqual(0, slice.len);
}
}
fn SliceAsBytesReturnType(comptime Slice: type) type {
return CopyPtrAttrs(Slice, .slice, u8);
}
/// 给定切片,返回底层字节的切片,并保留指针属性。
pub fn sliceAsBytes(slice: anytype) SliceAsBytesReturnType(@TypeOf(slice)) {
const Slice = @TypeOf(slice);
// 由零位值组成的切片始终占用零字节。
if (@sizeOf(std.meta.Elem(Slice)) == 0) return &[0]u8{};
// 不要将未定义指针传给 @ptrCast,
// 因为它可能等于零,从而无法通过空指针检查。
if (slice.len == 0 and std.meta.sentinel(Slice) == null) return &[0]u8{};
const cast_target = CopyPtrAttrs(Slice, .many, u8);
return @as(cast_target, @ptrCast(slice))[0 .. slice.len * @sizeOf(std.meta.Elem(Slice))];
}
test sliceAsBytes {
const bytes = [_]u16{ 0xDEAD, 0xBEEF };
const slice = sliceAsBytes(bytes[0..]);
try testing.expect(slice.len == 4);
try testing.expect(eql(u8, slice, switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xAD\xDE\xEF\xBE",
}));
}
test "sliceAsBytes with sentinel slice" {
const empty_string: [:0]const u8 = "";
const bytes = sliceAsBytes(empty_string);
try testing.expect(bytes.len == 0);
}
test "sliceAsBytes with zero-bit element type" {
const lots_of_nothing: [10_000]void = @splat({});
const bytes = sliceAsBytes(&lots_of_nothing);
try testing.expect(bytes.len == 0);
}
test "sliceAsBytes packed struct at runtime and comptime" {
const Foo = packed struct {
a: u4,
b: u4,
};
const S = struct {
fn doTheTest() !void {
var foo: Foo = undefined;
var slice = sliceAsBytes(@as(*[1]Foo, &foo)[0..1]);
slice[0] = 0x13;
try testing.expect(foo.a == 0x3);
try testing.expect(foo.b == 0x1);
}
};
try S.doTheTest();
try comptime S.doTheTest();
}
test "sliceAsBytes and bytesAsSlice back" {
try testing.expect(@sizeOf(i32) == 4);
var big_thing_array = [_]i32{ 1, 2, 3, 4 };
const big_thing_slice: []i32 = big_thing_array[0..];
const bytes = sliceAsBytes(big_thing_slice);
try testing.expect(bytes.len == 4 * 4);
bytes[4] = 0;
bytes[5] = 0;
bytes[6] = 0;
bytes[7] = 0;
try testing.expect(big_thing_slice[1] == 0);
const big_thing_again = bytesAsSlice(i32, bytes);
try testing.expect(big_thing_again[2] == 3);
big_thing_again[2] = -1;
try testing.expect(bytes[8] == math.maxInt(u8));
try testing.expect(bytes[9] == math.maxInt(u8));
try testing.expect(bytes[10] == math.maxInt(u8));
try testing.expect(bytes[11] == math.maxInt(u8));
}
test "sliceAsBytes preserves pointer attributes" {
const inArr align(16) = [2]u16{ 0xDEAD, 0xBEEF };
const inSlice = @as(*align(16) const volatile [2]u16, @ptrCast(&inArr))[0..];
const outSlice = sliceAsBytes(inSlice);
const in_attrs = @typeInfo(@TypeOf(inSlice)).pointer.attrs;
const out_attrs = @typeInfo(@TypeOf(outSlice)).pointer.attrs;
try testing.expectEqual(in_attrs.@"const", out_attrs.@"const");
try testing.expectEqual(in_attrs.@"volatile", out_attrs.@"volatile");
try testing.expectEqual(in_attrs.@"allowzero", out_attrs.@"allowzero");
try testing.expectEqual(in_attrs.@"align", out_attrs.@"align");
}
/// 如果提供的切片没有以哨兵值结尾,则不执行任何操作并返回该切片。
/// 如果切片以哨兵值结尾,则返回不带哨兵的切片,
/// 长度加一,以包含被吸收的哨兵元素。
pub fn absorbSentinel(slice: anytype) AbsorbSentinel(@TypeOf(slice)) {
const info = @typeInfo(@TypeOf(slice)).pointer;
switch (info.size) {
.slice => {
if (info.sentinel_ptr == null) {
return slice;
} else {
return slice.ptr[0 .. slice.len + 1];
}
},
.one => {
const child_info = @typeInfo(info.child).array;
if (child_info.sentinel_ptr == null) {
return slice;
} else {
return slice[0 .. child_info.len + 1];
}
},
else => unreachable,
}
}
test absorbSentinel {
{
var buffer: [3:0]u8 = .{ 1, 2, 3 };
const foo: [:0]const u8 = &buffer;
const bar: []const u8 = &buffer;
const baz: *const [3:0]u8 = &buffer;
try testing.expectEqual([]const u8, @TypeOf(absorbSentinel(foo)));
try testing.expectEqual([]const u8, @TypeOf(absorbSentinel(bar)));
try testing.expectEqual(*const [4]u8, @TypeOf(absorbSentinel(baz)));
try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 0 }, absorbSentinel(foo));
try testing.expectEqualSlices(u8, &.{ 1, 2, 3 }, absorbSentinel(bar));
try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 0 }, absorbSentinel(baz));
}
{
var buffer: [3:0]u8 = .{ 1, 2, 3 };
const foo: [:0]u8 = &buffer;
const bar: []u8 = &buffer;
const baz: *[3:0]u8 = &buffer;
try testing.expectEqual([]u8, @TypeOf(absorbSentinel(foo)));
try testing.expectEqual([]u8, @TypeOf(absorbSentinel(bar)));
try testing.expectEqual(*[4]u8, @TypeOf(absorbSentinel(baz)));
var expected_foo = [_]u8{ 1, 2, 3, 0 };
try testing.expectEqualSlices(u8, &expected_foo, absorbSentinel(foo));
var expected_bar = [_]u8{ 1, 2, 3 };
try testing.expectEqualSlices(u8, &expected_bar, absorbSentinel(bar));
var expected_baz = [_]u8{ 1, 2, 3, 0 };
try testing.expectEqualSlices(u8, &expected_baz, absorbSentinel(baz));
}
}
/// 将地址向下舍入到最近的对齐地址(可能是当前地址)。
/// 与 `alignForward` 不同,`alignment` 可为任意正数,不限于 2 的幂。
pub fn alignForwardAnyAlign(comptime T: type, addr: T, alignment: T) T {
if (isValidAlignGeneric(T, alignment))
return alignForward(T, addr, alignment);
assert(alignment != 0);
return alignBackwardAnyAlign(T, addr + (alignment - 1), alignment);
}
/// 将地址向上舍入到下一个(或当前)对齐地址。
/// 对齐值必须为大于 0 的 2 的幂。
/// 断言地址向上舍入不会引起整数溢出。
pub fn alignForward(comptime T: type, addr: T, alignment: T) T {
assert(isValidAlignGeneric(T, alignment));
return alignBackward(T, addr + (alignment - 1), alignment);
}
/// 使用 log2 表示,将地址向上舍入到下一个对齐边界。
/// 等同于以 alignment = 1 << log2_alignment 调用 alignForward。
/// 已知对齐量为 2 的幂时更高效。
pub fn alignForwardLog2(addr: usize, log2_alignment: u8) usize {
const alignment = @as(usize, 1) << @as(math.Log2Int(usize), @intCast(log2_alignment));
return alignForward(usize, addr, alignment);
}
/// 强制对表达式求值;即使最终丢弃结果,
/// 也尝试阻止编译器将计算优化掉。
///
// TODO: 在 @declareSideEffect() 可用后使用它,参见 https://github.com/ziglang/zig/issues/6168
pub fn doNotOptimizeAway(val: anytype) void {
if (@inComptime()) return;
if (builtin.zig_backend == .stage2_c and builtin.abi == .msvc) {
_ = @atomicRmw(*const anyopaque, @as(*volatile *const anyopaque, &struct {
var escape: *const anyopaque = undefined;
}.escape), .Xchg, &val, .acq_rel); // TODO: syncscope("singlethreaded")
return;
}
switch (@typeInfo(@TypeOf(val))) {
.void, .null, .comptime_int, .comptime_float => return,
.@"enum" => doNotOptimizeAway(@backingInt(val)),
.bool => doNotOptimizeAway(@intFromBool(val)),
.int => |int| {
// SPIR-V 目标本身没有寄存器,而是使用
// 绑定到标识的值,这些值可传递给有效指令。
// 某些 SPIR-V 目标不定义 c_long,因此在这些目标上
// 允许任意大小的整数。
const val_fits_in_gp_register = builtin.target.cpu.arch.isSpirV() or fits: {
const max_gp_register_bits = @bitSizeOf(c_long);
break :fits int.bits <= max_gp_register_bits;
};
if (val_fits_in_gp_register) {
const val2 = @as(
@Int(int.signedness, @max(8, std.math.ceilPowerOfTwoAssert(u16, int.bits))),
val,
);
asm volatile (""
:
: [_] "r" (val2),
);
} else {
doNotOptimizeAway(&val);
}
},
.float => |float| switch (float.bits) {
else => comptime unreachable,
16, 80, 128 => doNotOptimizeAway(&val),
32, 64 => asm volatile (""
:
: [_] "rm" (val),
),
},
.pointer => asm volatile (""
:
: [_] "m" (val),
: .{ .memory = true }),
.array => |array| if (array.len * @sizeOf(array.child) <= 64) {
for (val) |v| doNotOptimizeAway(v);
} else doNotOptimizeAway(&val),
else => doNotOptimizeAway(&val),
}
}
test doNotOptimizeAway {
comptime doNotOptimizeAway("test");
doNotOptimizeAway(null);
doNotOptimizeAway(true);
doNotOptimizeAway(0);
doNotOptimizeAway(0.0);
doNotOptimizeAway(@as(u1, 0));
doNotOptimizeAway(@as(u3, 0));
doNotOptimizeAway(@as(u8, 0));
doNotOptimizeAway(@as(u16, 0));
doNotOptimizeAway(@as(u32, 0));
doNotOptimizeAway(@as(u64, 0));
doNotOptimizeAway(@as(u128, 0));
doNotOptimizeAway(@as(u13, 0));
doNotOptimizeAway(@as(u37, 0));
doNotOptimizeAway(@as(u96, 0));
doNotOptimizeAway(@as(u200, 0));
doNotOptimizeAway(@as(f32, 0.0));
doNotOptimizeAway(@as(f64, 0.0));
doNotOptimizeAway(@as([4]u8, @splat(0)));
doNotOptimizeAway(@as([100]u8, @splat(0)));
doNotOptimizeAway(@as(std.builtin.Endian, .little));
}
test alignForward {
try testing.expect(alignForward(usize, 1, 1) == 1);
try testing.expect(alignForward(usize, 2, 1) == 2);
try testing.expect(alignForward(usize, 1, 2) == 2);
try testing.expect(alignForward(usize, 2, 2) == 2);
try testing.expect(alignForward(usize, 3, 2) == 4);
try testing.expect(alignForward(usize, 4, 2) == 4);
try testing.expect(alignForward(usize, 7, 8) == 8);
try testing.expect(alignForward(usize, 8, 8) == 8);
try testing.expect(alignForward(usize, 9, 8) == 16);
try testing.expect(alignForward(usize, 15, 8) == 16);
try testing.expect(alignForward(usize, 16, 8) == 16);
try testing.expect(alignForward(usize, 17, 8) == 24);
}
/// 将地址向下舍入到前一个(或当前)对齐地址。
/// 与 `alignBackward` 不同,`alignment` 可为任意正数,不限于 2 的幂。
pub fn alignBackwardAnyAlign(comptime T: type, addr: T, alignment: T) T {
if (isValidAlignGeneric(T, alignment))
return alignBackward(T, addr, alignment);
assert(alignment != 0);
return addr - @mod(addr, alignment);
}
/// 将地址向下舍入到前一个或当前对齐地址。
/// 对齐值必须为大于 0 的 2 的幂。
pub fn alignBackward(comptime T: type, addr: T, alignment: T) T {
assert(isValidAlignGeneric(T, alignment));
// 000010000 // 示例对齐
// 000001111 // 减去 1
// 111110000 // 按位取反
return addr & ~(alignment - 1);
}
/// 返回 `alignment` 是否为有效对齐值,即正数 2 的幂。
///
pub fn isValidAlign(alignment: usize) bool {
return isValidAlignGeneric(usize, alignment);
}
/// 返回 `alignment` 是否为有效对齐值,即正数 2 的幂。
///
pub fn isValidAlignGeneric(comptime T: type, alignment: T) bool {
return alignment > 0 and std.math.isPowerOfTwo(alignment);
}
/// 若 i 按给定对齐值对齐,则返回 true。
/// 适用于任意正对齐值,不限于 2 的幂。
/// 对 2 的幂对齐值,`isAligned` 更高效。
pub fn isAlignedAnyAlign(i: usize, alignment: usize) bool {
if (isValidAlign(alignment))
return isAligned(i, alignment);
assert(alignment != 0);
return 0 == @mod(i, alignment);
}
/// 若 addr 按 2^log2_alignment 对齐,则返回 true。
/// 已知对齐量为 2 的幂时,比 `isAligned` 更高效。
/// log2_alignment 必须 < @bitSizeOf(usize)。
pub fn isAlignedLog2(addr: usize, log2_alignment: u8) bool {
return @ctz(addr) >= log2_alignment;
}
/// 给定地址和对齐值,若地址为对齐值的倍数,则返回 true。
/// 对齐值必须是大于 0 的 2 的幂。
pub fn isAligned(addr: usize, alignment: usize) bool {
return isAlignedGeneric(u64, addr, alignment);
}
/// `isAligned` 的泛型版本,适用于任意整数类型。
/// 若 addr 按给定对齐值对齐,则返回 true。
/// 对齐值必须为大于 0 的 2 的幂。
pub fn isAlignedGeneric(comptime T: type, addr: T, alignment: T) bool {
return alignBackward(T, addr, alignment) == addr;
}
test isAligned {
try testing.expect(isAligned(0, 4));
try testing.expect(isAligned(1, 1));
try testing.expect(isAligned(2, 1));
try testing.expect(isAligned(2, 2));
try testing.expect(!isAligned(2, 4));
try testing.expect(isAligned(3, 1));
try testing.expect(!isAligned(3, 2));
try testing.expect(!isAligned(3, 4));
try testing.expect(isAligned(4, 4));
try testing.expect(isAligned(4, 2));
try testing.expect(isAligned(4, 1));
try testing.expect(!isAligned(4, 8));
try testing.expect(!isAligned(4, 16));
}
test "freeing empty string with null-terminated sentinel" {
const empty_string = try testing.allocator.dupeSentinel(u8, "", 0);
testing.allocator.free(empty_string);
}
/// 返回具有指定新对齐要求的切片,
/// 其余指针属性均从 `AttributeSource` 复制。
fn AlignedSlice(comptime AttributeSource: type, comptime new_alignment: usize) type {
const ptr = @typeInfo(AttributeSource).pointer;
var attrs = ptr.attrs;
attrs.@"align" = new_alignment;
return @Pointer(.slice, attrs, ptr.child, null);
}
/// 返回给定字节中满足新对齐要求的最大切片,
/// 若给定字节中没有符合要求的地址,则返回 `null`。
pub fn alignInBytes(bytes: []u8, comptime new_alignment: usize) ?[]align(new_alignment) u8 {
const begin_address = @intFromPtr(bytes.ptr);
const end_address = begin_address + bytes.len;
const begin_address_aligned = mem.alignForward(usize, begin_address, new_alignment);
const new_length = std.math.sub(usize, end_address, begin_address_aligned) catch |e| switch (e) {
error.Overflow => return null,
};
const alignment_offset = begin_address_aligned - begin_address;
return @alignCast(bytes[alignment_offset .. alignment_offset + new_length]);
}
/// 返回给定切片内满足新对齐要求的最大子切片;
/// 若给定切片不包含符合要求的地址,则返回 `null`。
pub fn alignInSlice(slice: anytype, comptime new_alignment: usize) ?AlignedSlice(@TypeOf(slice), new_alignment) {
const bytes = sliceAsBytes(slice);
const aligned_bytes = alignInBytes(bytes, new_alignment) orelse return null;
const Element = @TypeOf(slice[0]);
const slice_length_bytes = aligned_bytes.len - (aligned_bytes.len % @sizeOf(Element));
const aligned_slice = bytesAsSlice(Element, aligned_bytes[0..slice_length_bytes]);
return @alignCast(aligned_slice);
}
test "read/write(Var)PackedInt" {
// 此测试生成的代码过多,无法在 WASI 上执行。
// LLVM 后端失败,报错 "too many locals: locals exceed maximum"
if (builtin.cpu.arch.isWasm()) return error.SkipZigTest;
const foreign_endian: Endian = if (native_endian == .big) .little else .big;
const expect = std.testing.expect;
var prng = std.Random.DefaultPrng.init(1234);
const random = prng.random();
@setEvalBranchQuota(10_000);
inline for ([_]type{ u8, u16, u32, u128 }) |BackingType| {
for ([_]BackingType{
@as(BackingType, 0), // 全零
-%@as(BackingType, 1), // 全一
random.int(BackingType), // 随机
random.int(BackingType), // 随机
random.int(BackingType), // 随机
}) |init_value| {
const uTs = [_]type{ u1, u3, u7, u8, u9, u10, u15, u16, u86 };
const iTs = [_]type{ i1, i3, i7, i8, i9, i10, i15, i16, i86 };
inline for (uTs ++ iTs) |PackedType| {
if (@bitSizeOf(PackedType) > @bitSizeOf(BackingType))
continue;
const iPackedType = @Int(.signed, @bitSizeOf(PackedType));
const uPackedType = @Int(.unsigned, @bitSizeOf(PackedType));
const Log2T = std.math.Log2Int(BackingType);
const offset_at_end = @bitSizeOf(BackingType) - @bitSizeOf(PackedType);
for ([_]usize{ 0, 1, 7, 8, 9, 10, 15, 16, 86, offset_at_end }) |offset| {
if (offset > offset_at_end or offset == @bitSizeOf(BackingType))
continue;
for ([_]PackedType{
~@as(PackedType, 0), // 所有位均为一:-1 iN / maxInt uN
@as(PackedType, 0), // 全零:0 iN / 0 uN
@bitCast(@as(iPackedType, math.maxInt(iPackedType))), // maxInt iN
@bitCast(@as(iPackedType, math.minInt(iPackedType))), // maxInt iN
random.int(PackedType), // 随机
random.int(PackedType), // 随机
}) |write_value| {
{ // 固定大小读写(本机字节序)
// 初始化 Value
var value: BackingType = init_value;
// 读取
const read_value1 = readPackedInt(PackedType, asBytes(&value), offset, native_endian);
try expect(read_value1 == @as(PackedType, @bitCast(@as(uPackedType, @truncate(value >> @as(Log2T, @intCast(offset)))))));
// 写入
writePackedInt(PackedType, asBytes(&value), offset, write_value, native_endian);
try expect(write_value == @as(PackedType, @bitCast(@as(uPackedType, @truncate(value >> @as(Log2T, @intCast(offset)))))));
// 再次读取
const read_value2 = readPackedInt(PackedType, asBytes(&value), offset, native_endian);
try expect(read_value2 == write_value);
// 验证目标整数之外的位未被修改
const diff_bits = init_value ^ value;
if (offset != offset_at_end)
try expect(diff_bits >> @as(Log2T, @intCast(offset + @bitSizeOf(PackedType))) == 0);
if (offset != 0)
try expect(diff_bits << @as(Log2T, @intCast(@bitSizeOf(BackingType) - offset)) == 0);
}
{ // 固定大小的读写(外部字节序)
// 初始化 Value
var value: BackingType = @byteSwap(init_value);
// 读取
const read_value1 = readPackedInt(PackedType, asBytes(&value), offset, foreign_endian);
try expect(read_value1 == @as(PackedType, @bitCast(@as(uPackedType, @truncate(@byteSwap(value) >> @as(Log2T, @intCast(offset)))))));
// 写入
writePackedInt(PackedType, asBytes(&value), offset, write_value, foreign_endian);
try expect(write_value == @as(PackedType, @bitCast(@as(uPackedType, @truncate(@byteSwap(value) >> @as(Log2T, @intCast(offset)))))));
// 再次读取
const read_value2 = readPackedInt(PackedType, asBytes(&value), offset, foreign_endian);
try expect(read_value2 == write_value);
// 验证目标整数之外的位未被修改
const diff_bits = init_value ^ @byteSwap(value);
if (offset != offset_at_end)
try expect(diff_bits >> @as(Log2T, @intCast(offset + @bitSizeOf(PackedType))) == 0);
if (offset != 0)
try expect(diff_bits << @as(Log2T, @intCast(@bitSizeOf(BackingType) - offset)) == 0);
}
const signedness = @typeInfo(PackedType).int.signedness;
const NextPowerOfTwoInt = @Int(signedness, try std.math.ceilPowerOfTwo(u16, @bitSizeOf(PackedType)));
const ui64 = @Int(signedness, 64);
inline for ([_]type{ PackedType, NextPowerOfTwoInt, ui64 }) |U| {
{ // 可变大小读写(本机字节序)
if (@bitSizeOf(U) < @bitSizeOf(PackedType))
continue;
// 初始化 Value
var value: BackingType = init_value;
// 读取
const read_value1 = readVarPackedInt(U, asBytes(&value), offset, @bitSizeOf(PackedType), native_endian, signedness);
try expect(read_value1 == @as(PackedType, @bitCast(@as(uPackedType, @truncate(value >> @as(Log2T, @intCast(offset)))))));
// 写入
writeVarPackedInt(asBytes(&value), offset, @bitSizeOf(PackedType), @as(U, write_value), native_endian);
try expect(write_value == @as(PackedType, @bitCast(@as(uPackedType, @truncate(value >> @as(Log2T, @intCast(offset)))))));
// 再次读取
const read_value2 = readVarPackedInt(U, asBytes(&value), offset, @bitSizeOf(PackedType), native_endian, signedness);
try expect(read_value2 == write_value);
// 验证目标整数之外的位未被修改
const diff_bits = init_value ^ value;
if (offset != offset_at_end)
try expect(diff_bits >> @as(Log2T, @intCast(offset + @bitSizeOf(PackedType))) == 0);
if (offset != 0)
try expect(diff_bits << @as(Log2T, @intCast(@bitSizeOf(BackingType) - offset)) == 0);
}
{ // 可变大小的读写(外部字节序)
if (@bitSizeOf(U) < @bitSizeOf(PackedType))
continue;
// 初始化 Value
var value: BackingType = @byteSwap(init_value);
// 读取
const read_value1 = readVarPackedInt(U, asBytes(&value), offset, @bitSizeOf(PackedType), foreign_endian, signedness);
try expect(read_value1 == @as(PackedType, @bitCast(@as(uPackedType, @truncate(@byteSwap(value) >> @as(Log2T, @intCast(offset)))))));
// 写入
writeVarPackedInt(asBytes(&value), offset, @bitSizeOf(PackedType), @as(U, write_value), foreign_endian);
try expect(write_value == @as(PackedType, @bitCast(@as(uPackedType, @truncate(@byteSwap(value) >> @as(Log2T, @intCast(offset)))))));
// 再次读取
const read_value2 = readVarPackedInt(U, asBytes(&value), offset, @bitSizeOf(PackedType), foreign_endian, signedness);
try expect(read_value2 == write_value);
// 验证目标整数之外的位未被修改
const diff_bits = init_value ^ @byteSwap(value);
if (offset != offset_at_end)
try expect(diff_bits >> @as(Log2T, @intCast(offset + @bitSizeOf(PackedType))) == 0);
if (offset != 0)
try expect(diff_bits << @as(Log2T, @intCast(@bitSizeOf(BackingType) - offset)) == 0);
}
}
}
}
}
}
}
}
pub const PrintError = error{
/// 已尽量向缓冲区写入数据,但缓冲区太小,
/// 无法容纳所有打印字节。
NoSpaceLeft,
};
/// 将格式化字符串写入 `buffer`。返回从 `buffer`
/// 索引 0 开始、包含结果的切片;若截断了一个或多个字节,
/// 则返回 `error.NoSpaceLeft`。
///
/// 参见 `std.Io.Writer.print`。
pub fn print(buffer: []u8, comptime format: []const u8, args: anytype) PrintError![]u8 {
var w: std.Io.Writer = .fixed(buffer);
w.print(format, args) catch |err| switch (err) {
error.WriteFailed => return error.NoSpaceLeft,
};
return w.buffered();
}
test print {
const x: i32 = -1;
const y: []const u8 = "hi";
var buffer: [64]u8 = undefined;
const s = try print(&buffer, "{d}={s}", .{ x, y });
try testing.expectEqualStrings("-1=hi", s);
}
/// 类似 `print`,但返回切片带有所提供的哨兵值。
pub fn printSentinel(
buffer: []u8,
comptime format: []const u8,
args: anytype,
comptime sentinel: u8,
) PrintError![:sentinel]u8 {
const result = try print(buffer, format ++ [1]u8{sentinel}, args);
return result[0 .. result.len - 1 :sentinel];
}
test printSentinel {
const x: i32 = -1;
const y: []const u8 = "hi";
var buffer: [64]u8 = undefined;
const s = try printSentinel(&buffer, "{d}={s}", .{ x, y }, 0);
try testing.expectEqualStrings("-1=hi", s);
try testing.expectEqual(0, s[s.len]);
}