authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-09-07 16:15:33-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-09-07 16:44:06-07:00
logb3d23464d066a10e902b75349e99752f2a235e66
treead2d6bf742deff19498a784e297a47e1e3285eed
parent5e36170b5ff1cb7710aa9b1c5540b7d11aa62537

std.mem: introduce copySentinel

for when source memory region is sentinel-terminated and length is not yet known.

1 files changed, 15 insertions(+), 0 deletions(-)

lib/std/mem.zig+15
...@@ -269,6 +269,21 @@ pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void {...@@ -269,6 +269,21 @@ pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void {
269 }269 }
270}270}
271271
272/// Copy `source` into `dest`. Asserts no overlap. Asserts `dest.len` greater or equal to source len. Returns
273/// number of elements copied. Sentinel is not copied.
274pub fn copySentinel(comptime T: type, comptime s: T, dest: []T, source: [*:s]const T) usize {
275 const i = findSentinel(T, s, source);
276 @memcpy(dest[0..i], source[0..i]);
277 return i;
278}
279
280test copySentinel {
281 var dst: [11]u8 = @splat(0xff);
282 const n = copySentinel(u8, 0, &dst, "hello this\x00is my null-terminated string");
283 try testing.expectEqualStrings("hello this\xff", &dst);
284 try testing.expectEqual(n, 10);
285}
286
272/// Generally, Zig users are encouraged to explicitly initialize all fields of a struct explicitly rather than using this function.287/// Generally, Zig users are encouraged to explicitly initialize all fields of a struct explicitly rather than using this function.
273/// However, it is recognized that there are sometimes use cases for initializing all fields to a "zero" value. For example, when288/// However, it is recognized that there are sometimes use cases for initializing all fields to a "zero" value. For example, when
274/// interfacing with a C API where this practice is more common and relied upon. If you are performing code review and see this289/// interfacing with a C API where this practice is more common and relied upon. If you are performing code review and see this