commit 5d6c8071e375856f60d5ff741caf65b5a221e2f2
parent a0d9ef9d5132a1338dcfa6848f88e523517ec2c3
Author: Bor Grošelj Simić <bor.groseljsimic@telemach.net>
Date: Tue, 9 Feb 2021 21:17:10 +0100
bytes/index.ha: fix a substring search bug
The substring search failed to find "aab" in "aaab". A test case was
added with this input (but in bytes).
Diffstat:
1 file changed, 9 insertions(+), 12 deletions(-)
diff --git a/bytes/index.ha b/bytes/index.ha
@@ -16,18 +16,9 @@ fn index_byte(haystack: []u8, needle: u8) (size | void) = {
};
fn index_slice(haystack: []u8, needle: []u8) (size | void) = {
- if (len(needle) > len(haystack)) {
- return;
- };
- let i = 0z;
- for (i < len(haystack)) {
- let n = nequal(haystack[i..], needle);
- if (n == len(needle)) {
+ for (let i = 0z; i + len(needle) <= len(haystack); i += 1z) {
+ if (equal(haystack[i..i + len(needle)], needle)) {
return i;
- } else if (n != 0z) {
- i += n;
- } else {
- i += 1z;
};
};
};
@@ -35,7 +26,7 @@ fn index_slice(haystack: []u8, needle: []u8) (size | void) = {
@test fn index() void = {
// Bytes
- let a: [4]u8 = [1u8, 3u8, 3u8, 7u8];
+ const a: [4]u8 = [1u8, 3u8, 3u8, 7u8];
match (index(a, 7u8)) {
n: size => assert(n == 3z),
void => abort(),
@@ -62,4 +53,10 @@ fn index_slice(haystack: []u8, needle: []u8) (size | void) = {
size => abort(),
void => void,
};
+
+ const special: []u8 = [1u8, 1u8, 1u8, 2u8];
+ match (index(special, [1u8, 1u8, 2u8])) {
+ n: size => assert(n == 1z),
+ void => abort(),
+ };
};