From b3d23464d066a10e902b75349e99752f2a235e66 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 7 Sep 2026 16:15:33 -0700 Subject: [PATCH] std.mem: introduce copySentinel for when source memory region is sentinel-terminated and length is not yet known. --- lib/std/mem.zig | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index d8b3872eb0be27f79fa66b3805f7cb567e57be10..24daa4a508f6fde819c5d558a5e3dd81f685c3b1 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -269,6 +269,21 @@ 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. +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); +} + /// 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 -- 2.54.0