diff --git a/lib/std/mem.zig b/lib/std/mem.zig index d8b3872eb0be27f79fa66b3805f7cb567e57be10..a679291dba1bcae6e79286ad3b7b199562f68695 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -269,6 +269,39 @@ pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void { } } +/// 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 @@ -733,6 +766,19 @@ test lessThan { 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,