From 00594462c47190d567c791c1ddc50c1ee1994a3b Mon Sep 17 00:00:00 2001 From: Alvydas Vitkauskas Date: Sun, 23 Jun 2019 21:25:50 +0300 Subject: [PATCH] fix string comparison functions --- builtin/string.v | 32 ++++++++++++------------- builtin/string_test.v | 54 ++++++++++++++++++++++++++++++++++++++----- 2 files changed, 63 insertions(+), 23 deletions(-) diff --git a/builtin/string.v b/builtin/string.v index b2d76a0e80..c33bd981a4 100644 --- a/builtin/string.v +++ b/builtin/string.v @@ -169,37 +169,35 @@ fn (s string) ne(a string) bool { return !s.eq(a) } -// s >= a -fn (s string) ge(a string) bool { - mut j := 0 +// s < a +fn (s string) lt(a string) bool { for i := 0; i < s.len; i++ { - if i >= a.len { - return true - } - if int(s[i]) < int(a[j]) { + if i >= a.len || s[i] > a[i] { return false } - else if int(s[i]) > int(a[j]) { + else if s[i] < a[i] { return true } - j++ } - return true + if s.len < a.len { + return true + } + return false } // s <= a fn (s string) le(a string) bool { - return !s.ge(a) || s == a -} - -// s < a -fn (s string) lt(a string) bool { - return s.le(a) && s != a + return s.lt(a) || s.eq(a) } // s > a fn (s string) gt(a string) bool { - return s.ge(a) && s != a + return !s.le(a) +} + +// s >= a +fn (s string) ge(a string) bool { + return !s.lt(a) } // TODO `fn (s string) + (a string)` ? To be consistent with operator overloading syntax. diff --git a/builtin/string_test.v b/builtin/string_test.v index c0356f71df..774d327461 100644 --- a/builtin/string_test.v +++ b/builtin/string_test.v @@ -32,16 +32,59 @@ fn test_compare() { assert b.ge(a) } +fn test_lt() { + a := '' + b := 'a' + c := 'a' + d := 'b' + e := 'aa' + f := 'ab' + assert a.lt(b) + assert b.lt(c) == false + assert c.lt(d) + assert d.lt(e) == false + assert c.lt(e) + assert e.lt(f) +} + +fn test_ge() { + a := 'aa' + b := 'aa' + c := 'ab' + d := 'abc' + e := 'aaa' + assert b.ge(a) + assert c.ge(b) + assert d.ge(c) + assert c.ge(d) == false + assert e.ge(a) +} + +fn test_compare_strings() { + a := 'aa' + b := 'aa' + c := 'ab' + d := 'abc' + e := 'aaa' + assert compare_strings(a, b) == 0 + assert compare_strings(b, c) == -1 + assert compare_strings(c, d) == -1 + assert compare_strings(d, e) == 1 + assert compare_strings(a, e) == -1 + assert compare_strings(e, a) == 1 +} + fn test_sort() { mut vals := [ - 'src', 'Music', 'go' + 'arr', 'an', 'a', 'any' ] len := vals.len vals.sort() assert len == vals.len - assert vals[0] == 'Music' - assert vals[1] == 'go' - assert vals[2] == 'src' + assert vals[0] == 'a' + assert vals[1] == 'an' + assert vals[2] == 'any' + assert vals[3] == 'arr' } fn test_split() { @@ -246,5 +289,4 @@ fn test_all_after() { s := 'fn hello' q := s.all_after('fn ') assert q == 'hello' -} - +} \ No newline at end of file