Commit ac4d79e322
Changed files (1)
lib
std
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 };