hare

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

commit ea5dfc8e136e4222fdeabfa3a65f998a7466dc41
parent a2a325478e28546afd23b754a8856d904c855255
Author: Bor Grošelj Simić <bgs@turminal.net>
Date:   Tue, 19 Apr 2022 03:57:09 +0200

add bytes::{l,r,}trim

Signed-off-by: Bor Grošelj Simić <bgs@turminal.net>

Diffstat:
Abytes/trim.ha | 27+++++++++++++++++++++++++++
Mscripts/gen-stdlib | 1+
Mstdlib.mk | 2++
3 files changed, 30 insertions(+), 0 deletions(-)

diff --git a/bytes/trim.ha b/bytes/trim.ha @@ -0,0 +1,27 @@ +// Returns a slice (borrowed from given input slice) after trimming off of +// the start of the input slice the bytes in the given list. +export fn ltrim(in: []u8, trim: u8...) []u8 = { + let i = 0z; + for (i < len(in) && contains(trim, in[i]); i+= 1) void; + return in[i..]; +}; + +// Returns a slice (borrowed from given input slice) after trimming off of +// the end of the input slice the bytes in the given list. +export fn rtrim(in: []u8, trim: u8...) []u8 = { + let i = len(in) - 1; + for (i < len(in) && contains(trim, in[i]); i-= 1) void; + return in[..i + 1]; +}; + +// Returns a slice (borrowed from given input slice) after trimming off of +// the both ends of the input slice the bytes in the given list. +export fn trim(in: []u8, trim: u8...) []u8 = ltrim(rtrim(in, trim...), trim...); + +@test fn trim() void = { + assert(equal(trim([0, 1, 2, 3, 5, 0], 0), [1, 2, 3, 5])); + assert(equal(trim([1, 2, 3, 5], 0), [1, 2, 3, 5])); + assert(equal(trim([0, 0, 0], 0), [])); + assert(equal(trim([0, 5, 0], 5), [0, 5, 0])); +}; + diff --git a/scripts/gen-stdlib b/scripts/gen-stdlib @@ -177,6 +177,7 @@ bytes() { index.ha \ reverse.ha \ tokenize.ha \ + trim.ha \ two_way.ha \ zero.ha gen_ssa bytes types diff --git a/stdlib.mk b/stdlib.mk @@ -707,6 +707,7 @@ stdlib_bytes_any_srcs= \ $(STDLIB)/bytes/index.ha \ $(STDLIB)/bytes/reverse.ha \ $(STDLIB)/bytes/tokenize.ha \ + $(STDLIB)/bytes/trim.ha \ $(STDLIB)/bytes/two_way.ha \ $(STDLIB)/bytes/zero.ha @@ -2654,6 +2655,7 @@ testlib_bytes_any_srcs= \ $(STDLIB)/bytes/index.ha \ $(STDLIB)/bytes/reverse.ha \ $(STDLIB)/bytes/tokenize.ha \ + $(STDLIB)/bytes/trim.ha \ $(STDLIB)/bytes/two_way.ha \ $(STDLIB)/bytes/zero.ha