hare

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

commit c0f442d0e509a65e0cfeef267269d5a0cae6d51b
parent a0ecfc626f7c7dd828e1c124fef183dbc2f96d89
Author: Vlad-Stefan Harbuz <vlad@vladh.net>
Date:   Thu, 12 May 2022 20:58:23 +0100

strings::contains: accept multiple needles. Fixes #570

Signed-off-by: Vlad-Stefan Harbuz <vlad@vladh.net>

Diffstat:
Mstrings/contains.ha | 30++++++++++++++++++++++++------
1 file changed, 24 insertions(+), 6 deletions(-)

diff --git a/strings/contains.ha b/strings/contains.ha @@ -1,20 +1,38 @@ // License: MPL-2.0 // (c) 2021 Drew DeVault <sir@cmpwn.com> // (c) 2021 Eyal Sawady <ecs@d2evs.net> +// (c) 2022 Vlad-Stefan Harbuz <vlad@vladh.net> use bytes; use encoding::utf8; -// Returns true if a string contains a rune or a sub-string. -export fn contains(haystack: str, needle: (str | rune)) bool = match (needle) { -case let s: str => - yield bytes::contains(toutf8(haystack), toutf8(s)); -case let r: rune => - yield bytes::contains(toutf8(haystack), utf8::encoderune(r)); +// Returns true if a string contains a rune or a sub-string, multiple of which +// can be given. +export fn contains(haystack: str, needles: (str | rune)...) bool = { + for (let i = 0z; i < len(needles); i += 1) { + const matched = match (needles[i]) { + case let s: str => + yield bytes::contains(toutf8(haystack), + toutf8(s)); + case let r: rune => + yield bytes::contains(toutf8(haystack), + utf8::encoderune(r)); + }; + if (matched) { + return true; + }; + }; + return false; }; @test fn contains() void = { assert(contains("hello world", "hello")); + assert(contains("hello world", 'h')); + assert(!contains("hello world", 'x')); assert(contains("hello world", "world")); assert(contains("hello world", "")); assert(!contains("hello world", "foobar")); + assert(contains("hello world", "foobar", "hello", "bar")); + assert(!contains("hello world", "foobar", "foo", "bar")); + assert(contains("hello world", 'h', "foo", "bar")); + assert(!contains("hello world", 'x', "foo", "bar")); };