zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 0a016e8fc29467e48cfc04b1ee829bbd254b2d6d (tree)
parent f93498d2d87ff03ffac95c814cc46b6994416b55
Author: dec05eba <dec05eba@protonmail.com>
Date:   Sat,  5 Sep 2020 16:55:32 +0200

Fix indexOf and lastIndexOf with empty needle

Diffstat:
Mlib/std/mem.zig | 9+++++++--
1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/lib/std/mem.zig b/lib/std/mem.zig @@ -895,7 +895,8 @@ fn boyerMooreHorspoolPreprocess(pattern: []const u8, table: *[256]usize) void { /// To start looking at a different index, slice the haystack first. // Reverse boyer-moore-horspool algorithm pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?usize { - if (needle.len > haystack.len or needle.len == 0) return null; + if (needle.len > haystack.len) return null; + if (needle.len == 0) return haystack.len; if (!meta.trait.hasUniqueRepresentation(T) or haystack.len < 32 or needle.len <= 2) return lastIndexOfLinear(T, haystack, needle); @@ -919,7 +920,8 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us // Boyer-moore-horspool algorithm pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize { - if (needle.len > haystack.len or needle.len == 0) return null; + if (needle.len > haystack.len) return null; + if (needle.len == 0) return 0; if (!meta.trait.hasUniqueRepresentation(T) or haystack.len < 32 or needle.len <= 2) return indexOfPosLinear(T, haystack, start_index, needle); @@ -945,6 +947,9 @@ test "mem.indexOf" { testing.expect(indexOf(u8, "one two three four five six seven eight nine ten", "two two") == null); testing.expect(lastIndexOf(u8, "one two three four five six seven eight nine ten", "two two") == null); + testing.expect(indexOf(u8, "one two three four five six seven eight nine ten", "").? == 0); + testing.expect(lastIndexOf(u8, "one two three four five six seven eight nine ten", "").? == 48); + testing.expect(indexOf(u8, "one two three four", "four").? == 14); testing.expect(lastIndexOf(u8, "one two three two four", "two").? == 14); testing.expect(indexOf(u8, "one two three four", "gour") == null);