Debian Codegraph @

bytes/trim.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 // Returns a slice (borrowed from given input slice) after trimming off of
5 // the start of the input slice the bytes in the given list, which must not be
6 // empty.
7 export fn ltrim(in: []u8, trim: u8...) []u8 = {
8 assert(len(trim) > 0);
9 let i = 0z;
10 for (i < len(in) && contains(trim, in[i]); i+= 1) void;
11 return in[i..];
12 };
13
14 // Returns a slice (borrowed from given input slice) after trimming off of
15 // the end of the input slice the bytes in the given list, which must not be
16 // empty.
17 export fn rtrim(in: []u8, trim: u8...) []u8 = {
18 assert(len(trim) > 0);
19 let i = len(in) - 1;
20 for (i < len(in) && contains(trim, in[i]); i -= 1) void;
21 return in[..i + 1];
22 };
23
24 // Returns a slice (borrowed from given input slice) after trimming off of
25 // the both ends of the input slice the bytes in the given list, which must not
26 // be empty.
27 export fn trim(in: []u8, trim: u8...) []u8 = ltrim(rtrim(in, trim...), trim...);
28
29 @test fn trim() void = {
30 assert(equal(trim([0, 1, 2, 3, 5, 0], 0), [1, 2, 3, 5]));
31 assert(equal(trim([1, 2, 3, 5], 0), [1, 2, 3, 5]));
32 assert(equal(trim([0, 0, 0], 0), []));
33 assert(equal(trim([0, 5, 0], 5), [0, 5, 0]));
34 assert(equal(trim([], 0), []));
35 };