authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-09-24 16:42:23-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-09-25 10:50:41-07:00
logac4d79e3227cf7bc5ec88e1dce6f879b1208bd8e
tree9604cb8fd3ef34223852629d6dfc477fe206f6eb
parenta73f246b2963de0024b9b7070448862e855d5a04

std.mem: introduce chompPrefix and chompSuffix


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

lib/std/mem.zig+20
......@@ -3079,6 +3079,26 @@ test endsWith {
30793079 try testing.expect(!endsWith(u8, "Bob", "Bo"));
30803080}
30813081
3082/// If `slice` starts with `prefix`, returns the rest of `slice` starting at `prefix.len`.
3083pub fn chompPrefix(comptime T: type, slice: []const T, prefix: []const T) ?[]const T {
3084 return if (startsWith(T, slice, prefix)) slice[prefix.len..] else null;
3085}
3086
3087test chompPrefix {
3088 try testing.expectEqualStrings("foo", chompPrefix(u8, "--example=foo", "--example=").?);
3089 try testing.expectEqual(null, chompPrefix(u8, "--example=foo", "-example="));
3090}
3091
3092/// If `slice` ends with `suffix`, returns `slice` from beginning to start of `suffix`.
3093pub fn chompSuffix(comptime T: type, slice: []const T, suffix: []const T) ?[]const T {
3094 return if (endsWith(T, slice, suffix)) slice[0 .. slice.len - suffix.len] else null;
3095}
3096
3097test chompSuffix {
3098 try testing.expectEqualStrings("foo", chompSuffix(u8, "foobar", "bar").?);
3099 try testing.expectEqual(null, chompSuffix(u8, "foobar", "baz"));
3100}
3101
30823102/// Delimiter type for tokenization and splitting operations.
30833103pub const DelimiterType = enum { sequence, any, scalar };
30843104