hare

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

commit 1e28e8ac6853366424048307904de2ceed11522a
parent 5a92722a862ff8afa85a5be830910f1e02bd5fbe
Author: Drew DeVault <sir@cmpwn.com>
Date:   Sun,  7 Feb 2021 11:20:05 -0500

strings: add has_prefix, has_suffix

Diffstat:
Astrings/suffix.ha | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mstrings/tokenize.ha | 2+-
2 files changed, 49 insertions(+), 1 deletion(-)

diff --git a/strings/suffix.ha b/strings/suffix.ha @@ -0,0 +1,48 @@ +// Returns true if 'in' has the given prefix. +export fn has_prefix(in: str, prefix: str) bool = { + let a = to_utf8(in), b = to_utf8(prefix); + if (len(a) < len(b)) { + return false; + }; + for (let i = 0z; i < len(b); i += 1z) { + if (a[i] != b[i]) { + return false; + }; + }; + return true; +}; + +@test fn prefix() void = { + assert(has_prefix("abcde", "abc")); + assert(has_prefix("abcde", "abcde")); + assert(has_prefix("abcde", "")); + assert(has_prefix("", "")); + assert(!has_prefix("abcde", "cde")); + assert(!has_prefix("abcde", "abcdefg")); + assert(!has_prefix("", "abc")); +}; + +// Returns true if 'in' has the given prefix. +export fn has_suffix(in: str, suff: str) bool = { + let a = to_utf8(in), b = to_utf8(suff); + if (len(a) < len(b)) { + return false; + }; + for (let i = 0z; i < len(b); i += 1z) { + if (a[len(a) - len(b) + i] != b[i]) { + return false; + }; + }; + return true; +}; + +@test fn suffix() void = { + assert(has_suffix("abcde", "cde")); + assert(has_suffix("abcde", "abcde")); + assert(has_suffix("abcde", "")); + assert(has_suffix("", "")); + assert(has_suffix("abcde", "")); + assert(!has_suffix("abcde", "abc")); + assert(!has_suffix("abcde", "fabcde")); + assert(!has_suffix("", "abc")); +}; diff --git a/strings/tokenize.ha b/strings/tokenize.ha @@ -2,7 +2,7 @@ use bytes; use types; // The state for a tokenizer. -type tokenizer = bytes::tokenizer; +export type tokenizer = bytes::tokenizer; // Returns a tokenizer which yields sub-strings tokenized by a delimiter. //