hare

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

contains.ha (1121B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 use bytes;
      5 use encoding::utf8;
      6 
      7 // Returns true if a string contains a rune or a sub-string, multiple of which
      8 // can be given.
      9 export fn contains(haystack: str, needles: (str | rune)...) bool = {
     10 	for (let needle .. needles) {
     11 		const matched = match (needle) {
     12 		case let s: str =>
     13 			yield bytes::contains(toutf8(haystack),
     14 				toutf8(s));
     15 		case let r: rune =>
     16 			yield bytes::contains(toutf8(haystack),
     17 				utf8::encoderune(r));
     18 		};
     19 		if (matched) {
     20 			return true;
     21 		};
     22 	};
     23 	return false;
     24 };
     25 
     26 @test fn contains() void = {
     27 	assert(contains("hello world", "hello"));
     28 	assert(contains("hello world", 'h'));
     29 	assert(!contains("hello world", 'x'));
     30 	assert(contains("hello world", "world"));
     31 	assert(contains("hello world", ""));
     32 	assert(!contains("hello world", "foobar"));
     33 	assert(contains("hello world", "foobar", "hello", "bar"));
     34 	assert(!contains("hello world", "foobar", "foo", "bar"));
     35 	assert(contains("hello world", 'h', "foo", "bar"));
     36 	assert(!contains("hello world", 'x', "foo", "bar"));
     37 	assert(!contains("hello world"));
     38 };