authorgravatar for shawn@git.icuShawn Landden <shawn@git.icu> 2018-08-07 05:30:54-07:00
committergravatar for shawn@git.icuShawn Landden <shawn@git.icu> 2018-08-07 05:30:54-07:00
logbbbb26f4d3271064ab35c17d214b504eac5a0ef9
treed7768c2530c591938a4395e0a727bdf48c518891
parent86b512c5cd277a800c8333ed4206002316f4aca2

mem: add mem.compare(), and use it for mem.lessThan()


1 files changed, 35 insertions(+), 5 deletions(-)

std/mem.zig+35-5
......@@ -175,16 +175,46 @@ pub fn set(comptime T: type, dest: []T, value: T) void {
175175 d.* = value;
176176}
177177
178/// Returns true if lhs < rhs, false otherwise
179pub fn lessThan(comptime T: type, lhs: []const T, rhs: []const T) bool {
178pub fn compare(comptime T: type, lhs: []const T, rhs: []const T) Compare {
180179 const n = math.min(lhs.len, rhs.len);
181180 var i: usize = 0;
182181 while (i < n) : (i += 1) {
183 if (lhs[i] == rhs[i]) continue;
184 return lhs[i] < rhs[i];
182 if (lhs[i] == rhs[i]) {
183 continue;
184 } else if (lhs[i] < rhs[i]) {
185 return Compare.LessThan;
186 } else if (lhs[i] > rhs[i]) {
187 return Compare.GreaterThan;
188 } else {
189 unreachable;
190 }
185191 }
186192
187 return lhs.len < rhs.len;
193 if (lhs.len == rhs.len) {
194 return Compare.Equal;
195 } else if (lhs.len < rhs.len) {
196 return Compare.LessThan;
197 } else if (lhs.len > rhs.len) {
198 return Compare.GreaterThan;
199 }
200 unreachable;
201}
202
203test "mem.compare" {
204 assert(compare(u8, "abcd", "bee") == Compare.LessThan);
205 assert(compare(u8, "abc", "abc") == Compare.Equal);
206 assert(compare(u8, "abc", "abc0") == Compare.LessThan);
207 assert(compare(u8, "", "") == Compare.Equal);
208 assert(compare(u8, "", "a") == Compare.LessThan);
209}
210
211/// Returns true if lhs < rhs, false otherwise
212pub fn lessThan(comptime T: type, lhs: []const T, rhs: []const T) bool {
213 var result = compare(T, lhs, rhs);
214 if (result == Compare.LessThan) {
215 return true;
216 } else
217 return false;
188218}
189219
190220test "mem.lessThan" {