authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-12-15 17:26:22-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-12-15 17:26:22-05:00
log39e96d933ec3611017edccfdd443fece826a7207
tree05910a5b956428afb3abb9425184467490962e29
parent68f63323437e1b974be7a9982f5d70b95624878b

change mem.cmp to mem.lessThan and add test


1 files changed, 14 insertions(+), 9 deletions(-)

std/mem.zig+14-9
......@@ -3,8 +3,6 @@ const assert = debug.assert;
33const math = @import("math/index.zig");
44const builtin = @import("builtin");
55
6pub const Cmp = math.Cmp;
7
86pub const Allocator = struct {
97 /// Allocate byte_count bytes and return them in a slice, with the
108 /// slice's pointer aligned at least to alignment bytes.
......@@ -166,17 +164,24 @@ pub fn set(comptime T: type, dest: []T, value: T) {
166164 for (dest) |*d| *d = value;
167165}
168166
169/// Return < 0, == 0, or > 0 if memory a is less than, equal to, or greater than,
170/// memory b, respectively.
171pub fn cmp(comptime T: type, a: []const T, b: []const T) -> Cmp {
172 const n = math.min(a.len, b.len);
167/// Returns true if lhs < rhs, false otherwise
168pub fn lessThan(comptime T: type, lhs: []const T, rhs: []const T) -> bool {
169 const n = math.min(lhs.len, rhs.len);
173170 var i: usize = 0;
174171 while (i < n) : (i += 1) {
175 if (a[i] == b[i]) continue;
176 return if (a[i] > b[i]) Cmp.Greater else if (a[i] < b[i]) Cmp.Less else Cmp.Equal;
172 if (lhs[i] == rhs[i]) continue;
173 return lhs[i] < rhs[i];
177174 }
178175
179 return if (a.len > b.len) Cmp.Greater else if (a.len < b.len) Cmp.Less else Cmp.Equal;
176 return lhs.len < rhs.len;
177}
178
179test "mem.lessThan" {
180 assert(lessThan(u8, "abcd", "bee"));
181 assert(!lessThan(u8, "abc", "abc"));
182 assert(lessThan(u8, "abc", "abc0"));
183 assert(!lessThan(u8, "", ""));
184 assert(lessThan(u8, "", "a"));
180185}
181186
182187/// Compares two slices and returns whether they are equal.