diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 278e917df6213af76dbd1131d7acc872416fbe30..a679291dba1bcae6e79286ad3b7b199562f68695 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -269,8 +269,10 @@ pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void { } } -/// Copy `source` into `dest`. Asserts no overlap. Asserts `dest.len` greater or equal to source len. Returns -/// number of elements copied. Sentinel is not copied. +/// 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]); @@ -284,6 +286,22 @@ test copySentinel { 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