hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

trim.ha (1124B)


      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.
      6 export fn ltrim(in: []u8, trim: u8...) []u8 = {
      7 	let i = 0z;
      8 	for (i < len(in) && contains(trim, in[i]); i+= 1) void;
      9 	return in[i..];
     10 };
     11 
     12 // Returns a slice (borrowed from given input slice) after trimming off of
     13 // the end of the input slice the bytes in the given list.
     14 export fn rtrim(in: []u8, trim: u8...) []u8 = {
     15 	let i = len(in) - 1;
     16 	for (i < len(in) && contains(trim, in[i]); i -= 1) void;
     17 	return in[..i + 1];
     18 };
     19 
     20 // Returns a slice (borrowed from given input slice) after trimming off of
     21 // the both ends of the input slice the bytes in the given list.
     22 export fn trim(in: []u8, trim: u8...) []u8 = ltrim(rtrim(in, trim...), trim...);
     23 
     24 @test fn trim() void = {
     25 	assert(equal(trim([0, 1, 2, 3, 5, 0], 0), [1, 2, 3, 5]));
     26 	assert(equal(trim([1, 2, 3, 5], 0), [1, 2, 3, 5]));
     27 	assert(equal(trim([0, 0, 0], 0), []));
     28 	assert(equal(trim([0, 5, 0], 5), [0, 5, 0]));
     29 	assert(equal(trim([], 0), []));
     30 };