hare

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

commit 9761fd06e2d4cd37ea1ff6a1b7e877c2bcd39ee5
parent 13fbc8fd10abea66171d93ab308edb01e0ab6f93
Author: Sebastian <sebastian@sebsite.pw>
Date:   Tue, 22 Feb 2022 18:50:04 -0500

strings: add strcmp function

Signed-off-by: Sebastian <sebastian@sebsite.pw>

Diffstat:
Mstdlib.mk | 2++
Astrings/strcmp.ha | 38++++++++++++++++++++++++++++++++++++++
2 files changed, 40 insertions(+), 0 deletions(-)

diff --git a/stdlib.mk b/stdlib.mk @@ -1620,6 +1620,7 @@ stdlib_strings_any_srcs= \ $(STDLIB)/strings/cstrings.ha \ $(STDLIB)/strings/dup.ha \ $(STDLIB)/strings/iter.ha \ + $(STDLIB)/strings/strcmp.ha \ $(STDLIB)/strings/sub.ha \ $(STDLIB)/strings/suffix.ha \ $(STDLIB)/strings/tokenize.ha \ @@ -3488,6 +3489,7 @@ testlib_strings_any_srcs= \ $(STDLIB)/strings/cstrings.ha \ $(STDLIB)/strings/dup.ha \ $(STDLIB)/strings/iter.ha \ + $(STDLIB)/strings/strcmp.ha \ $(STDLIB)/strings/sub.ha \ $(STDLIB)/strings/suffix.ha \ $(STDLIB)/strings/tokenize.ha \ diff --git a/strings/strcmp.ha b/strings/strcmp.ha @@ -0,0 +1,38 @@ +// Compares two strings by their Unicode codepoint sort order. Zero is returned +// if the strings are equal, a negative value if a is less than b, or a positive +// value if a is greater than b. +export fn strcmp(a: str, b: str) int = { + let a = iter(a), b = iter(b); + for (true) { + let ra = match (next(&a)) { + case void => + match (next(&b)) { + case void => + return 0; + case rune => + return -1; + }; + case let r: rune => + yield r; + }; + let rb = match (next(&b)) { + case void => + return 1; + case let r: rune => + yield r; + }; + if (ra != rb) { + return ra: u32: int - rb: u32: int; + }; + }; + abort("unreachable"); +}; + +@test fn strcmp() void = { + assert(strcmp("ABC", "ABC") == 0); + assert(strcmp("ABC", "AB") > 0); + assert(strcmp("AB", "ABC") < 0); + assert(strcmp("BCD", "ABC") > 0); + assert(strcmp("ABC", "こんにちは") < 0); + assert(strcmp("ABC", "abc") < 0); +};