Debian Codegraph @

bytes/contains.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 // Returns true if a byte slice contains a byte or a sequence of bytes.
5 export fn contains(haystack: []u8, needles: (u8 | []u8)...) bool = {
6 for (let i = 0z; i < len(needles); i += 1) {
7 const matched = match (needles[i]) {
8 case let b: u8 =>
9 yield index_byte(haystack, b) is size;
10 case let b: []u8 =>
11 yield index_slice(haystack, b) is size;
12 };
13 if (matched) {
14 return true;
15 };
16 };
17 return false;
18 };
19
20 // Returns true if "in" has the given prefix, false otherwise
21 export fn hasprefix(in: []u8, prefix: []u8) bool = {
22 return len(in) >= len(prefix) && equal(in[..len(prefix)], prefix);
23 };
24
25 @test fn hasprefix() void = {
26 assert(hasprefix([], []));
27 assert(hasprefix([0], []));
28 assert(!hasprefix([], [0]));
29 assert(hasprefix([1, 2, 3], [1, 2]));
30 assert(!hasprefix([1, 2, 3], [1, 1]));
31 assert(!hasprefix([1, 2, 3], [1, 2, 3, 4]));
32 };
33
34 // Returns true if "in" has the given suffix, false otherwise
35 export fn hassuffix(in: []u8, suffix: []u8) bool = {
36 return len(in) >= len(suffix)
37 && equal(in[len(in) - len(suffix)..], suffix);
38 };
39
40 @test fn hassuffix() void = {
41 assert(hassuffix([], []));
42 assert(hassuffix([0], []));
43 assert(!hassuffix([], [0]));
44 assert(hassuffix([1, 2, 3], [2, 3]));
45 assert(!hassuffix([1, 2, 3], [2, 2]));
46 assert(hassuffix([1, 2, 3, 4], [2, 3, 4]));
47 };