From ac4d79e3227cf7bc5ec88e1dce6f879b1208bd8e Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 24 Sep 2025 16:42:23 -0700 Subject: [PATCH] std.mem: introduce chompPrefix and chompSuffix --- lib/std/mem.zig | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 4e6161b0ec..890530d363 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -3079,6 +3079,26 @@ test endsWith { try testing.expect(!endsWith(u8, "Bob", "Bo")); } +/// If `slice` starts with `prefix`, returns the rest of `slice` starting at `prefix.len`. +pub fn chompPrefix(comptime T: type, slice: []const T, prefix: []const T) ?[]const T { + return if (startsWith(T, slice, prefix)) slice[prefix.len..] else null; +} + +test chompPrefix { + try testing.expectEqualStrings("foo", chompPrefix(u8, "--example=foo", "--example=").?); + try testing.expectEqual(null, chompPrefix(u8, "--example=foo", "-example=")); +} + +/// If `slice` ends with `suffix`, returns `slice` from beginning to start of `suffix`. +pub fn chompSuffix(comptime T: type, slice: []const T, suffix: []const T) ?[]const T { + return if (endsWith(T, slice, suffix)) slice[0 .. slice.len - suffix.len] else null; +} + +test chompSuffix { + try testing.expectEqualStrings("foo", chompSuffix(u8, "foobar", "bar").?); + try testing.expectEqual(null, chompSuffix(u8, "foobar", "baz")); +} + /// Delimiter type for tokenization and splitting operations. pub const DelimiterType = enum { sequence, any, scalar };