authorgravatar for dec05eba@protonmail.comdec05eba <dec05eba@protonmail.com> 2020-09-05 16:55:32+02:00
committergravatar for dec05eba@protonmail.comdec05eba <dec05eba@protonmail.com> 2020-09-05 16:55:32+02:00
log0a016e8fc29467e48cfc04b1ee829bbd254b2d6d
treea00a42856b69b275f713d022282096003445530e
parentf93498d2d87ff03ffac95c814cc46b6994416b55

Fix indexOf and lastIndexOf with empty needle


1 files changed, 7 insertions(+), 2 deletions(-)

lib/std/mem.zig+7-2
......@@ -895,7 +895,8 @@ fn boyerMooreHorspoolPreprocess(pattern: []const u8, table: *[256]usize) void {
895895/// To start looking at a different index, slice the haystack first.
896896// Reverse boyer-moore-horspool algorithm
897897pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?usize {
898 if (needle.len > haystack.len or needle.len == 0) return null;
898 if (needle.len > haystack.len) return null;
899 if (needle.len == 0) return haystack.len;
899900
900901 if (!meta.trait.hasUniqueRepresentation(T) or haystack.len < 32 or needle.len <= 2)
901902 return lastIndexOfLinear(T, haystack, needle);
......@@ -919,7 +920,8 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us
919920
920921// Boyer-moore-horspool algorithm
921922pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {
922 if (needle.len > haystack.len or needle.len == 0) return null;
923 if (needle.len > haystack.len) return null;
924 if (needle.len == 0) return 0;
923925
924926 if (!meta.trait.hasUniqueRepresentation(T) or haystack.len < 32 or needle.len <= 2)
925927 return indexOfPosLinear(T, haystack, start_index, needle);
......@@ -945,6 +947,9 @@ test "mem.indexOf" {
945947 testing.expect(indexOf(u8, "one two three four five six seven eight nine ten", "two two") == null);
946948 testing.expect(lastIndexOf(u8, "one two three four five six seven eight nine ten", "two two") == null);
947949
950 testing.expect(indexOf(u8, "one two three four five six seven eight nine ten", "").? == 0);
951 testing.expect(lastIndexOf(u8, "one two three four five six seven eight nine ten", "").? == 48);
952
948953 testing.expect(indexOf(u8, "one two three four", "four").? == 14);
949954 testing.expect(lastIndexOf(u8, "one two three two four", "two").? == 14);
950955 testing.expect(indexOf(u8, "one two three four", "gour") == null);