change mem.cmp to mem.lessThan and add test

master
Andrew Kelley 2017-12-15 17:26:22 -05:00
parent 68f6332343
commit 39e96d933e
1 changed files with 14 additions and 9 deletions

View File

@ -3,8 +3,6 @@ const assert = debug.assert;
const math = @import("math/index.zig"); const math = @import("math/index.zig");
const builtin = @import("builtin"); const builtin = @import("builtin");
pub const Cmp = math.Cmp;
pub const Allocator = struct { pub const Allocator = struct {
/// Allocate byte_count bytes and return them in a slice, with the /// Allocate byte_count bytes and return them in a slice, with the
/// slice's pointer aligned at least to alignment bytes. /// slice's pointer aligned at least to alignment bytes.
@ -166,17 +164,24 @@ pub fn set(comptime T: type, dest: []T, value: T) {
for (dest) |*d| *d = value; for (dest) |*d| *d = value;
} }
/// Return < 0, == 0, or > 0 if memory a is less than, equal to, or greater than, /// Returns true if lhs < rhs, false otherwise
/// memory b, respectively. pub fn lessThan(comptime T: type, lhs: []const T, rhs: []const T) -> bool {
pub fn cmp(comptime T: type, a: []const T, b: []const T) -> Cmp { const n = math.min(lhs.len, rhs.len);
const n = math.min(a.len, b.len);
var i: usize = 0; var i: usize = 0;
while (i < n) : (i += 1) { while (i < n) : (i += 1) {
if (a[i] == b[i]) continue; if (lhs[i] == rhs[i]) continue;
return if (a[i] > b[i]) Cmp.Greater else if (a[i] < b[i]) Cmp.Less else Cmp.Equal; return lhs[i] < rhs[i];
} }
return if (a.len > b.len) Cmp.Greater else if (a.len < b.len) Cmp.Less else Cmp.Equal; return lhs.len < rhs.len;
}
test "mem.lessThan" {
assert(lessThan(u8, "abcd", "bee"));
assert(!lessThan(u8, "abc", "abc"));
assert(lessThan(u8, "abc", "abc0"));
assert(!lessThan(u8, "", ""));
assert(lessThan(u8, "", "a"));
} }
/// Compares two slices and returns whether they are equal. /// Compares two slices and returns whether they are equal.