From 91c5eaeab9e2c5d71bda4614c8748d6ebf715835 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 24 Aug 2026 20:06:51 -0700 Subject: [PATCH] std.mem: add copySentinel and lessThanZ functions --- lib/std/mem.zig | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index d8b3872eb0be27f79fa66b3805f7cb567e57be10..d2b8c571085d19d57732e7549bf23237463d31ef 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -269,6 +269,18 @@ 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. +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 { + @panic("TODO"); +} + /// 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 +745,20 @@ 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, -- 2.54.0