membuiltinnative_endianstddebugassertmathtestingEndianAbsorbSentinelbyte_size_in_bitsAllocatorAlignmentValidationAllocatorvalidationWrapcopyForwardscopyBackwardscopySentinelcopySentinelInclusivezeroeszeroInitsortsortUnstablesortContextsortUnstableContextorderorderZboundedOrderZlessThanlessThanZuse_vectorsuse_vectors_for_comparisoneqleqlBytesindexOfDifffindDiffSpanspanSliceTosliceTolenSliceTolenindexOfSentinelfindSentinelallEqualtrimStarttrimEndtrimindexOfScalarfindScalarlastIndexOfScalarfindScalarLastindexOfScalarPosfindScalarPosindexOfAnyfindAnylastIndexOfAnyfindLastAnyindexOfAnyPosfindAnyPosindexOfNonefindNonelastIndexOfNonefindLastNoneindexOfNonePosfindNonePosindexOffindlastIndexOfLinearfindLastLinearindexOfPosLinearfindPosLinearboyerMooreHorspoolPreprocessReverseboyerMooreHorspoolPreprocesslastIndexOffindLastindexOfPosfindPoscountcountScalarcontainsAtLeastcontainsAtLeastScalarreadVarIntreadVarPackedIntreadIntreadPackedIntLittlereadPackedIntBigreadPackedIntwriteIntwritePackedIntLittlewritePackedIntBigwritePackedIntwriteVarPackedIntbyteSwapAllFieldsbyteSwapAllFieldsAlignedbyteSwapbyteSwapAlignedbyteSwapAllElementstokenizeAnytokenizeSequencetokenizeScalarsplitSequencesplitAnysplitScalarsplitBackwardsSequencesplitBackwardsAnysplitBackwardsScalarwindowWindowIteratorstartsWithendsWithcutPrefixcutSuffixcutcutLastcutScalarcutScalarLastDelimiterTypeTokenIteratorSplitIteratorSplitBackwardsIteratorjoinjoinZjoinMaybeZconcatconcatWithSentinelconcatMaybeSentinelmoreReadIntTestsminmaxminMaxindexOfMinfindMinindexOfMaxfindMaxindexOfMinMaxfindMinMaxswapreverseVectorreverseReverseIteratorreverseIteratorrotatereplacereplaceScalarcollapseRepeatsLencollapseRepeatstestCollapseRepeatsreplacementSizereplaceOwnedlittleToNativebigToNativetoNativenativeTonativeToLittlenativeToBigalignPointerOffsetalignPointercheckAlignCopyPtrAttrsAsBytesReturnTypeasBytestoBytesBytesAsValueReturnTypebytesAsValuebytesToValueBytesAsSliceReturnTypebytesAsSliceSliceAsBytesReturnTypesliceAsBytesdoTheTestabsorbSentinelalignForwardAnyAlignalignForwardalignForwardLog2doNotOptimizeAwayalignBackwardAnyAlignalignBackwardisValidAlignisValidAlignGenericisAlignedAnyAlignisAlignedLog2isAlignedisAlignedGenericAlignedSlicealignInBytesalignInSlicePrintErrorprintprintSentinel
std.mem.absorbSentinel
function
If the provided slice is not sentinel terminated, do nothing and return that slice. If it is sentinel-terminated, return a non-sentinel-terminated slice with the length increased by one to include the absorbed sentinel element.
pub fn absorbSentinel(slice: anytype) AbsorbSentinel(@TypeOf(slice))
Example usage
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
alias
Alias of std.meta.AbsorbSentinel
std.mem.alignBackward
function
Round an address down to the previous (or current) aligned address. The alignment must be a power of 2 and greater than 0.
pub fn alignBackward(comptime T: type, addr: T, alignment: T) T
Parameters
T: type
addr: T
alignment: T
std.mem.alignBackwardAnyAlign
function
Round an address down to the previous (or current) aligned address.
Unlike alignBackward, alignment can be any positive number, not just a power of 2.
pub fn alignBackwardAnyAlign(comptime T: type, addr: T, alignment: T) T
Parameters
T: type
addr: T
alignment: T
std.mem.AlignedSlice
type-function
Returns a slice with the given new alignment,
all other pointer attributes copied from AttributeSource.
fn AlignedSlice(comptime AttributeSource: type, comptime new_alignment: usize) type
Parameters
AttributeSource: type
new_alignment: usize
std.mem.alignForward
function
Round an address up to the next (or current) aligned address. The alignment must be a power of 2 and greater than 0. Asserts that rounding up the address does not cause integer overflow.
pub fn alignForward(comptime T: type, addr: T, alignment: T) T
Parameters
T: type
addr: T
alignment: T
Example usage
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
function
Round an address down to the next (or current) aligned address.
Unlike alignForward, alignment can be any positive number, not just a power of 2.
pub fn alignForwardAnyAlign(comptime T: type, addr: T, alignment: T) T
Parameters
T: type
addr: T
alignment: T
std.mem.alignForwardLog2
function
Rounds an address up to the next alignment boundary using log2 representation. Equivalent to alignForward with alignment = 1 << log2_alignment. More efficient when alignment is known to be a power of 2.
pub fn alignForwardLog2(addr: usize, log2_alignment: u8) usize
Parameters
addr: usize
log2_alignment: u8
std.mem.alignInBytes
function
Returns the largest slice in the given bytes that conforms to the new alignment,
or null if the given bytes contain no conforming address.
pub fn alignInBytes(bytes: []u8, comptime new_alignment: usize) ?[]align(new_alignment) u8
Parameters
bytes: []u8
new_alignment: usize
std.mem.alignInSlice
function
Returns the largest sub-slice within the given slice that conforms to the new alignment,
or null if the given slice contains no conforming address.
pub fn alignInSlice(slice: anytype, comptime new_alignment: usize) ?AlignedSlice(@TypeOf(slice), new_alignment)
Parameters
new_alignment: usize
std.mem.Alignment
container
Stored as a power-of-two.
Fields
@"1" = 0
@"2" = 1
@"4" = 2
@"8" = 3
@"16" = 4
@"32" = 5
@"64" = 6
_
std.mem.Alignment.backward
function
Return previous address with this alignment.
pub fn backward(a: Alignment, address: usize) usize
Parameters
a: Alignment
address: usize
std.mem.Alignment.check
function
Return whether address is aligned to this amount.
pub fn check(a: Alignment, address: usize) bool
Parameters
a: Alignment
address: usize
std.mem.Alignment.compare
function
pub fn compare(lhs: Alignment, op: std.math.CompareOperator, rhs: Alignment) bool
Parameters
std.mem.Alignment.forward
function
Return next address with this alignment.
pub fn forward(a: Alignment, address: usize) usize
Parameters
a: Alignment
address: usize
std.mem.Alignment.fromByteUnits
function
pub fn fromByteUnits(n: usize) Alignment
Parameters
n: usize
std.mem.Alignment.fromByteUnitsOptional
function
pub fn fromByteUnitsOptional(maybe_n: ?usize) ?Alignment
Parameters
maybe_n: ?usize
std.mem.Alignment.max
function
pub fn max(lhs: Alignment, rhs: Alignment) Alignment
Parameters
std.mem.Alignment.min
function
pub fn min(lhs: Alignment, rhs: Alignment) Alignment
Parameters
std.mem.Alignment.of
function
pub inline fn of(comptime T: type) Alignment
Parameters
T: type
std.mem.Alignment.order
function
pub fn order(lhs: Alignment, rhs: Alignment) std.math.Order
Parameters
std.mem.Alignment.toByteUnits
function
pub fn toByteUnits(a: Alignment) usize
Parameters
a: Alignment
std.mem.alignPointer
function
Aligns a given pointer value to a specified alignment factor. Returns an aligned pointer or null if one of the following conditions is met:
- The aligned pointer would not fit the address space,
- The delta required to align the pointer is not a multiple of the pointee's type.
pub fn alignPointer(ptr: anytype, align_to: usize) ?@TypeOf(ptr)
Parameters
align_to: usize
Example usage
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);
// Misaligned.
try S.checkAlign([*]align(1) u32, 0x3, 2, 0);
// Overflow.
try S.checkAlign([*]u32, math.maxInt(usize) - 3, 8, 0);
}
std.mem.alignPointerOffset
function
Returns the number of elements that, if added to the given pointer, align it
to a multiple of the given quantity, or null if one of the following
conditions is met:
- The aligned pointer would not fit the address space,
- The delta required to align the pointer is not a multiple of the pointee's type.
pub fn alignPointerOffset(ptr: anytype, align_to: usize) ?usize
Parameters
align_to: usize
std.mem.allEqual
function
Returns true if all elements in a slice are equal to the scalar value provided
pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool
Parameters
T: type
slice: []const T
scalar: T
std.mem.Allocator
alias
Alias of std.mem.Allocator
std.mem.asBytes
function
Given a pointer to a single item, returns a slice of the underlying bytes, preserving pointer attributes.
pub fn asBytes(ptr: anytype) AsBytesReturnType(@TypeOf(ptr))
Example usage
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
type-function
fn AsBytesReturnType(comptime P: type) type
Parameters
P: type
std.mem.assert
alias
Alias of std.debug.assert
std.mem.bigToNative
function
Converts a big-endian integer to host endianness.
pub fn bigToNative(comptime T: type, x: T) T
Parameters
T: type
x: T
std.mem.boundedOrderZ
function
Compares two many-item pointers with NUL-termination lexicographically until some specified bound.
pub fn boundedOrderZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T, bound: usize) math.Order
Parameters
T: type
lhs: [*:0]const T
rhs: [*:0]const T
bound: usize
std.mem.boyerMooreHorspoolPreprocess
function
fn boyerMooreHorspoolPreprocess(pattern: []const u8, table: *[256]usize) void
Parameters
pattern: []const u8
table: *[256]usize
std.mem.boyerMooreHorspoolPreprocessReverse
function
fn boyerMooreHorspoolPreprocessReverse(pattern: []const u8, table: *[256]usize) void
Parameters
pattern: []const u8
table: *[256]usize
std.mem.builtin
constant
std.mem.byte_size_in_bits
constant
The standard library currently thoroughly depends on byte size being 8 bits. (see the use of u8 throughout allocation code as the "byte" type.) Code which depends on this can reference this declaration. If we ever try to port the standard library to a non-8-bit-byte platform, this will allow us to search for things which need to be updated.
std.mem.bytesAsSlice
function
Given a slice of bytes, returns a slice of the specified type
backed by those bytes, preserving pointer attributes.
If T is zero-bytes sized, the returned slice has a len of zero.
pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T, @TypeOf(bytes))
Parameters
T: type
Example usage
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
type-function
fn BytesAsSliceReturnType(comptime T: type, comptime bytesType: type) type
Parameters
T: type
bytesType: type
std.mem.bytesAsValue
function
Given a pointer to an array of bytes, returns a pointer to a value of the specified type backed by those bytes, preserving pointer attributes.
pub fn bytesAsValue(comptime T: type, bytes: anytype) BytesAsValueReturnType(T, @TypeOf(bytes))
Parameters
T: type
Example usage
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
type-function
fn BytesAsValueReturnType(comptime T: type, comptime B: type) type
Parameters
T: type
B: type
std.mem.bytesToValue
function
Given a pointer to an array of bytes, returns a value of the specified type backed by a copy of those bytes.
pub fn bytesToValue(comptime T: type, bytes: anytype) T
Parameters
T: type
Example usage
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
function
Reverses the byte order. Handles structs, unions, arrays, enums, floats, and integers recursively. The order of extern struct fields and array elements remains unchanged and will be byte swapped recursively. Useful for converting between little-endian and big-endian representations.
pub fn byteSwap(comptime S: type, ptr: *S) void
Parameters
S: type
ptr: *S
Example usage
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
function
Reverses the byte order. Handles structs, unions, arrays, enums, floats, and integers recursively. The order of extern struct fields and array elements remains unchanged and will be byte swapped recursively. Useful for converting between little-endian and big-endian representations.
pub fn byteSwapAligned( comptime S: type, comptime a: Alignment, ptr: *align(a.toByteUnits()) S, ) void
Parameters
std.mem.byteSwapAllElements
function
Reverses the byte order of all elements in a slice. Handles structs, unions, arrays, enums, floats, and integers recursively. Useful for converting between little-endian and big-endian representations.
pub fn byteSwapAllElements(comptime Elem: type, slice: []Elem) void
Parameters
Elem: type
slice: []Elem
std.mem.byteSwapAllFields
alias
Deprecated: use byteSwap instead.
Alias of std.mem.byteSwap
std.mem.byteSwapAllFieldsAligned
alias
Deprecated: use byteSwapAligned instead.
Alias of std.mem.byteSwapAligned
std.mem.checkAlign
function
fn checkAlign(comptime T: type, base: usize, align_to: usize, expected: usize) !void
Parameters
T: type
base: usize
align_to: usize
expected: usize
std.mem.collapseRepeats
function
Collapse consecutive duplicate elements into one entry.
pub fn collapseRepeats(comptime T: type, slice: []T, elem: T) []T
Parameters
T: type
slice: []T
elem: T
Example usage
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
function
Collapse consecutive duplicate elements into one entry.
pub fn collapseRepeatsLen(comptime T: type, slice: []T, elem: T) usize
Parameters
T: type
slice: []T
elem: T
std.mem.concat
function
Copies each T from slices into a new slice that exactly holds all the elements.
pub fn concat(allocator: Allocator, comptime T: type, slices: []const []const T) Allocator.Error![]T
Parameters
Errors
- OutOfMemory
Example usage
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
function
Copies each T from slices into a new slice that exactly holds all the elements as well as the sentinel.
pub fn concatMaybeSentinel(allocator: Allocator, comptime T: type, slices: []const []const T, comptime s: ?T) Allocator.Error![]T
Parameters
Errors
- OutOfMemory
std.mem.concatWithSentinel
function
Copies each T from slices into a new slice that exactly holds all the elements.
pub fn concatWithSentinel(allocator: Allocator, comptime T: type, slices: []const []const T, comptime s: T) Allocator.Error![:s]T
Parameters
Errors
- OutOfMemory
std.mem.containsAtLeast
function
Returns true if the haystack contains expected_count or more needles
needle.len must be > 0
does not count overlapping needles
See also: containsAtLeastScalar
pub fn containsAtLeast(comptime T: type, haystack: []const T, expected_count: usize, needle: []const T) bool
Parameters
T: type
haystack: []const T
expected_count: usize
needle: []const T
Example usage
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
function
Returns true if element appears at least minimum number of times in list.
Related:
pub fn containsAtLeastScalar(comptime T: type, list: []const T, element: T, minimum: usize) bool
Parameters
T: type
list: []const T
element: T
minimum: usize
Example usage
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
function
Copy all of source into dest at position 0. dest.len must be >= source.len. If the slices overlap, dest.ptr must be >= src.ptr. This function is deprecated; use @memmove instead.
pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void
Parameters
T: type
dest: []T
source: []const T
std.mem.copyForwards
function
Copy all of source into dest at position 0. dest.len must be >= source.len. If the slices overlap, dest.ptr must be <= src.ptr. This function is deprecated; use @memmove instead.
pub fn copyForwards(comptime T: type, dest: []T, source: []const T) void
Parameters
T: type
dest: []T
source: []const T
std.mem.CopyPtrAttrs
type-function
fn CopyPtrAttrs( comptime source: type, comptime size: std.builtin.Type.Pointer.Size, comptime child: type, ) type
Parameters
std.mem.copySentinel
function
Copy source into dest, excluding the sentinel.
Asserts no overlap. Asserts dest.len greater or equal to source len. Returns number of elements copied,
not counting the sentinel.
pub fn copySentinel(comptime T: type, comptime s: T, dest: []T, source: [*:s]const T) usize
Parameters
T: type
s: T
dest: []T
source: [*:s]const T
Example usage
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
function
Copy source into dest, including the sentinel.
Asserts no overlap. Asserts dest.len greater or equal to source len, including room for the sentinel.
Returns number of elements copied, including the sentinel.
pub fn copySentinelInclusive(comptime T: type, comptime s: T, dest: []T, source: [*:s]const T) usize
Parameters
T: type
s: T
dest: []T
source: [*:s]const T
Example usage
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
function
Returns the number of needles inside the haystack needle.len must be > 0 does not count overlapping needles
pub fn count(comptime T: type, haystack: []const T, needle: []const T) usize
Parameters
T: type
haystack: []const T
needle: []const T
Example usage
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
function
Returns the number of times element appears in a slice of memory.
pub fn countScalar(comptime T: type, list: []const T, element: T) usize
Parameters
T: type
list: []const T
element: T
Example usage
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
function
Returns slice of haystack before and after first occurrence of needle,
or null if not found.
See also:
cutScalarsplittokenizeAny
pub fn cut(comptime T: type, haystack: []const T, needle: []const T) ?struct { []const T, []const T }
Parameters
T: type
haystack: []const T
needle: []const T
Example usage
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
function
Returns slice of haystack before and after last occurrence of needle,
or null if not found.
See also:
pub fn cutLast(comptime T: type, haystack: []const T, needle: []const T) ?struct { []const T, []const T }
Parameters
T: type
haystack: []const T
needle: []const T
Example usage
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
function
If slice starts with prefix, returns the rest of slice starting at prefix.len.
pub fn cutPrefix(comptime T: type, slice: []const T, prefix: []const T) ?[]const T
Parameters
T: type
slice: []const T
prefix: []const T
Example usage
test cutPrefix {
try testing.expectEqualStrings("foo", cutPrefix(u8, "--example=foo", "--example=").?);
try testing.expectEqual(null, cutPrefix(u8, "--example=foo", "-example="));
}
std.mem.cutScalar
function
Returns slice of haystack before and after first occurrence needle, or
null if not found.
See also:
pub fn cutScalar(comptime T: type, haystack: []const T, needle: T) ?struct { []const T, []const T }
Parameters
T: type
haystack: []const T
needle: T
Example usage
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
function
Returns slice of haystack before and after last occurrence of needle,
or null if not found.
See also:
pub fn cutScalarLast(comptime T: type, haystack: []const T, needle: T) ?struct { []const T, []const T }
Parameters
T: type
haystack: []const T
needle: T
Example usage
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
function
If slice ends with suffix, returns slice from beginning to start of suffix.
pub fn cutSuffix(comptime T: type, slice: []const T, suffix: []const T) ?[]const T
Parameters
T: type
slice: []const T
suffix: []const T
Example usage
test cutSuffix {
try testing.expectEqualStrings("foo", cutSuffix(u8, "foobar", "bar").?);
try testing.expectEqual(null, cutSuffix(u8, "foobar", "baz"));
}
std.mem.debug
alias
Alias of std.debug
std.mem.DelimiterType
container
Delimiter type for tokenization and splitting operations.
Fields
sequence
any
scalar
std.mem.doNotOptimizeAway
function
Force an evaluation of the expression; this tries to prevent the compiler from optimizing the computation away even if the result eventually gets discarded.
pub fn doNotOptimizeAway(val: anytype) void
Example usage
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
variable
*const anyopaque
std.mem.doTheTest
function
fn doTheTest() !void
std.mem.Endian
alias
Alias of std.lang.Endian
std.mem.endsWith
function
Returns true if haystack ends with needle. Time complexity: O(needle.len)
pub fn endsWith(comptime T: type, haystack: []const T, needle: []const T) bool
Parameters
T: type
haystack: []const T
needle: []const T
Example usage
test endsWith {
try testing.expect(endsWith(u8, "Needle in haystack", "haystack"));
try testing.expect(!endsWith(u8, "Bob", "Bo"));
}
std.mem.eql
function
Returns true if and only if the slices have the same length and all elements compare true using equality operator.
pub fn eql(comptime T: type, a: []const T, b: []const T) bool
Parameters
T: type
a: []const T
b: []const T
Example usage
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
function
std.mem.eql heavily optimized for slices of bytes.
fn eqlBytes(a: []const u8, b: []const u8) bool
Parameters
a: []const u8
b: []const u8
std.mem.eqlBytes.Chunk
constant
std.mem.eqlBytes.Chunk
type
std.mem.eqlBytes.isNotEqual
function
pub inline fn isNotEqual(chunk_a: Chunk, chunk_b: Chunk) bool
Parameters
std.mem.eqlBytes.isNotEqual
function
pub inline fn isNotEqual(chunk_a: Chunk, chunk_b: Chunk) bool
Parameters
std.mem.eqlBytes.size
constant
std.mem.eqlBytes.size
constant
std.mem.find
function
Search for needle in haystack and return the index of the first occurrence. Uses Boyer-Moore-Horspool algorithm on large inputs; linear search on small inputs. Returns null if needle is not found.
pub fn find(comptime T: type, haystack: []const T, needle: []const T) ?usize
Parameters
T: type
haystack: []const T
needle: []const T
Example usage
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
function
Linear search for the index of any value in the provided list inside a slice. Returns null if no values are found.
pub fn findAny(comptime T: type, slice: []const T, values: []const T) ?usize
Parameters
T: type
slice: []const T
values: []const T
std.mem.findAnyPos
function
Linear search for the index of any value in the provided list inside a slice, starting from a given position. Returns null if no values are found.
pub fn findAnyPos(comptime T: type, slice: []const T, start_index: usize, values: []const T) ?usize
Parameters
T: type
slice: []const T
start_index: usize
values: []const T
std.mem.findDiff
function
Compares two slices and returns the index of the first inequality. Returns null if the slices are equal.
pub fn findDiff(comptime T: type, a: []const T, b: []const T) ?usize
Parameters
T: type
a: []const T
b: []const T
Example usage
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
function
Find the index in a slice of a sub-slice, searching from the end backwards.
To start looking at a different index, slice the haystack first.
Uses the Reverse Boyer-Moore-Horspool algorithm on large inputs;
lastIndexOfLinear on small inputs.
pub fn findLast(comptime T: type, haystack: []const T, needle: []const T) ?usize
Parameters
T: type
haystack: []const T
needle: []const T
std.mem.findLastAny
function
Linear search for the last index of any value in the provided list inside a slice. Returns null if no values are found.
pub fn findLastAny(comptime T: type, slice: []const T, values: []const T) ?usize
Parameters
T: type
slice: []const T
values: []const T
std.mem.findLastLinear
function
Find the index in a slice of a sub-slice, searching from the end backwards.
To start looking at a different index, slice the haystack first.
Consider using lastIndexOf instead of this, which will automatically use a
more sophisticated algorithm on larger inputs.
pub fn findLastLinear(comptime T: type, haystack: []const T, needle: []const T) ?usize
Parameters
T: type
haystack: []const T
needle: []const T
std.mem.findLastNone
function
Find the last item in slice which is not contained in values.
Like strspn in the C standard library, but searches from the end.
pub fn findLastNone(comptime T: type, slice: []const T, values: []const T) ?usize
Parameters
T: type
slice: []const T
values: []const T
std.mem.findMax
function
Returns the index of the largest number in a slice. O(n).
slice must not be empty.
pub fn findMax(comptime T: type, slice: []const T) usize
Parameters
T: type
slice: []const T
Example usage
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
function
Returns the index of the smallest number in a slice. O(n).
slice must not be empty.
pub fn findMin(comptime T: type, slice: []const T) usize
Parameters
T: type
slice: []const T
Example usage
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
type-function
Finds the indices of the smallest and largest number in a slice. O(n).
Returns the indices of the smallest and largest numbers in that order.
slice must not be empty.
pub fn findMinMax(comptime T: type, slice: []const T) struct { usize, usize }
Parameters
T: type
slice: []const T
Example usage
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
function
Find the first item in slice which is not contained in values.
Comparable to strspn in the C standard library.
pub fn findNone(comptime T: type, slice: []const T, values: []const T) ?usize
Parameters
T: type
slice: []const T
values: []const T
Example usage
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
function
Find the first item in slice[start_index..] which is not contained in values.
The returned index will be relative to the start of slice, and never less than start_index.
Comparable to strspn in the C standard library.
pub fn findNonePos(comptime T: type, slice: []const T, start_index: usize, values: []const T) ?usize
Parameters
T: type
slice: []const T
start_index: usize
values: []const T
std.mem.findPos
function
Uses Boyer-Moore-Horspool algorithm on large inputs; findPosLinear on small inputs.
pub fn findPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize
Parameters
T: type
haystack: []const T
start_index: usize
needle: []const T
std.mem.findPosLinear
function
Consider using findPos instead of this, which will automatically use a
more sophisticated algorithm on larger inputs.
pub fn findPosLinear(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize
Parameters
T: type
haystack: []const T
start_index: usize
needle: []const T
Example usage
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
function
Linear search for the index of a scalar value inside a slice.
pub fn findScalar(comptime T: type, slice: []const T, value: T) ?usize
Parameters
T: type
slice: []const T
value: T
std.mem.findScalarLast
function
Linear search for the last index of a scalar value inside a slice.
pub fn findScalarLast(comptime T: type, slice: []const T, value: T) ?usize
Parameters
T: type
slice: []const T
value: T
std.mem.findScalarPos
function
Linear search for the index of a scalar value inside a slice, starting from a given position. Returns null if the value is not found.
pub fn findScalarPos(comptime T: type, slice: []const T, start_index: usize, value: T) ?usize
Parameters
T: type
slice: []const T
start_index: usize
value: T
Example usage
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
function
Returns the index of the sentinel value in a sentinel-terminated pointer. Linear search through memory until the sentinel is found.
pub fn findSentinel(comptime T: type, comptime sentinel: T, p: [*:sentinel]const T) usize
Parameters
T: type
sentinel: T
p: [*:sentinel]const T
std.mem.indexOf
alias
Deprecated in favor of find.
Alias of std.mem.find
std.mem.indexOfAny
alias
Deprecated in favor of findAny.
Alias of std.mem.findAny
std.mem.indexOfAnyPos
alias
Deprecated in favor of findAnyPos.
Alias of std.mem.findAnyPos
std.mem.indexOfDiff
alias
Deprecated in favor of findDiff.
Alias of std.mem.findDiff
std.mem.indexOfMax
alias
Alias of std.mem.findMax
std.mem.indexOfMin
alias
Deprecated in favor of findMin.
Alias of std.mem.findMin
std.mem.indexOfMinMax
alias
Deprecated in favor of findMinMax.
Alias of std.mem.findMinMax
std.mem.indexOfNone
alias
Deprecated in favor of findNone.
Alias of std.mem.findNone
std.mem.indexOfNonePos
alias
Alias of std.mem.findNonePos
std.mem.indexOfPos
alias
Deprecated in favor of findPos.
Alias of std.mem.findPos
std.mem.indexOfPosLinear
alias
Alias of std.mem.findPosLinear
std.mem.indexOfScalar
alias
Deprecated in favor of findScalar.
Alias of std.mem.findScalar
std.mem.indexOfScalarPos
alias
Deprecated in favor of findScalarPos.
Alias of std.mem.findScalarPos
std.mem.indexOfSentinel
alias
Deprecated in favor of findSentinel.
Alias of std.mem.findSentinel
std.mem.isAligned
function
Given an address and an alignment, return true if the address is a multiple of the alignment The alignment must be a power of 2 and greater than 0.
pub fn isAligned(addr: usize, alignment: usize) bool
Parameters
addr: usize
alignment: usize
Example usage
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
function
Returns true if i is aligned to the given alignment.
Works with any positive alignment value, not just powers of 2.
For power-of-2 alignments, isAligned is more efficient.
pub fn isAlignedAnyAlign(i: usize, alignment: usize) bool
Parameters
i: usize
alignment: usize
std.mem.isAlignedGeneric
function
Generic version of isAligned that works with any integer type.
Returns true if addr is aligned to the given alignment.
Alignment must be a power of 2 and greater than 0.
pub fn isAlignedGeneric(comptime T: type, addr: T, alignment: T) bool
Parameters
T: type
addr: T
alignment: T
std.mem.isAlignedLog2
function
Returns true if addr is aligned to 2^log2_alignment.
More efficient than isAligned when alignment is known to be a power of 2.
log2_alignment must be < @bitSizeOf(usize).
pub fn isAlignedLog2(addr: usize, log2_alignment: u8) bool
Parameters
addr: usize
log2_alignment: u8
std.mem.isValidAlign
function
Returns whether alignment is a valid alignment, meaning it is
a positive power of 2.
pub fn isValidAlign(alignment: usize) bool
Parameters
alignment: usize
std.mem.isValidAlignGeneric
function
Returns whether alignment is a valid alignment, meaning it is
a positive power of 2.
pub fn isValidAlignGeneric(comptime T: type, alignment: T) bool
Parameters
T: type
alignment: T
std.mem.join
function
Naively combines a series of slices with a separator. Allocates memory for the result, which must be freed by the caller.
pub fn join(allocator: Allocator, separator: []const u8, slices: []const []const u8) Allocator.Error![]u8
Parameters
Errors
- OutOfMemory
Example usage
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
function
fn joinMaybeZ(allocator: Allocator, separator: []const u8, slices: []const []const u8, zero: bool) Allocator.Error![]u8
Parameters
Errors
- OutOfMemory
std.mem.joinZ
function
Naively combines a series of slices with a separator and null terminator. Allocates memory for the result, which must be freed by the caller.
pub fn joinZ(allocator: Allocator, separator: []const u8, slices: []const []const u8) Allocator.Error![:0]u8
Parameters
Errors
- OutOfMemory
Example usage
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
alias
Deprecated in favor of find.
Alias of std.mem.findLast
std.mem.lastIndexOfAny
alias
Deprecated in favor of findLastAny.
Alias of std.mem.findLastAny
std.mem.lastIndexOfLinear
alias
Deprecated in favor of findLastLinear.
Alias of std.mem.findLastLinear
std.mem.lastIndexOfNone
alias
Deprecated in favor of findLastNone.
Alias of std.mem.findLastNone
std.mem.lastIndexOfScalar
alias
Deprecated in favor of findScalarLast.
Alias of std.mem.findScalarLast
std.mem.len
function
Takes a sentinel-terminated pointer and iterates over the memory to find the
sentinel and determine the length.
[*c] pointers are assumed to be non-null and 0-terminated.
pub fn len(value: anytype) usize
Example usage
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
function
Private helper for sliceTo(). If you want the length, use sliceTo(foo, x).len
fn lenSliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) usize
Parameters
Example usage
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
function
Returns true if lhs < rhs, false otherwise
pub fn lessThan(comptime T: type, lhs: []const T, rhs: []const T) bool
Parameters
T: type
lhs: []const T
rhs: []const T
Example usage
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
function
Returns true if lhs < rhs; false otherwise, operating on null-terminated arrays.
pub fn lessThanZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T) bool
Parameters
T: type
lhs: [*:0]const T
rhs: [*:0]const T
Example usage
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
function
Converts a little-endian integer to host endianness.
pub fn littleToNative(comptime T: type, x: T) T
Parameters
T: type
x: T
std.mem.math
alias
Alias of std.math
std.mem.max
function
Returns the largest number in a slice. O(n).
slice must not be empty.
pub fn max(comptime T: type, slice: []const T) T
Parameters
T: type
slice: []const T
Example usage
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
alias
Alias of std.mem
std.mem.min
function
Returns the smallest number in a slice. O(n).
slice must not be empty.
pub fn min(comptime T: type, slice: []const T) T
Parameters
T: type
slice: []const T
Example usage
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
type-function
Finds the smallest and largest number in a slice. O(n).
Returns an anonymous struct with the fields min and max.
slice must not be empty.
pub fn minMax(comptime T: type, slice: []const T) struct { T, T }
Parameters
T: type
slice: []const T
Example usage
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
function
fn moreReadIntTests() !void
std.mem.native_endian
constant
std.mem.nativeTo
function
Converts an integer which has host endianness to the desired endianness.
pub fn nativeTo(comptime T: type, x: T, desired_endianness: Endian) T
Parameters
std.mem.nativeToBig
function
Converts an integer which has host endianness to big endian.
pub fn nativeToBig(comptime T: type, x: T) T
Parameters
T: type
x: T
std.mem.nativeToLittle
function
Converts an integer which has host endianness to little endian.
pub fn nativeToLittle(comptime T: type, x: T) T
Parameters
T: type
x: T
std.mem.order
function
Compares two slices of numbers lexicographically. O(n).
pub fn order(comptime T: type, lhs: []const T, rhs: []const T) math.Order
Parameters
T: type
lhs: []const T
rhs: []const T
Example usage
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
function
Compares two many-item pointers with NUL-termination lexicographically.
pub fn orderZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T) math.Order
Parameters
T: type
lhs: [*:0]const T
rhs: [*:0]const T
Example usage
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
function
Render a formatted string into buffer. Returns a slice of buffer
starting at index 0 containing the result, or error.NoSpaceLeft if one or
more bytes were truncated.
See std.Io.Writer.print.
pub fn print(buffer: []u8, comptime format: []const u8, args: anytype) PrintError![]u8
Parameters
buffer: []u8
format: []const u8
Errors
- NoSpaceLeft
As much as possible was written to the buffer, but it was too small to fit all the printed bytes.
Example usage
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
error-set
Errors
- NoSpaceLeft
As much as possible was written to the buffer, but it was too small to fit all the printed bytes.
std.mem.printSentinel
function
Like print but returned slice has the provided sentinel.
pub fn printSentinel( buffer: []u8, comptime format: []const u8, args: anytype, comptime sentinel: u8, ) PrintError![:sentinel]u8
Parameters
buffer: []u8
format: []const u8
sentinel: u8
Errors
- NoSpaceLeft
As much as possible was written to the buffer, but it was too small to fit all the printed bytes.
Example usage
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
function
Reads an integer from memory with bit count specified by T. The bit count of T must be evenly divisible by 8. This function cannot fail and cannot cause undefined behavior.
pub inline fn readInt(comptime T: type, buffer: *const [@divExact(@typeInfo(T).int.bits, 8)]u8, endian: Endian) T
Parameters
Example usage
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
function
Loads an integer from packed memory. Asserts that buffer contains at least bit_offset + @bitSizeOf(T) bits.
pub fn readPackedInt(comptime T: type, bytes: []const u8, bit_offset: usize, endian: Endian) T
Parameters
Example usage
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
function
fn readPackedIntBig(comptime T: type, bytes: []const u8, bit_offset: usize) T
Parameters
T: type
bytes: []const u8
bit_offset: usize
std.mem.readPackedIntLittle
function
fn readPackedIntLittle(comptime T: type, bytes: []const u8, bit_offset: usize) T
Parameters
T: type
bytes: []const u8
bit_offset: usize
std.mem.readVarInt
function
Reads an integer from memory with size equal to bytes.len. ReturnType specifies the return type, which must be large enough to store the result.
pub fn readVarInt(comptime ReturnType: type, bytes: []const u8, endian: Endian) ReturnType
Parameters
Example usage
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);
// Return type can be oversized (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
function
Loads an integer from packed memory with provided bit_count, bit_offset, and signedness. Asserts that T is large enough to store the read value.
pub fn readVarPackedInt( comptime T: type, bytes: []const u8, bit_offset: usize, bit_count: usize, endian: std.builtin.Endian, signedness: std.builtin.Signedness, ) T
Parameters
T: type
bytes: []const u8
bit_offset: usize
bit_count: usize
endian: std.builtin.Endian
signedness: std.builtin.Signedness
Example usage
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
function
Replace needle with replacement as many times as possible, writing to an output buffer which is assumed to be of
appropriate size. Use replacementSize to calculate an appropriate buffer size.
The input and output slices must not overlap.
The needle must not be empty.
Returns the number of replacements made.
pub fn replace(comptime T: type, input: []const T, needle: []const T, replacement: []const T, output: []T) usize
Parameters
T: type
input: []const T
needle: []const T
replacement: []const T
output: []T
Example usage
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]);
// Empty needle is not allowed but input may be empty.
replacements = replace(u8, "", "x", "y", output[0..0]);
expected = "";
try testing.expect(replacements == 0);
try testing.expectEqualStrings(expected, output[0..expected.len]);
// Adjacent replacements.
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
function
Calculate the size needed in an output buffer to perform a replacement. The needle must not be empty.
pub fn replacementSize(comptime T: type, input: []const T, needle: []const T, replacement: []const T) usize
Parameters
T: type
input: []const T
needle: []const T
replacement: []const T
Example usage
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);
// Empty needle is not allowed but input may be empty.
try testing.expect(replacementSize(u8, "", "x", "y") == 0);
// Adjacent replacements.
try testing.expect(replacementSize(u8, "\\n\\n", "\\n", "\n") == 2);
try testing.expect(replacementSize(u8, "abbba", "b", "cd") == 8);
}
std.mem.replaceOwned
function
Perform a replacement on an allocated buffer of pre-determined size. Caller must free returned memory.
pub fn replaceOwned(comptime T: type, allocator: Allocator, input: []const T, needle: []const T, replacement: []const T) Allocator.Error![]T
Parameters
Errors
- OutOfMemory
Example usage
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
function
Replace all occurrences of match with replacement.
pub fn replaceScalar(comptime T: type, slice: []T, match: T, replacement: T) void
Parameters
T: type
slice: []T
match: T
replacement: T
std.mem.reverse
function
In-place order reversal of a slice
pub fn reverse(comptime T: type, items: []T) void
Parameters
T: type
items: []T
Example usage
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
function
Iterates over a slice in reverse.
pub fn reverseIterator(slice: anytype) ReverseIterator(@TypeOf(slice))
Example usage
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
type-function
Returned by reverseIterator.
pub fn ReverseIterator(comptime T: type) type
Parameters
T: type
Fields
ptr: Pointer
index: usize
std.mem.ReverseIterator.next
function
pub fn next(self: *@This()) ?Element
Parameters
self: *@This()
std.mem.ReverseIterator.nextPtr
function
pub fn nextPtr(self: *@This()) ?ElementPointer
Parameters
self: *@This()
std.mem.reverseVector
function
inline fn reverseVector(comptime N: usize, comptime T: type, a: []T) [N]T
Parameters
N: usize
T: type
a: []T
std.mem.rotate
function
In-place rotation of the values in an array ([0 1 2 3] becomes [1 2 3 0] if we rotate by 1) Assumes 0 <= amount <= items.len
pub fn rotate(comptime T: type, items: []T, amount: usize) void
Parameters
T: type
items: []T
amount: usize
Example usage
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
function
Given a slice, returns a slice of the underlying bytes, preserving pointer attributes.
pub fn sliceAsBytes(slice: anytype) SliceAsBytesReturnType(@TypeOf(slice))
Example usage
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
type-function
fn SliceAsBytesReturnType(comptime Slice: type) type
Parameters
Slice: type
std.mem.sliceTo
function
Takes a pointer to an array, a many-item pointer, or a slice, and returns a
slice of the items up to the first occurrence of end.
If end is not found, the resulting slice will include all items up to the
input's length or sentinel.
If the pointer type is unbounded (no length or sentinel), end will be the
sentinel for the resulting slice.
If the pointer type is sentinel-terminated by end, the resulting slice
will also be sentinel-terminated by end.
Pointer properties such as mutability and alignment are preserved.
C pointers are assumed to be non-null.
pub fn sliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) SliceTo(@TypeOf(ptr), end)
Parameters
Example usage
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
type-function
Helper for the return type of sliceTo()
fn SliceTo(comptime T: type, comptime end: std.meta.Elem(T)) type
Parameters
std.mem.sort
function
Sorts a slice in-place using a stable algorithm (maintains relative order of equal elements). Average time complexity: O(n log n), worst case: O(n log n) Space complexity: O(log n) for recursive calls
For slice of primitives with default ordering, consider using std.sort.block directly.
For unstable but potentially faster sorting, see sortUnstable.
pub fn sort( comptime T: type, items: []T, context: anytype, comptime lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool, ) void
Parameters
T: type
items: []T
lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool
std.mem.sortContext
function
TODO: currently this just calls insertionSortContext. The block sort implementation
in this file needs to be adapted to use the sort context.
pub fn sortContext(a: usize, b: usize, context: anytype) void
Parameters
a: usize
b: usize
std.mem.sortUnstable
function
Sorts a slice in-place using an unstable algorithm (does not preserve relative order of equal elements). Time complexity: O(n) best case, O(n log n) worst case and average case. Generally faster than stable sort but order of equal elements is undefined.
Uses pattern-defeating quicksort (PDQ) algorithm which performs well on many data patterns.
For stable sorting that preserves equal element order, use sort.
pub fn sortUnstable( comptime T: type, items: []T, context: anytype, comptime lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool, ) void
Parameters
T: type
items: []T
lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool
std.mem.sortUnstableContext
function
Sorts a range [a, b) using an unstable algorithm with custom context. This is a lower-level interface for sorting that works with indices instead of slices. Does not preserve relative order of equal elements.
The context must provide lessThan(a_idx, b_idx) and swap(a_idx, b_idx) methods. Uses pattern-defeating quicksort (PDQ) algorithm.
pub fn sortUnstableContext(a: usize, b: usize, context: anytype) void
Parameters
a: usize
b: usize
std.mem.span
function
Takes a sentinel-terminated pointer and returns a slice, iterating over the
memory to find the sentinel and determine the length.
Pointer attributes such as const are preserved.
[*c] pointers are assumed to be non-null and 0-terminated.
pub fn span(ptr: anytype) Span(@TypeOf(ptr))
Example usage
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
type-function
Takes a sentinel-terminated pointer and returns a slice preserving pointer attributes.
[*c] pointers are assumed to be 0-terminated and assumed to not be allowzero.
fn Span(comptime T: type) type
Parameters
T: type
Example usage
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
function
Returns an iterator that iterates over the slices of buffer that
are separated by any item in delimiters.
splitAny(u8, "abc,def||ghi", "|,") will return slices
for "abc", "def", "", "ghi", null, in that order.
If none of delimiters exist in buffer,
the iterator will return buffer, null, in that order.
See also: splitSequence, splitScalar, splitBackwardsSequence,
splitBackwardsAny,splitBackwardsScalar,
tokenizeAny, tokenizeSequence, and tokenizeScalar.
pub fn splitAny(comptime T: type, buffer: []const T, delimiters: []const T) SplitIterator(T, .any)
Parameters
T: type
buffer: []const T
delimiters: []const T
Example usage
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
function
Returns an iterator that iterates backwards over the slices of buffer that
are separated by any item in delimiters.
splitBackwardsAny(u8, "abc,def||ghi", "|,") will return slices
for "ghi", "", "def", "abc", null, in that order.
If none of delimiters exist in buffer,
the iterator will return buffer, null, in that order.
See also: splitBackwardsSequence, splitBackwardsScalar,
splitSequence, splitAny,splitScalar,
tokenizeAny, tokenizeSequence, and tokenizeScalar.
pub fn splitBackwardsAny(comptime T: type, buffer: []const T, delimiters: []const T) SplitBackwardsIterator(T, .any)
Parameters
T: type
buffer: []const T
delimiters: []const T
Example usage
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
type-function
Iterator type for splitting operations from the end backwards, including empty sequences.
pub fn SplitBackwardsIterator(comptime T: type, comptime delimiter_type: DelimiterType) type
Parameters
T: type
delimiter_type: DelimiterType
Fields
buffer: []const T
index: ?usize
delimiter: switch (delimiter_type) {
.sequence, .any => []const T,
.scalar => T,
}
std.mem.SplitBackwardsIterator.first
function
Returns a slice of the first field.
Call this only to get the first field and then use next to get all subsequent fields.
Asserts that iteration has not begun.
pub fn first(self: *Self) []const T
Parameters
self: *Self
std.mem.SplitBackwardsIterator.next
function
Returns a slice of the next field, or null if splitting is complete.
pub fn next(self: *Self) ?[]const T
Parameters
self: *Self
std.mem.SplitBackwardsIterator.reset
function
Resets the iterator to the initial slice.
pub fn reset(self: *Self) void
Parameters
self: *Self
std.mem.SplitBackwardsIterator.rest
function
Returns a slice of the remaining bytes. Does not affect iterator state.
pub fn rest(self: Self) []const T
Parameters
self: Self
std.mem.SplitBackwardsIterator.Self
alias
Alias of std.mem.SplitBackwardsIterator
std.mem.splitBackwardsScalar
function
Returns an iterator that iterates backwards over the slices of buffer that
are separated by delimiter.
splitBackwardsScalar(u8, "abc|def||ghi", '|') will return slices
for "ghi", "", "def", "abc", null, in that order.
If delimiter does not exist in buffer,
the iterator will return buffer, null, in that order.
See also: splitBackwardsSequence, splitBackwardsAny,
splitSequence, splitAny,splitScalar,
tokenizeAny, tokenizeSequence, and tokenizeScalar.
pub fn splitBackwardsScalar(comptime T: type, buffer: []const T, delimiter: T) SplitBackwardsIterator(T, .scalar)
Parameters
T: type
buffer: []const T
delimiter: T
Example usage
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
function
Returns an iterator that iterates backwards over the slices of buffer that
are separated by the sequence in delimiter.
splitBackwardsSequence(u8, "abc||def||||ghi", "||") will return slices
for "ghi", "", "def", "abc", null, in that order.
If delimiter does not exist in buffer,
the iterator will return buffer, null, in that order.
The delimiter length must not be zero.
See also: splitBackwardsAny, splitBackwardsScalar,
splitSequence, splitAny,splitScalar,
tokenizeAny, tokenizeSequence, and tokenizeScalar.
pub fn splitBackwardsSequence(comptime T: type, buffer: []const T, delimiter: []const T) SplitBackwardsIterator(T, .sequence)
Parameters
T: type
buffer: []const T
delimiter: []const T
Example usage
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
type-function
Iterator type for splitting operations, including empty sequences between delimiters.
pub fn SplitIterator(comptime T: type, comptime delimiter_type: DelimiterType) type
Parameters
T: type
delimiter_type: DelimiterType
Fields
buffer: []const T
index: ?usize
delimiter: switch (delimiter_type) {
.sequence, .any => []const T,
.scalar => T,
}
std.mem.SplitIterator.first
function
Returns a slice of the first field.
Call this only to get the first field and then use next to get all subsequent fields.
Asserts that iteration has not begun.
pub fn first(self: *Self) []const T
Parameters
self: *Self
std.mem.SplitIterator.next
function
Returns a slice of the next field, or null if splitting is complete.
pub fn next(self: *Self) ?[]const T
Parameters
self: *Self
std.mem.SplitIterator.peek
function
Returns a slice of the next field, or null if splitting is complete. This method does not alter self.index.
pub fn peek(self: *const Self) ?[]const T
Parameters
self: *const Self
std.mem.SplitIterator.reset
function
Resets the iterator to the initial slice.
pub fn reset(self: *Self) void
Parameters
self: *Self
std.mem.SplitIterator.rest
function
Returns a slice of the remaining bytes. Does not affect iterator state.
pub fn rest(self: Self) []const T
Parameters
self: Self
std.mem.SplitIterator.Self
alias
Alias of std.mem.SplitIterator
std.mem.splitScalar
function
Returns an iterator that iterates over the slices of buffer that
are separated by delimiter.
splitScalar(u8, "abc|def||ghi", '|') will return slices
for "abc", "def", "", "ghi", null, in that order.
If delimiter does not exist in buffer,
the iterator will return buffer, null, in that order.
See also: splitSequence, splitAny, splitBackwardsSequence,
splitBackwardsAny,splitBackwardsScalar,
tokenizeAny, tokenizeSequence, and tokenizeScalar.
pub fn splitScalar(comptime T: type, buffer: []const T, delimiter: T) SplitIterator(T, .scalar)
Parameters
T: type
buffer: []const T
delimiter: T
Example usage
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
function
Returns an iterator that iterates over the slices of buffer that
are separated by the byte sequence in delimiter.
splitSequence(u8, "abc||def||||ghi", "||") will return slices
for "abc", "def", "", "ghi", null, in that order.
If delimiter does not exist in buffer,
the iterator will return buffer, null, in that order.
The delimiter length must not be zero.
See also: splitAny, splitScalar, splitBackwardsSequence,
splitBackwardsAny,splitBackwardsScalar,
tokenizeAny, tokenizeSequence, and tokenizeScalar.
pub fn splitSequence(comptime T: type, buffer: []const T, delimiter: []const T) SplitIterator(T, .sequence)
Parameters
T: type
buffer: []const T
delimiter: []const T
Example usage
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
function
Returns true if haystack starts with needle. Time complexity: O(needle.len)
pub fn startsWith(comptime T: type, haystack: []const T, needle: []const T) bool
Parameters
T: type
haystack: []const T
needle: []const T
Example usage
test startsWith {
try testing.expect(startsWith(u8, "Bob", "Bo"));
try testing.expect(!startsWith(u8, "Needle in haystack", "haystack"));
}
std.mem.std
alias
Alias of std
std.mem.swap
function
Exchanges contents of two memory locations.
pub fn swap(comptime T: type, noalias a: *T, noalias b: *T) void
Parameters
T: type
a: *T
b: *T
std.mem.testCollapseRepeats
function
fn testCollapseRepeats(str: []const u8, elem: u8, expected: []const u8) !void
Parameters
str: []const u8
elem: u8
expected: []const u8
std.mem.testing
alias
Alias of std.testing
std.mem.toBytes
function
Given any value, returns a copy of its bytes in an array.
pub fn toBytes(value: anytype) [@sizeOf(@TypeOf(value))]u8
Example usage
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
type-function
Iterator type for tokenization operations, skipping empty sequences and delimiter sequences.
pub fn TokenIterator(comptime T: type, comptime delimiter_type: DelimiterType) type
Parameters
T: type
delimiter_type: DelimiterType
Fields
buffer: []const T
delimiter: switch (delimiter_type) {
.sequence, .any => []const T,
.scalar => T,
}
index: usize
std.mem.TokenIterator.isDelimiter
function
fn isDelimiter(self: Self, index: usize) bool
Parameters
self: Self
index: usize
std.mem.TokenIterator.next
function
Returns a slice of the current token, or null if tokenization is complete, and advances to the next token.
pub fn next(self: *Self) ?[]const T
Parameters
self: *Self
std.mem.TokenIterator.peek
function
Returns a slice of the current token, or null if tokenization is complete. Does not advance to the next token.
pub fn peek(self: *Self) ?[]const T
Parameters
self: *Self
std.mem.TokenIterator.reset
function
Resets the iterator to the initial token.
pub fn reset(self: *Self) void
Parameters
self: *Self
std.mem.TokenIterator.rest
function
Returns a slice of the remaining bytes. Does not affect iterator state.
pub fn rest(self: Self) []const T
Parameters
self: Self
std.mem.TokenIterator.Self
alias
Alias of std.mem.TokenIterator
std.mem.tokenizeAny
function
Returns an iterator that iterates over the slices of buffer that are not
any of the items in delimiters.
tokenizeAny(u8, " abc|def || ghi ", " |") will return slices
for "abc", "def", "ghi", null, in that order.
If buffer is empty, the iterator will return null.
If none of delimiters exist in buffer,
the iterator will return buffer, null, in that order.
See also: tokenizeSequence, tokenizeScalar,
splitSequence,splitAny, splitScalar,
splitBackwardsSequence, splitBackwardsAny, and splitBackwardsScalar
pub fn tokenizeAny(comptime T: type, buffer: []const T, delimiters: []const T) TokenIterator(T, .any)
Parameters
T: type
buffer: []const T
delimiters: []const T
Example usage
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
function
Returns an iterator that iterates over the slices of buffer that are not
delimiter.
tokenizeScalar(u8, " abc def ghi ", ' ') will return slices
for "abc", "def", "ghi", null, in that order.
If buffer is empty, the iterator will return null.
If delimiter does not exist in buffer,
the iterator will return buffer, null, in that order.
See also: tokenizeAny, tokenizeSequence,
splitSequence,splitAny, and splitScalar
splitBackwardsSequence, splitBackwardsAny, and splitBackwardsScalar
pub fn tokenizeScalar(comptime T: type, buffer: []const T, delimiter: T) TokenIterator(T, .scalar)
Parameters
T: type
buffer: []const T
delimiter: T
Example usage
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
function
Returns an iterator that iterates over the slices of buffer that are not
the sequence in delimiter.
tokenizeSequence(u8, "<>abc><def<><>ghi", "<>") will return slices
for "abc><def", "ghi", null, in that order.
If buffer is empty, the iterator will return null.
If delimiter does not exist in buffer,
the iterator will return buffer, null, in that order.
The delimiter length must not be zero.
See also: tokenizeAny, tokenizeScalar,
splitSequence,splitAny, and splitScalar
splitBackwardsSequence, splitBackwardsAny, and splitBackwardsScalar
pub fn tokenizeSequence(comptime T: type, buffer: []const T, delimiter: []const T) TokenIterator(T, .sequence)
Parameters
T: type
buffer: []const T
delimiter: []const T
Example usage
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
function
Converts an integer from specified endianness to host endianness.
pub fn toNative(comptime T: type, x: T, endianness_of_x: Endian) T
Parameters
std.mem.trim
function
Remove a set of values from the beginning and end of a slice.
pub fn trim(comptime T: type, slice: []const T, values_to_strip: []const T) []const T
Parameters
T: type
slice: []const T
values_to_strip: []const T
Example usage
test trim {
try testing.expectEqualSlices(u8, "foo", trim(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, "foo", trim(u8, "foo", " \n"));
}
std.mem.trimEnd
function
Remove a set of values from the end of a slice.
pub fn trimEnd(comptime T: type, slice: []const T, values_to_strip: []const T) []const T
Parameters
T: type
slice: []const T
values_to_strip: []const T
Example usage
test trimEnd {
try testing.expectEqualSlices(u8, " foo", trimEnd(u8, " foo\n ", " \n"));
}
std.mem.trimStart
function
Remove a set of values from the beginning of a slice.
pub fn trimStart(comptime T: type, slice: []const T, values_to_strip: []const T) []const T
Parameters
T: type
slice: []const T
values_to_strip: []const T
Example usage
test trimStart {
try testing.expectEqualSlices(u8, "foo\n ", trimStart(u8, " foo\n ", " \n"));
}
std.mem.use_vectors
constant
std.mem.use_vectors_for_comparison
constant
std.mem.ValidationAllocator
type-function
Detects and asserts if the std.mem.Allocator interface is violated by the caller or the allocator.
pub fn ValidationAllocator(comptime T: type) type
Parameters
T: type
Fields
underlying_allocator: T
std.mem.ValidationAllocator.alloc
function
pub fn alloc( ctx: *anyopaque, n: usize, alignment: mem.Alignment, ret_addr: usize, ) ?[*]u8
Parameters
std.mem.ValidationAllocator.allocator
function
pub fn allocator(self: *Self) Allocator
Parameters
self: *Self
std.mem.ValidationAllocator.free
function
pub fn free( ctx: *anyopaque, buf: []u8, alignment: Alignment, ret_addr: usize, ) void
Parameters
std.mem.ValidationAllocator.getUnderlyingAllocatorPtr
function
fn getUnderlyingAllocatorPtr(self: *Self) Allocator
Parameters
self: *Self
std.mem.ValidationAllocator.init
function
pub fn init(underlying_allocator: T) @This()
Parameters
underlying_allocator: T
std.mem.ValidationAllocator.remap
function
pub fn remap( ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ret_addr: usize, ) ?[*]u8
Parameters
std.mem.ValidationAllocator.reset
function
pub fn reset(self: *Self) void
Parameters
self: *Self
std.mem.ValidationAllocator.resize
function
pub fn resize( ctx: *anyopaque, buf: []u8, alignment: Alignment, new_len: usize, ret_addr: usize, ) bool
Parameters
std.mem.ValidationAllocator.Self
alias
Alias of std.mem.ValidationAllocator
std.mem.validationWrap
function
Wraps an allocator with basic validation checks. Asserts that allocation sizes are greater than zero and returned pointers have correct alignment.
pub fn validationWrap(allocator: anytype) ValidationAllocator(@TypeOf(allocator))
std.mem.window
function
Returns an iterator with a sliding window of slices for buffer.
The sliding window has length size and on every iteration moves
forward by advance.
Extract data for moving average with:
window(u8, "abcdefg", 3, 1) will return slices
"abc", "bcd", "cde", "def", "efg", null, in that order.
Chunk or split every N items with:
window(u8, "abcdefg", 3, 3) will return slices
"abc", "def", "g", null, in that order.
Pick every even index with:
window(u8, "abcdefg", 1, 2) will return slices
"a", "c", "e", "g" null, in that order.
The size and advance must be not be zero.
pub fn window(comptime T: type, buffer: []const T, size: usize, advance: usize) WindowIterator(T)
Parameters
T: type
buffer: []const T
size: usize
advance: usize
Example usage
test window {
{
// moving average size 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());
// multibyte
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);
}
{
// chunk/split every 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());
}
{
// pick even
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());
}
{
// empty
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());
}
{
// first
var it = window(u8, "abcdefg", 3, 3);
try testing.expectEqualSlices(u8, "abc", it.next().?);
it.reset();
try testing.expectEqualSlices(u8, "abc", it.next().?);
}
{
// reset
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 and 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());
}
{
// advance > size
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
type-function
Iterator type returned by the window function for sliding window operations.
pub fn WindowIterator(comptime T: type) type
Parameters
T: type
Fields
buffer: []const T
index: ?usize
size: usize
advance: usize
std.mem.WindowIterator.next
function
Returns a slice of the next window, or null if window is at end.
pub fn next(self: *Self) ?[]const T
Parameters
self: *Self
std.mem.WindowIterator.reset
function
Resets the iterator to the initial window.
pub fn reset(self: *Self) void
Parameters
self: *Self
std.mem.WindowIterator.Self
alias
Alias of std.mem.WindowIterator
std.mem.writeInt
function
Writes an integer to memory, storing it in twos-complement. This function always succeeds, has defined behavior for all inputs, but the integer bit width must be divisible by 8.
pub inline fn writeInt(comptime T: type, buffer: *[@divExact(@typeInfo(T).int.bits, 8)]u8, value: T, endian: Endian) void
Parameters
Example usage
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
function
Stores an integer to packed memory. Asserts that buffer contains at least bit_offset + @bitSizeOf(T) bits.
pub fn writePackedInt(comptime T: type, bytes: []u8, bit_offset: usize, value: T, endian: Endian) void
Parameters
Example usage
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
function
fn writePackedIntBig(comptime T: type, bytes: []u8, bit_offset: usize, value: T) void
Parameters
T: type
bytes: []u8
bit_offset: usize
value: T
std.mem.writePackedIntLittle
function
fn writePackedIntLittle(comptime T: type, bytes: []u8, bit_offset: usize, value: T) void
Parameters
T: type
bytes: []u8
bit_offset: usize
value: T
std.mem.writeVarPackedInt
function
Stores an integer to packed memory with provided bit_offset, bit_count, and signedness. If negative, the written value is sign-extended.
pub fn writeVarPackedInt(bytes: []u8, bit_offset: usize, bit_count: usize, value: anytype, endian: std.builtin.Endian) void
Parameters
Example usage
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
function
Generally, Zig users are encouraged to explicitly initialize all fields of a struct explicitly rather than using this function. However, it is recognized that there are sometimes use cases for initializing all fields to a "zero" value. For example, when interfacing with a C API where this practice is more common and relied upon. If you are performing code review and see this function used, examine closely - it may be a code smell. Zero initializes the type. This can be used to zero-initialize any type for which it makes sense. Structs will be initialized recursively.
pub fn zeroes(comptime T: type) T
Parameters
T: type
Example usage
test zeroes {
const C_struct = extern struct {
x: u32,
y: u32 align(128),
};
var a = zeroes(C_struct);
// Extern structs should have padding zeroed out.
{
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);
// Ensure zero sized struct with fields is initialized correctly.
_ = zeroes(struct { handle: void });
}
std.mem.zeroInit
function
Initializes all fields of the struct with their default value, or zero values if no default value is present. If the field is present in the provided initial values, it will have that value instead. Structs are initialized recursively.
pub fn zeroInit(comptime T: type, init: anytype) T
Parameters
T: type
Example usage
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);
}
Source code
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;
/// The standard library currently thoroughly depends on byte size
/// being 8 bits. (see the use of u8 throughout allocation code as
/// the "byte" type.) Code which depends on this can reference this
/// declaration. If we ever try to port the standard library to a
/// non-8-bit-byte platform, this will allow us to search for things
/// which need to be updated.
pub const byte_size_in_bits = 8;
pub const Allocator = @import("mem/Allocator.zig");
/// Stored as a power-of-two.
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))));
}
/// Return next address with this alignment.
pub fn forward(a: Alignment, address: usize) usize {
const x = (@as(usize, 1) << @backingInt(a)) - 1;
return (address + x) & ~x;
}
/// Return previous address with this alignment.
pub fn backward(a: Alignment, address: usize) usize {
const x = (@as(usize, 1) << @backingInt(a)) - 1;
return address & ~x;
}
/// Return whether address is aligned to this amount.
pub fn check(a: Alignment, address: usize) bool {
return @ctz(address) >= @backingInt(a);
}
};
/// Detects and asserts if the std.mem.Allocator interface is violated by the caller
/// or the 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();
}
};
}
/// Wraps an allocator with basic validation checks.
/// Asserts that allocation sizes are greater than zero and returned pointers have correct alignment.
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` is not guaranteed to succeed even if there is sufficient memory.
}
}
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` is not guaranteed to succeed even if there is sufficient memory.
}
}
}
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);
}
/// Copy all of source into dest at position 0.
/// dest.len must be >= source.len.
/// If the slices overlap, dest.ptr must be <= src.ptr.
/// This function is deprecated; use @memmove instead.
pub fn copyForwards(comptime T: type, dest: []T, source: []const T) void {
for (dest[0..source.len], source) |*d, s| d.* = s;
}
/// Copy all of source into dest at position 0.
/// dest.len must be >= source.len.
/// If the slices overlap, dest.ptr must be >= src.ptr.
/// This function is deprecated; use @memmove instead.
pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void {
// TODO instead of manually doing this check for the whole array
// and turning off runtime safety, the compiler should detect loops like
// this and automatically omit safety checks for loops
@setRuntimeSafety(false);
assert(dest.len >= source.len);
var i = source.len;
while (i > 0) {
i -= 1;
dest[i] = source[i];
}
}
/// Copy `source` into `dest`, excluding the sentinel.
///
/// Asserts no overlap. Asserts `dest.len` greater or equal to source len. Returns number of elements copied,
/// not counting the sentinel.
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);
}
/// Copy `source` into `dest`, including the sentinel.
///
/// Asserts no overlap. Asserts `dest.len` greater or equal to source len, including room for the sentinel.
/// Returns number of elements copied, including the sentinel.
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);
}
/// Generally, Zig users are encouraged to explicitly initialize all fields of a struct explicitly rather than using this function.
/// However, it is recognized that there are sometimes use cases for initializing all fields to a "zero" value. For example, when
/// interfacing with a C API where this practice is more common and relied upon. If you are performing code review and see this
/// function used, examine closely - it may be a code smell.
/// Zero initializes the type.
/// This can be used to zero-initialize any type for which it makes sense. Structs will be initialized recursively.
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 ""; // A special case for the most common use-case: null-terminated strings.
}
@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 structs should have padding zeroed out.
{
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);
// Ensure zero sized struct with fields is initialized correctly.
_ = zeroes(struct { handle: void });
}
/// Initializes all fields of the struct with their default value, or zero values if no default value is present.
/// If the field is present in the provided initial values, it will have that value instead.
/// Structs are initialized recursively.
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);
}
/// Sorts a slice in-place using a stable algorithm (maintains relative order of equal elements).
/// Average time complexity: O(n log n), worst case: O(n log n)
/// Space complexity: O(log n) for recursive calls
///
/// For slice of primitives with default ordering, consider using `std.sort.block` directly.
/// For unstable but potentially faster sorting, see `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);
}
/// Sorts a slice in-place using an unstable algorithm (does not preserve relative order of equal elements).
/// Time complexity: O(n) best case, O(n log n) worst case and average case.
/// Generally faster than stable sort but order of equal elements is undefined.
///
/// Uses pattern-defeating quicksort (PDQ) algorithm which performs well on many data patterns.
/// For stable sorting that preserves equal element order, use `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: currently this just calls `insertionSortContext`. The block sort implementation
/// in this file needs to be adapted to use the sort context.
pub fn sortContext(a: usize, b: usize, context: anytype) void {
std.sort.insertionContext(a, b, context);
}
/// Sorts a range [a, b) using an unstable algorithm with custom context.
/// This is a lower-level interface for sorting that works with indices instead of slices.
/// Does not preserve relative order of equal elements.
///
/// The context must provide lessThan(a_idx, b_idx) and swap(a_idx, b_idx) methods.
/// Uses pattern-defeating quicksort (PDQ) algorithm.
pub fn sortUnstableContext(a: usize, b: usize, context: anytype) void {
std.sort.pdqContext(a, b, context);
}
/// Compares two slices of numbers lexicographically. 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);
}
/// Compares two many-item pointers with NUL-termination lexicographically.
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));
}
/// Compares two many-item pointers with NUL-termination lexicographically until some specified bound.
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);
}
/// Returns true if lhs < rhs, false otherwise
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"));
}
/// Returns `true` if `lhs < rhs`; `false` otherwise, operating on null-terminated arrays.
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) {
// These backends don't support vectors yet.
.stage2_aarch64,
.stage2_loongarch,
.stage2_powerpc,
.stage2_riscv64,
=> false,
// The SPIR-V backend does not support the optimized path yet.
.stage2_spirv => false,
else => true,
};
// The naive memory comparison implementation is more useful for fuzzers to find interesting inputs.
const use_vectors_for_comparison = use_vectors and !builtin.fuzz;
/// Returns true if and only if the slices have the same length and all elements
/// compare true using equality operator.
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 heavily optimized for slices of bytes.
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;
}
// Figure out the fastest way to scan through the input in chunks.
// Uses vectors when supported and falls back to usize/words when not.
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);
}
}
// Compare inputs in chunks at a time (excluding the last chunk).
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;
}
// Compare the last chunk using an overlapping read (similar to the previous size strategies).
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);
}
/// Deprecated in favor of `findDiff`.
pub const indexOfDiff = findDiff;
/// Compares two slices and returns the index of the first inequality.
/// Returns null if the slices are equal.
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));
}
/// Takes a sentinel-terminated pointer and returns a slice preserving pointer attributes.
/// `[*c]` pointers are assumed to be 0-terminated and assumed to not be 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);
}
/// Takes a sentinel-terminated pointer and returns a slice, iterating over the
/// memory to find the sentinel and determine the length.
/// Pointer attributes such as const are preserved.
/// `[*c]` pointers are assumed to be non-null and 0-terminated.
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)));
}
/// Helper for the return type of 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));
}
/// Takes a pointer to an array, a many-item pointer, or a slice, and returns a
/// slice of the items up to the first occurrence of `end`.
/// If `end` is not found, the resulting slice will include all items up to the
/// input's length or sentinel.
/// If the pointer type is unbounded (no length or sentinel), `end` will be the
/// sentinel for the resulting slice.
/// If the pointer type is sentinel-terminated by `end`, the resulting slice
/// will also be sentinel-terminated by `end`.
/// Pointer properties such as mutability and alignment are preserved.
/// C pointers are assumed to be non-null.
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));
}
/// Private helper for sliceTo(). If you want the length, use 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);
}
// We're looking for something other than the sentinel,
// but iterating past the sentinel would be a bug so we need
// to check for both.
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));
}
}
/// Takes a sentinel-terminated pointer and iterates over the memory to find the
/// sentinel and determine the length.
/// `[*c]` pointers are assumed to be non-null and 0-terminated.
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);
}
/// Deprecated in favor of `findSentinel`.
pub const indexOfSentinel = findSentinel;
/// Returns the index of the sentinel value in a sentinel-terminated pointer.
/// Linear search through memory until the sentinel is found.
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;
// Allocate three pages so we guarantee a page-crossing address with a full page after
const memory = try allocator.alloc(T, 3 * page_size / @sizeOf(T));
defer allocator.free(memory);
@memset(memory, 0xaa);
// Find starting page-alignment = 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));
// Validate all sub-block alignments
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;
// Validate page boundary crossing
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])));
}
}
}
/// Returns true if all elements in a slice are equal to the scalar value provided
pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool {
for (slice) |item| {
if (item != scalar) return false;
}
return true;
}
/// Remove a set of values from the beginning of a slice.
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"));
}
/// Remove a set of values from the end of a slice.
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"));
}
/// Remove a set of values from the beginning and end of a slice.
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"));
}
/// Deprecated in favor of `findScalar`.
pub const indexOfScalar = findScalar;
/// Linear search for the index of a scalar value inside a slice.
pub fn findScalar(comptime T: type, slice: []const T, value: T) ?usize {
return findScalarPos(T, slice, 0, value);
}
/// Deprecated in favor of `findScalarLast`.
pub const lastIndexOfScalar = findScalarLast;
/// Linear search for the last index of a scalar value inside a slice.
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;
}
/// Deprecated in favor of `findScalarPos`.
pub const indexOfScalarPos = findScalarPos;
/// Linear search for the index of a scalar value inside a slice, starting from a given position.
/// Returns null if the value is not found.
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| {
// For Intel Nehalem (2009) and AMD Bulldozer (2012) or later, unaligned loads on aligned data result
// in the same execution as aligned loads. We ignore older arch's here and don't bother pre-aligning.
//
// Use `std.simd.suggestVectorLength(T)` to get the same alignment as used in this function
// however this usually isn't necessary unless your arch has a performance penalty due to this.
//
// This may differ for other arch's. Arm for example costs a cycle when loading across a cache
// line so explicit alignment prologues may be worth exploration.
// Unrolling here is ~10% improvement. We can then do one bounds check every 2 blocks
// instead of one which adds up.
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} check
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).?);
}
}
}
/// Deprecated in favor of `findAny`.
pub const indexOfAny = findAny;
/// Linear search for the index of any value in the provided list inside a slice.
/// Returns null if no values are found.
pub fn findAny(comptime T: type, slice: []const T, values: []const T) ?usize {
return findAnyPos(T, slice, 0, values);
}
/// Deprecated in favor of `findLastAny`.
pub const lastIndexOfAny = findLastAny;
/// Linear search for the last index of any value in the provided list inside a slice.
/// Returns null if no values are found.
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;
}
/// Deprecated in favor of `findAnyPos`.
pub const indexOfAnyPos = findAnyPos;
/// Linear search for the index of any value in the provided list inside a slice, starting from a given position.
/// Returns null if no values are found.
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;
}
/// Deprecated in favor of `findNone`.
pub const indexOfNone = findNone;
/// Find the first item in `slice` which is not contained in `values`.
///
/// Comparable to `strspn` in the C standard library.
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);
}
/// Deprecated in favor of `findLastNone`.
pub const lastIndexOfNone = findLastNone;
/// Find the last item in `slice` which is not contained in `values`.
///
/// Like `strspn` in the C standard library, but searches from the end.
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;
/// Find the first item in `slice[start_index..]` which is not contained in `values`.
/// The returned index will be relative to the start of `slice`, and never less than `start_index`.
///
/// Comparable to `strspn` in the C standard library.
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;
}
/// Deprecated in favor of `find`.
pub const indexOf = find;
/// Search for needle in haystack and return the index of the first occurrence.
/// Uses Boyer-Moore-Horspool algorithm on large inputs; linear search on small inputs.
/// Returns null if needle is not found.
pub fn find(comptime T: type, haystack: []const T, needle: []const T) ?usize {
return findPos(T, haystack, 0, needle);
}
/// Deprecated in favor of `findLastLinear`.
pub const lastIndexOfLinear = findLastLinear;
/// Find the index in a slice of a sub-slice, searching from the end backwards.
/// To start looking at a different index, slice the haystack first.
/// Consider using `lastIndexOf` instead of this, which will automatically use a
/// more sophisticated algorithm on larger inputs.
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;
/// Consider using `findPos` instead of this, which will automatically use a
/// more sophisticated algorithm on larger inputs.
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;
// The first item is intentionally ignored and the skip size will be pattern.len.
// This is the standard way Boyer-Moore-Horspool is implemented.
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;
// The last item is intentionally ignored and the skip size will be pattern.len.
// This is the standard way Boyer-Moore-Horspool is implemented.
while (i < pattern.len - 1) : (i += 1) {
table[pattern[i]] = pattern.len - 1 - i;
}
}
/// Deprecated in favor of `find`.
pub const lastIndexOf = findLast;
/// Find the index in a slice of a sub-slice, searching from the end backwards.
/// To start looking at a different index, slice the haystack first.
/// Uses the Reverse Boyer-Moore-Horspool algorithm on large inputs;
/// `lastIndexOfLinear` on small inputs.
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;
}
/// Deprecated in favor of `findPos`.
pub const indexOfPos = findPos;
/// Uses Boyer-Moore-Horspool algorithm on large inputs; `findPosLinear` on small inputs.
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 is significantly faster than 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" {
{
// make haystack and needle long enough to trigger Boyer-Moore-Horspool algorithm
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);
// check for misaligned false positives (little and big endian)
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);
}
{
// make haystack and needle long enough to trigger Boyer-Moore-Horspool algorithm
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);
// check for misaligned false positives (little and big endian)
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);
}
/// Returns the number of needles inside the haystack
/// needle.len must be > 0
/// does not count overlapping needles
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);
}
/// Returns the number of times `element` appears in a slice of memory.
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'));
}
/// Returns true if the haystack contains expected_count or more needles
/// needle.len must be > 0
/// does not count overlapping needles
//
/// See also: `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"));
}
/// Returns true if `element` appears at least `minimum` number of times in `list`.
//
/// Related:
/// * `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));
}
/// Reads an integer from memory with size equal to bytes.len.
/// ReturnType specifies the return type, which must be large enough to store
/// the result.
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);
// Return type can be oversized (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);
}
/// Loads an integer from packed memory with provided bit_count, bit_offset, and signedness.
/// Asserts that T is large enough to store the read value.
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) {
// These are the same shifts/masks we perform below, but adds `@truncate`/`@intCast`
// where needed since int is smaller than a byte.
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),
}
}
// Copy the value out (respecting endianness), accounting for 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);
}
/// Reads an integer from memory with bit count specified by T.
/// The bit count of T must be evenly divisible by 8.
/// This function cannot fail and cannot cause undefined behavior.
pub inline fn readInt(comptime T: type, buffer: *const [@divExact(@typeInfo(T).int.bits, 8)]u8, endian: Endian) T {
// Zig's logical bit order aligns with a little-endian byte array, so when reading in big-endian
// we must `@byteSwap` the int after we `@bitCast` to it.
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;
// Read by loading a LoadInt, and then follow it up with a 1-byte read
// of the tail if bit_offset pushed us over a byte boundary.
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;
// Read by loading a LoadInt, and then follow it up with a 1-byte read
// of the tail if bit_offset pushed us over a byte boundary.
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);
}
}
/// Loads an integer from packed memory.
/// Asserts that buffer contains at least bit_offset + @bitSizeOf(T) bits.
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);
}
}
/// Writes an integer to memory, storing it in twos-complement.
/// This function always succeeds, has defined behavior for all inputs, but
/// the integer bit width must be divisible by 8.
pub inline fn writeInt(comptime T: type, buffer: *[@divExact(@typeInfo(T).int.bits, 8)]u8, value: T, endian: Endian) void {
// Zig's logical bit order aligns with a little-endian byte array, so when writing in big-endian
// we must `@byteSwap` the int before we `@bitCast` to an array.
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;
// Write by storing a StoreInt, and then follow it up with a 1-byte tail
// if bit_offset pushed us over a byte boundary.
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;
// Write by storing a StoreInt, and then follow it up with a 1-byte tail
// if bit_offset pushed us over a byte boundary.
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);
}
/// Stores an integer to packed memory.
/// Asserts that buffer contains at least bit_offset + @bitSizeOf(T) bits.
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);
}
/// Stores an integer to packed memory with provided bit_offset, bit_count, and signedness.
/// If negative, the written value is sign-extended.
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) {
// Single byte writes are handled specially, since we need to mask bits
// on both ends of the byte.
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;
// Iterate bytes forward for Little-endian, backward for Big-endian
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 for signed index arithmetic
// Write first byte, using a mask to protects bits preceding 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;
// Write 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;
}
}
// Write last byte, using a mask to protect bits following 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);
}
/// Deprecated: use `byteSwap` instead.
pub const byteSwapAllFields = byteSwap;
/// Deprecated: use `byteSwapAligned` instead.
pub const byteSwapAllFieldsAligned = byteSwapAligned;
/// Reverses the byte order.
/// Handles structs, unions, arrays, enums, floats, and integers recursively.
/// The order of extern struct fields and array elements remains unchanged and
/// will be byte swapped recursively.
/// Useful for converting between little-endian and big-endian representations.
pub fn byteSwap(comptime S: type, ptr: *S) void {
byteSwapAligned(S, .of(S), ptr);
}
/// Reverses the byte order.
/// Handles structs, unions, arrays, enums, floats, and integers recursively.
/// The order of extern struct fields and array elements remains unchanged and
/// will be byte swapped recursively.
/// Useful for converting between little-endian and big-endian representations.
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);
}
/// Reverses the byte order of all elements in a slice.
/// Handles structs, unions, arrays, enums, floats, and integers recursively.
/// Useful for converting between little-endian and big-endian representations.
pub fn byteSwapAllElements(comptime Elem: type, slice: []Elem) void {
for (slice) |*elem| byteSwap(Elem, elem);
}
/// Returns an iterator that iterates over the slices of `buffer` that are not
/// any of the items in `delimiters`.
///
/// `tokenizeAny(u8, " abc|def || ghi ", " |")` will return slices
/// for "abc", "def", "ghi", null, in that order.
///
/// If `buffer` is empty, the iterator will return null.
/// If none of `delimiters` exist in buffer,
/// the iterator will return `buffer`, null, in that order.
///
/// See also: `tokenizeSequence`, `tokenizeScalar`,
/// `splitSequence`,`splitAny`, `splitScalar`,
/// `splitBackwardsSequence`, `splitBackwardsAny`, and `splitBackwardsScalar`
pub fn tokenizeAny(comptime T: type, buffer: []const T, delimiters: []const T) TokenIterator(T, .any) {
return .{
.index = 0,
.buffer = buffer,
.delimiter = delimiters,
};
}
/// Returns an iterator that iterates over the slices of `buffer` that are not
/// the sequence in `delimiter`.
///
/// `tokenizeSequence(u8, "<>abc><def<><>ghi", "<>")` will return slices
/// for "abc><def", "ghi", null, in that order.
///
/// If `buffer` is empty, the iterator will return null.
/// If `delimiter` does not exist in buffer,
/// the iterator will return `buffer`, null, in that order.
/// The delimiter length must not be zero.
///
/// See also: `tokenizeAny`, `tokenizeScalar`,
/// `splitSequence`,`splitAny`, and `splitScalar`
/// `splitBackwardsSequence`, `splitBackwardsAny`, and `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,
};
}
/// Returns an iterator that iterates over the slices of `buffer` that are not
/// `delimiter`.
///
/// `tokenizeScalar(u8, " abc def ghi ", ' ')` will return slices
/// for "abc", "def", "ghi", null, in that order.
///
/// If `buffer` is empty, the iterator will return null.
/// If `delimiter` does not exist in buffer,
/// the iterator will return `buffer`, null, in that order.
///
/// See also: `tokenizeAny`, `tokenizeSequence`,
/// `splitSequence`,`splitAny`, and `splitScalar`
/// `splitBackwardsSequence`, `splitBackwardsAny`, and `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);
}
}
/// Returns an iterator that iterates over the slices of `buffer` that
/// are separated by the byte sequence in `delimiter`.
///
/// `splitSequence(u8, "abc||def||||ghi", "||")` will return slices
/// for "abc", "def", "", "ghi", null, in that order.
///
/// If `delimiter` does not exist in buffer,
/// the iterator will return `buffer`, null, in that order.
/// The delimiter length must not be zero.
///
/// See also: `splitAny`, `splitScalar`, `splitBackwardsSequence`,
/// `splitBackwardsAny`,`splitBackwardsScalar`,
/// `tokenizeAny`, `tokenizeSequence`, and `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,
};
}
/// Returns an iterator that iterates over the slices of `buffer` that
/// are separated by any item in `delimiters`.
///
/// `splitAny(u8, "abc,def||ghi", "|,")` will return slices
/// for "abc", "def", "", "ghi", null, in that order.
///
/// If none of `delimiters` exist in buffer,
/// the iterator will return `buffer`, null, in that order.
///
/// See also: `splitSequence`, `splitScalar`, `splitBackwardsSequence`,
/// `splitBackwardsAny`,`splitBackwardsScalar`,
/// `tokenizeAny`, `tokenizeSequence`, and `tokenizeScalar`.
pub fn splitAny(comptime T: type, buffer: []const T, delimiters: []const T) SplitIterator(T, .any) {
return .{
.index = 0,
.buffer = buffer,
.delimiter = delimiters,
};
}
/// Returns an iterator that iterates over the slices of `buffer` that
/// are separated by `delimiter`.
///
/// `splitScalar(u8, "abc|def||ghi", '|')` will return slices
/// for "abc", "def", "", "ghi", null, in that order.
///
/// If `delimiter` does not exist in buffer,
/// the iterator will return `buffer`, null, in that order.
///
/// See also: `splitSequence`, `splitAny`, `splitBackwardsSequence`,
/// `splitBackwardsAny`,`splitBackwardsScalar`,
/// `tokenizeAny`, `tokenizeSequence`, and `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);
}
}
/// Returns an iterator that iterates backwards over the slices of `buffer` that
/// are separated by the sequence in `delimiter`.
///
/// `splitBackwardsSequence(u8, "abc||def||||ghi", "||")` will return slices
/// for "ghi", "", "def", "abc", null, in that order.
///
/// If `delimiter` does not exist in buffer,
/// the iterator will return `buffer`, null, in that order.
/// The delimiter length must not be zero.
///
/// See also: `splitBackwardsAny`, `splitBackwardsScalar`,
/// `splitSequence`, `splitAny`,`splitScalar`,
/// `tokenizeAny`, `tokenizeSequence`, and `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,
};
}
/// Returns an iterator that iterates backwards over the slices of `buffer` that
/// are separated by any item in `delimiters`.
///
/// `splitBackwardsAny(u8, "abc,def||ghi", "|,")` will return slices
/// for "ghi", "", "def", "abc", null, in that order.
///
/// If none of `delimiters` exist in buffer,
/// the iterator will return `buffer`, null, in that order.
///
/// See also: `splitBackwardsSequence`, `splitBackwardsScalar`,
/// `splitSequence`, `splitAny`,`splitScalar`,
/// `tokenizeAny`, `tokenizeSequence`, and `tokenizeScalar`.
pub fn splitBackwardsAny(comptime T: type, buffer: []const T, delimiters: []const T) SplitBackwardsIterator(T, .any) {
return .{
.index = buffer.len,
.buffer = buffer,
.delimiter = delimiters,
};
}
/// Returns an iterator that iterates backwards over the slices of `buffer` that
/// are separated by `delimiter`.
///
/// `splitBackwardsScalar(u8, "abc|def||ghi", '|')` will return slices
/// for "ghi", "", "def", "abc", null, in that order.
///
/// If `delimiter` does not exist in buffer,
/// the iterator will return `buffer`, null, in that order.
///
/// See also: `splitBackwardsSequence`, `splitBackwardsAny`,
/// `splitSequence`, `splitAny`,`splitScalar`,
/// `tokenizeAny`, `tokenizeSequence`, and `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);
}
}
/// Returns an iterator with a sliding window of slices for `buffer`.
/// The sliding window has length `size` and on every iteration moves
/// forward by `advance`.
///
/// Extract data for moving average with:
/// `window(u8, "abcdefg", 3, 1)` will return slices
/// "abc", "bcd", "cde", "def", "efg", null, in that order.
///
/// Chunk or split every N items with:
/// `window(u8, "abcdefg", 3, 3)` will return slices
/// "abc", "def", "g", null, in that order.
///
/// Pick every even index with:
/// `window(u8, "abcdefg", 1, 2)` will return slices
/// "a", "c", "e", "g" null, in that order.
///
/// The `size` and `advance` must be not be zero.
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 {
{
// moving average size 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());
// multibyte
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);
}
{
// chunk/split every 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());
}
{
// pick even
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());
}
{
// empty
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());
}
{
// first
var it = window(u8, "abcdefg", 3, 3);
try testing.expectEqualSlices(u8, "abc", it.next().?);
it.reset();
try testing.expectEqualSlices(u8, "abc", it.next().?);
}
{
// reset
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 and 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());
}
{
// advance > size
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());
}
}
/// Iterator type returned by the `window` function for sliding window operations.
pub fn WindowIterator(comptime T: type) type {
return struct {
buffer: []const T,
index: ?usize,
size: usize,
advance: usize,
const Self = @This();
/// Returns a slice of the next window, or null if window is at end.
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];
}
/// Resets the iterator to the initial window.
pub fn reset(self: *Self) void {
self.index = 0;
}
};
}
/// Returns true if haystack starts with needle.
/// Time complexity: 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"));
}
/// Returns true if haystack ends with needle.
/// Time complexity: 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"));
}
/// If `slice` starts with `prefix`, returns the rest of `slice` starting at `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="));
}
/// If `slice` ends with `suffix`, returns `slice` from beginning to start of `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"));
}
/// Returns slice of `haystack` before and after first occurrence of `needle`,
/// or `null` if not found.
///
/// See also:
/// * `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);
}
/// Returns slice of `haystack` before and after last occurrence of `needle`,
/// or `null` if not found.
///
/// See also:
/// * `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);
}
/// Returns slice of `haystack` before and after first occurrence `needle`, or
/// `null` if not found.
///
/// See also:
/// * `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);
}
/// Returns slice of `haystack` before and after last occurrence of `needle`,
/// or `null` if not found.
///
/// See also:
/// * `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);
}
/// Delimiter type for tokenization and splitting operations.
pub const DelimiterType = enum { sequence, any, scalar };
/// Iterator type for tokenization operations, skipping empty sequences and delimiter sequences.
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();
/// Returns a slice of the current token, or null if tokenization is
/// complete, and advances to the next token.
pub fn next(self: *Self) ?[]const T {
const result = self.peek() orelse return null;
self.index += result.len;
return result;
}
/// Returns a slice of the current token, or null if tokenization is
/// complete. Does not advance to the next token.
pub fn peek(self: *Self) ?[]const T {
// move to beginning of token
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;
}
// move to end of token
var end = start;
while (end < self.buffer.len and !self.isDelimiter(end)) : (end += 1) {}
return self.buffer[start..end];
}
/// Returns a slice of the remaining bytes. Does not affect iterator state.
pub fn rest(self: Self) []const T {
// move to beginning of token
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..];
}
/// Resets the iterator to the initial token.
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,
}
}
};
}
/// Iterator type for splitting operations, including empty sequences between delimiters.
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();
/// Returns a slice of the first field.
/// Call this only to get the first field and then use `next` to get all subsequent fields.
/// Asserts that iteration has not begun.
pub fn first(self: *Self) []const T {
assert(self.index.? == 0);
return self.next().?;
}
/// Returns a slice of the next field, or null if splitting is complete.
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];
}
/// Returns a slice of the next field, or null if splitting is complete.
/// This method does not alter 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];
}
/// Returns a slice of the remaining bytes. Does not affect iterator state.
pub fn rest(self: Self) []const T {
const end = self.buffer.len;
const start = self.index orelse end;
return self.buffer[start..end];
}
/// Resets the iterator to the initial slice.
pub fn reset(self: *Self) void {
self.index = 0;
}
};
}
/// Iterator type for splitting operations from the end backwards, including empty sequences.
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();
/// Returns a slice of the first field.
/// Call this only to get the first field and then use `next` to get all subsequent fields.
/// Asserts that iteration has not begun.
pub fn first(self: *Self) []const T {
assert(self.index.? == self.buffer.len);
return self.next().?;
}
/// Returns a slice of the next field, or null if splitting is complete.
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];
}
/// Returns a slice of the remaining bytes. Does not affect iterator state.
pub fn rest(self: Self) []const T {
const end = self.index orelse 0;
return self.buffer[0..end];
}
/// Resets the iterator to the initial slice.
pub fn reset(self: *Self) void {
self.index = self.buffer.len;
}
};
}
/// Naively combines a series of slices with a separator.
/// Allocates memory for the result, which must be freed by the caller.
pub fn join(allocator: Allocator, separator: []const u8, slices: []const []const u8) Allocator.Error![]u8 {
return joinMaybeZ(allocator, separator, slices, false);
}
/// Naively combines a series of slices with a separator and null terminator.
/// Allocates memory for the result, which must be freed by the caller.
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;
// No need for shrink since buf is exactly the correct size.
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);
}
}
/// Copies each T from slices into a new slice that exactly holds all the elements.
pub fn concat(allocator: Allocator, comptime T: type, slices: []const []const T) Allocator.Error![]T {
return concatMaybeSentinel(allocator, T, slices, null);
}
/// Copies each T from slices into a new slice that exactly holds all the elements.
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];
}
/// Copies each T from slices into a new slice that exactly holds all the elements as well as the sentinel.
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;
}
// No need for shrink since buf is exactly the correct size.
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);
}
}
/// Returns the smallest number in a slice. O(n).
/// `slice` must not be empty.
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');
}
/// Returns the largest number in a slice. O(n).
/// `slice` must not be empty.
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');
}
/// Finds the smallest and largest number in a slice. O(n).
/// Returns an anonymous struct with the fields `min` and `max`.
/// `slice` must not be empty.
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);
}
}
/// Deprecated in favor of `findMin`.
pub const indexOfMin = findMin;
/// Returns the index of the smallest number in a slice. O(n).
/// `slice` must not be empty.
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;
/// Returns the index of the largest number in a slice. O(n).
/// `slice` must not be empty.
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);
}
/// Deprecated in favor of `findMinMax`.
pub const indexOfMinMax = findMinMax;
/// Finds the indices of the smallest and largest number in a slice. O(n).
/// Returns the indices of the smallest and largest numbers in that order.
/// `slice` must not be empty.
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"));
}
/// Exchanges contents of two memory locations.
pub fn swap(comptime T: type, noalias a: *T, noalias b: *T) void {
if (@inComptime()) {
// In comptime, accessing bytes of values with no defined layout is a compile error.
const tmp = a.*;
a.* = b.*;
b.* = tmp;
} else {
// Swapping in streaming nature from start to end instead of swapping
// everything in one step allows easier optimizations and less stack usage.
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;
}
/// In-place order reversal of a slice
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 } } }));
}
}
/// Returned by `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];
}
};
}
/// Iterates over a slice in reverse.
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);
}
}
/// In-place rotation of the values in an array ([0 1 2 3] becomes [1 2 3 0] if we rotate by 1)
/// Assumes 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 }));
}
/// Replace needle with replacement as many times as possible, writing to an output buffer which is assumed to be of
/// appropriate size. Use replacementSize to calculate an appropriate buffer size.
/// The `input` and `output` slices must not overlap.
/// The needle must not be empty.
/// Returns the number of replacements made.
pub fn replace(comptime T: type, input: []const T, needle: []const T, replacement: []const T, output: []T) usize {
// Empty needle will loop until output buffer overflows.
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]);
// Empty needle is not allowed but input may be empty.
replacements = replace(u8, "", "x", "y", output[0..0]);
expected = "";
try testing.expect(replacements == 0);
try testing.expectEqualStrings(expected, output[0..expected.len]);
// Adjacent replacements.
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]);
}
/// Replace all occurrences of `match` with `replacement`.
pub fn replaceScalar(comptime T: type, slice: []T, match: T, replacement: T) void {
for (slice) |*e| {
if (e.* == match)
e.* = replacement;
}
}
/// Collapse consecutive duplicate elements into one entry.
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;
}
/// Collapse consecutive duplicate elements into one entry.
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/");
}
/// Calculate the size needed in an output buffer to perform a replacement.
/// The needle must not be empty.
pub fn replacementSize(comptime T: type, input: []const T, needle: []const T, replacement: []const T) usize {
// Empty needle will loop forever.
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);
// Empty needle is not allowed but input may be empty.
try testing.expect(replacementSize(u8, "", "x", "y") == 0);
// Adjacent replacements.
try testing.expect(replacementSize(u8, "\\n\\n", "\\n", "\n") == 2);
try testing.expect(replacementSize(u8, "abbba", "b", "cd") == 8);
}
/// Perform a replacement on an allocated buffer of pre-determined size. Caller must free returned memory.
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."));
}
/// Converts a little-endian integer to host endianness.
pub fn littleToNative(comptime T: type, x: T) T {
return switch (native_endian) {
.little => x,
.big => @byteSwap(x),
};
}
/// Converts a big-endian integer to host endianness.
pub fn bigToNative(comptime T: type, x: T) T {
return switch (native_endian) {
.little => @byteSwap(x),
.big => x,
};
}
/// Converts an integer from specified endianness to host endianness.
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),
};
}
/// Converts an integer which has host endianness to the desired endianness.
pub fn nativeTo(comptime T: type, x: T, desired_endianness: Endian) T {
return switch (desired_endianness) {
.little => nativeToLittle(T, x),
.big => nativeToBig(T, x),
};
}
/// Converts an integer which has host endianness to little endian.
pub fn nativeToLittle(comptime T: type, x: T) T {
return switch (native_endian) {
.little => x,
.big => @byteSwap(x),
};
}
/// Converts an integer which has host endianness to big endian.
pub fn nativeToBig(comptime T: type, x: T) T {
return switch (native_endian) {
.little => @byteSwap(x),
.big => x,
};
}
/// Returns the number of elements that, if added to the given pointer, align it
/// to a multiple of the given quantity, or `null` if one of the following
/// conditions is met:
/// - The aligned pointer would not fit the address space,
/// - The delta required to align the pointer is not a multiple of the pointee's
/// type.
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));
// Do nothing if the pointer is already well-aligned.
if (align_to <= info.pointer.attrs.@"align" orelse @alignOf(info.pointer.child))
return 0;
// Calculate the aligned base address with an eye out for overflow.
const addr = @intFromPtr(ptr);
var ov = @addWithOverflow(addr, align_to - 1);
if (ov[1] != 0) return null;
ov[0] &= ~@as(usize, align_to - 1);
// The delta is expressed in terms of bytes, turn it into a number of child
// type elements.
const delta = ov[0] - addr;
const pointee_size = @sizeOf(info.pointer.child);
if (delta % pointee_size != 0) return null;
return delta / pointee_size;
}
/// Aligns a given pointer value to a specified alignment factor.
/// Returns an aligned pointer or null if one of the following conditions is
/// met:
/// - The aligned pointer would not fit the address space,
/// - The delta required to align the pointer is not a multiple of the pointee's
/// type.
pub fn alignPointer(ptr: anytype, align_to: usize) ?@TypeOf(ptr) {
const adjust_off = alignPointerOffset(ptr, align_to) orelse return null;
// Avoid the use of ptrFromInt to avoid losing the pointer provenance info.
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);
// Misaligned.
try S.checkAlign([*]align(1) u32, 0x3, 2, 0);
// Overflow.
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);
}
/// Given a pointer to a single item, returns a slice of the underlying bytes, preserving pointer attributes.
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");
}
/// Given any value, returns a copy of its bytes in an array.
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);
}
/// Given a pointer to an array of bytes, returns a pointer to a value of the specified type
/// backed by those bytes, preserving pointer attributes.
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");
}
/// Given a pointer to an array of bytes, returns a value of the specified type backed by a
/// copy of those bytes.
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);
}
/// Given a slice of bytes, returns a slice of the specified type
/// backed by those bytes, preserving pointer attributes.
/// If `T` is zero-bytes sized, the returned slice has a len of zero.
pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T, @TypeOf(bytes)) {
// let's not give an undefined pointer to @ptrCast
// it may be equal to zero and fail a null check
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);
}
/// Given a slice, returns a slice of the underlying bytes, preserving pointer attributes.
pub fn sliceAsBytes(slice: anytype) SliceAsBytesReturnType(@TypeOf(slice)) {
const Slice = @TypeOf(slice);
// a slice of zero-bit values always occupies zero bytes
if (@sizeOf(std.meta.Elem(Slice)) == 0) return &[0]u8{};
// let's not give an undefined pointer to @ptrCast
// it may be equal to zero and fail a null check
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");
}
/// If the provided slice is not sentinel terminated, do nothing and return that slice.
/// If it is sentinel-terminated, return a non-sentinel-terminated slice with the
/// length increased by one to include the absorbed sentinel element.
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));
}
}
/// Round an address down to the next (or current) aligned address.
/// Unlike `alignForward`, `alignment` can be any positive number, not just a power of 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);
}
/// Round an address up to the next (or current) aligned address.
/// The alignment must be a power of 2 and greater than 0.
/// Asserts that rounding up the address does not cause integer overflow.
pub fn alignForward(comptime T: type, addr: T, alignment: T) T {
assert(isValidAlignGeneric(T, alignment));
return alignBackward(T, addr + (alignment - 1), alignment);
}
/// Rounds an address up to the next alignment boundary using log2 representation.
/// Equivalent to alignForward with alignment = 1 << log2_alignment.
/// More efficient when alignment is known to be a power of 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);
}
/// Force an evaluation of the expression; this tries to prevent
/// the compiler from optimizing the computation away even if the
/// result eventually gets discarded.
// TODO: use @declareSideEffect() when it is available - 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 targets do not have registers per se, they have values
// tied to IDs that can be passed to valid instructions. Some
// SPIR-V targets do not define c_long, so we just allow any sized
// integer on these targets
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);
}
/// Round an address down to the previous (or current) aligned address.
/// Unlike `alignBackward`, `alignment` can be any positive number, not just a power of 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);
}
/// Round an address down to the previous (or current) aligned address.
/// The alignment must be a power of 2 and greater than 0.
pub fn alignBackward(comptime T: type, addr: T, alignment: T) T {
assert(isValidAlignGeneric(T, alignment));
// 000010000 // example alignment
// 000001111 // subtract 1
// 111110000 // binary not
return addr & ~(alignment - 1);
}
/// Returns whether `alignment` is a valid alignment, meaning it is
/// a positive power of 2.
pub fn isValidAlign(alignment: usize) bool {
return isValidAlignGeneric(usize, alignment);
}
/// Returns whether `alignment` is a valid alignment, meaning it is
/// a positive power of 2.
pub fn isValidAlignGeneric(comptime T: type, alignment: T) bool {
return alignment > 0 and std.math.isPowerOfTwo(alignment);
}
/// Returns true if i is aligned to the given alignment.
/// Works with any positive alignment value, not just powers of 2.
/// For power-of-2 alignments, `isAligned` is more efficient.
pub fn isAlignedAnyAlign(i: usize, alignment: usize) bool {
if (isValidAlign(alignment))
return isAligned(i, alignment);
assert(alignment != 0);
return 0 == @mod(i, alignment);
}
/// Returns true if addr is aligned to 2^log2_alignment.
/// More efficient than `isAligned` when alignment is known to be a power of 2.
/// log2_alignment must be < @bitSizeOf(usize).
pub fn isAlignedLog2(addr: usize, log2_alignment: u8) bool {
return @ctz(addr) >= log2_alignment;
}
/// Given an address and an alignment, return true if the address is a multiple of the alignment
/// The alignment must be a power of 2 and greater than 0.
pub fn isAligned(addr: usize, alignment: usize) bool {
return isAlignedGeneric(u64, addr, alignment);
}
/// Generic version of `isAligned` that works with any integer type.
/// Returns true if addr is aligned to the given alignment.
/// Alignment must be a power of 2 and greater than 0.
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);
}
/// Returns a slice with the given new alignment,
/// all other pointer attributes copied from `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);
}
/// Returns the largest slice in the given bytes that conforms to the new alignment,
/// or `null` if the given bytes contain no conforming address.
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]);
}
/// Returns the largest sub-slice within the given slice that conforms to the new alignment,
/// or `null` if the given slice contains no conforming address.
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" {
// This test generates too much code to execute on WASI.
// LLVM backend fails with "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), // all zeros
-%@as(BackingType, 1), // all ones
random.int(BackingType), // random
random.int(BackingType), // random
random.int(BackingType), // random
}) |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), // all ones: -1 iN / maxInt uN
@as(PackedType, 0), // all zeros: 0 iN / 0 uN
@bitCast(@as(iPackedType, math.maxInt(iPackedType))), // maxInt iN
@bitCast(@as(iPackedType, math.minInt(iPackedType))), // maxInt iN
random.int(PackedType), // random
random.int(PackedType), // random
}) |write_value| {
{ // Fixed-size Read/Write (Native-endian)
// Initialize Value
var value: BackingType = init_value;
// Read
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)))))));
// Write
writePackedInt(PackedType, asBytes(&value), offset, write_value, native_endian);
try expect(write_value == @as(PackedType, @bitCast(@as(uPackedType, @truncate(value >> @as(Log2T, @intCast(offset)))))));
// Read again
const read_value2 = readPackedInt(PackedType, asBytes(&value), offset, native_endian);
try expect(read_value2 == write_value);
// Verify bits outside of the target integer are unmodified
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);
}
{ // Fixed-size Read/Write (Foreign-endian)
// Initialize Value
var value: BackingType = @byteSwap(init_value);
// Read
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)))))));
// Write
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)))))));
// Read again
const read_value2 = readPackedInt(PackedType, asBytes(&value), offset, foreign_endian);
try expect(read_value2 == write_value);
// Verify bits outside of the target integer are unmodified
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| {
{ // Variable-size Read/Write (Native-endian)
if (@bitSizeOf(U) < @bitSizeOf(PackedType))
continue;
// Initialize Value
var value: BackingType = init_value;
// Read
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)))))));
// Write
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)))))));
// Read again
const read_value2 = readVarPackedInt(U, asBytes(&value), offset, @bitSizeOf(PackedType), native_endian, signedness);
try expect(read_value2 == write_value);
// Verify bits outside of the target integer are unmodified
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);
}
{ // Variable-size Read/Write (Foreign-endian)
if (@bitSizeOf(U) < @bitSizeOf(PackedType))
continue;
// Initialize Value
var value: BackingType = @byteSwap(init_value);
// Read
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)))))));
// Write
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)))))));
// Read again
const read_value2 = readVarPackedInt(U, asBytes(&value), offset, @bitSizeOf(PackedType), foreign_endian, signedness);
try expect(read_value2 == write_value);
// Verify bits outside of the target integer are unmodified
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{
/// As much as possible was written to the buffer, but it was too small to
/// fit all the printed bytes.
NoSpaceLeft,
};
/// Render a formatted string into `buffer`. Returns a slice of `buffer`
/// starting at index 0 containing the result, or `error.NoSpaceLeft` if one or
/// more bytes were truncated.
///
/// See `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);
}
/// Like `print` but returned slice has the provided sentinel.
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]);
}