Skip to content

Commit

Permalink
[lib/util] Add Strings.asciiLt
Browse files Browse the repository at this point in the history
  • Loading branch information
titzer committed Jan 29, 2024
1 parent d4519da commit eb78ece
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/util/Strings.v3
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,16 @@ component Strings {
def puts(s: string) -> StringBuilder -> StringBuilder {
return StringBuilder.puts(_, s);
}
// Compares two strings according to 8-bit ASCII lexicographical order.
def asciiLt(a: string, b: string) -> bool {
if (a == null) return b != null; // null < non-null
if (b == null) return false; // non-null > null
for (i < a.length) {
if (i >= b.length) return false;
var ac = a[i], bc = b[i];
if (ac < bc) return true;
if (bc < ac) return false;
}
return a.length < b.length;
}
}
24 changes: 24 additions & 0 deletions test/lib/StringsTest.v3
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ def X = [
T("parseLiteral", test_parseLiteral),
T("parseLiteralHex", test_parseLiteralHex),
T("parseLiteralErr", test_parseLiteralErr),
T("asciiLt", test_asciiLt),
()
];

Expand Down Expand Up @@ -89,3 +90,26 @@ def test_parseLiteralErr(t: LibTest) {
}

}

def test_asciiLt(t: LibTest) {
def empty = "", a = "a", b = "b", aa = "aa", bb = "bb";
def LT = Strings.asciiLt;

t.assertz(false, LT(null, null));
t.assertz(true, LT(null, empty));
t.assertz(false, LT(empty, null));
t.assertz(false, LT(empty, empty));

t.assertz(false, LT(a, a));
t.assertz(true, LT(a, b));
t.assertz(false, LT(b, a));
t.assertz(false, LT(b, b));

t.assertz(false, LT(aa, a));
t.assertz(true, LT(a, aa));
t.assertz(false, LT(b, aa));
t.assertz(true, LT(aa, b));

t.assertz(true, LT("aaaaaa", "aazaaa"));
t.assertz(false, LT("BBBBBB", "BBABBB"));
}
3 changes: 3 additions & 0 deletions test/lib/main.v3
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ class LibTest(prefix: string, name: string, fun: LibTest -> void, tail: LibTest)
def assert(z: bool) -> this {
if (!z) fail("expected true");
}
def assertz(expected: bool, got: bool) -> this {
if (expected != got) fail(if(expected, "expected true", "expected false"));
}
def asserteq<T>(a: T, b: T) -> this {
if (a != b) fail("expected equal");
}
Expand Down

0 comments on commit eb78ece

Please sign in to comment.