hare

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

strcmp.ha (1281B)


      1 // License: MPL-2.0
      2 // (c) 2021 Drew DeVault <sir@cmpwn.com>
      3 // (c) 2021 Ember Sawady <ecs@d2evs.net>
      4 use strings;
      5 
      6 // Compares two strings by their ASCII sort order, treating all capital letters
      7 // as their lowercase counterpart (i.e. a case-insensitive comparison is
      8 // performed). Zero is returned if the strings are equal, a negative value if a
      9 // is less than b, or a positive value if a is greater than b. Aborts if a
     10 // non-ASCII byte is encountered.
     11 export fn strcasecmp(a: str, b: str) int = {
     12 	let a = strings::iter(a), b = strings::iter(b);
     13 	for (true) {
     14 		let ra = match (strings::next(&a)) {
     15 		case void =>
     16 			match (strings::next(&b)) {
     17 			case void =>
     18 				break;
     19 			case rune =>
     20 				return -1;
     21 			};
     22 		case let r: rune =>
     23 			yield r;
     24 		};
     25 		let rb = match (strings::next(&b)) {
     26 		case void =>
     27 			return 1;
     28 		case let r: rune =>
     29 			yield r;
     30 		};
     31 		assert(valid(ra) && valid(rb));
     32 		let ra = tolower(ra), rb = tolower(rb);
     33 		if (ra != rb) {
     34 			return ra: u32: int - rb: u32: int;
     35 		};
     36 	};
     37 	return 0;
     38 };
     39 
     40 @test fn strcmp() void = {
     41 	assert(strcasecmp("ABC", "ABC") == 0);
     42 	assert(strcasecmp("ABC", "abc") == 0);
     43 	assert(strcasecmp("ABC", "aB") > 0);
     44 	assert(strcasecmp("ab", "Abc") < 0);
     45 	assert(strcasecmp("bcd", "ABC") > 0);
     46 	assert(strcasecmp("ABC", "[[[") > 0);
     47 };