Commit da7baf7dae

Fabio Arnold <fabio@fabioarnold.de>
2021-11-26 02:56:38
std.mem.indexOfPos should return start_index when needle length is zero (#10220)
Closes #10216
1 parent b891ee1
Changed files (1)
lib
lib/std/mem.zig
@@ -1162,7 +1162,7 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us
 /// Uses Boyer-moore-horspool algorithm on large inputs; `indexOfPosLinear` on small inputs.
 pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {
     if (needle.len > haystack.len) return null;
-    if (needle.len == 0) return 0;
+    if (needle.len == 0) return start_index;
 
     if (!meta.trait.hasUniqueRepresentation(T) or haystack.len < 52 or needle.len <= 4)
         return indexOfPosLinear(T, haystack, start_index, needle);
@@ -1237,6 +1237,10 @@ test "mem.indexOf multibyte" {
     }
 }
 
+test "mem.indexOfPos empty needle" {
+    try testing.expectEqual(indexOfPos(u8, "abracadabra", 5, ""), 5);
+}
+
 /// Returns the number of needles inside the haystack
 /// needle.len must be > 0
 /// does not count overlapping needles