authorgravatar for dec05eba@protonmail.comdec05eba <dec05eba@protonmail.com> 2020-09-05 11:22:12+02:00
committergravatar for dec05eba@protonmail.comdec05eba <dec05eba@protonmail.com> 2020-09-05 11:22:12+02:00
log50c52e013541550c7c89c30d336bc4991218f888
treeac62b5f6da80aca3f7ea1922d855aa4cf8ee5e53
parentcff14dc2c67d9a35ae2c3e07bd6d2c5594d8a0a1

Use boyer-moore-horspool algorithm for indexOfPos and lastIndexOf


1 files changed, 23 insertions(+), 14 deletions(-)

lib/std/mem.zig+23-14
......@@ -850,29 +850,38 @@ pub fn indexOfAnyPos(comptime T: type, slice: []const T, start_index: usize, val
850850pub fn indexOf(comptime T: type, haystack: []const T, needle: []const T) ?usize {
851851 return indexOfPos(T, haystack, 0, needle);
852852}
853
854853/// Find the index in a slice of a sub-slice, searching from the end backwards.
855854/// To start looking at a different index, slice the haystack first.
856/// TODO is there even a better algorithm for this?
855// Reverse boyer-moore-horspool algorithm
857856pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?usize {
858 if (needle.len > haystack.len) return null;
859
860 var i: usize = haystack.len - needle.len;
861 while (true) : (i -= 1) {
862 if (mem.eql(T, haystack[i .. i + needle.len], needle)) return i;
863 if (i == 0) return null;
857 if (needle.len > haystack.len or needle.len == 0) return null;
858
859 var i: usize = needle.len - 1;
860 while (i < haystack.len) {
861 const reverseIndex = haystack.len - i - 1;
862 if (indexOfScalar(T, needle, haystack[reverseIndex])) |index| {
863 const haystackIndex = reverseIndex - index;
864 if (haystackIndex + needle.len <= haystack.len and mem.eql(T, haystack[haystackIndex .. haystackIndex + needle.len], needle)) return haystackIndex;
865 }
866 i += needle.len;
864867 }
868
869 return null;
865870}
866871
867// TODO boyer-moore algorithm
872// Boyer-moore-horspool algorithm
868873pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {
869 if (needle.len > haystack.len) return null;
874 if (needle.len > haystack.len or needle.len == 0) return null;
870875
871 var i: usize = start_index;
872 const end = haystack.len - needle.len;
873 while (i <= end) : (i += 1) {
874 if (eql(T, haystack[i .. i + needle.len], needle)) return i;
876 var i: usize = start_index + needle.len - 1;
877 while (i < haystack.len) {
878 if (lastIndexOfScalar(T, needle, haystack[i])) |index| {
879 const haystackIndex = i - index;
880 if (haystackIndex + needle.len <= haystack.len and mem.eql(T, haystack[haystackIndex .. haystackIndex + needle.len], needle)) return haystackIndex;
881 }
882 i += needle.len;
875883 }
884
876885 return null;
877886}
878887