From fd8fa551295cdf8eac2f524bda835dce731a4c0a Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Fri, 4 Dec 2020 21:27:28 +0100 Subject: [PATCH] std: Add a few helpers for matching ascii strings (#7300) * startsWithIgnoreCase * endsWithIgnoreCase --- lib/std/ascii.zig | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/lib/std/ascii.zig b/lib/std/ascii.zig index d0f4b5758b..c8dc37c99c 100644 --- a/lib/std/ascii.zig +++ b/lib/std/ascii.zig @@ -335,6 +335,24 @@ test "eqlIgnoreCase" { std.testing.expect(!eqlIgnoreCase("hElLo!", "helro!")); } +pub fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool { + return if (needle.len > haystack.len) false else eqlIgnoreCase(haystack[0..needle.len], needle); +} + +test "ascii.startsWithIgnoreCase" { + std.testing.expect(startsWithIgnoreCase("boB", "Bo")); + std.testing.expect(!startsWithIgnoreCase("Needle in hAyStAcK", "haystack")); +} + +pub fn endsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool { + return if (needle.len > haystack.len) false else eqlIgnoreCase(haystack[haystack.len - needle.len ..], needle); +} + +test "ascii.endsWithIgnoreCase" { + std.testing.expect(endsWithIgnoreCase("Needle in HaYsTaCk", "haystack")); + std.testing.expect(!endsWithIgnoreCase("BoB", "Bo")); +} + /// Finds `substr` in `container`, ignoring case, starting at `start_index`. /// TODO boyer-moore algorithm pub fn indexOfIgnoreCasePos(container: []const u8, start_index: usize, substr: []const u8) ?usize {