Merge pull request #4982 from MageJohn/fix/binarySearch

sort.binarySearch: fix integer underflow (#4980)
This commit is contained in:
Andrew Kelley 2020-04-09 14:58:07 -04:00 committed by GitHub
commit 543031db35
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -6,20 +6,17 @@ const math = std.math;
const builtin = @import("builtin");
pub fn binarySearch(comptime T: type, key: T, items: []const T, comptime compareFn: fn (lhs: T, rhs: T) math.Order) ?usize {
if (items.len < 1)
return null;
var left: usize = 0;
var right: usize = items.len - 1;
var right: usize = items.len;
while (left <= right) {
while (left < right) {
// Avoid overflowing in the midpoint calculation
const mid = left + (right - left) / 2;
// Compare the key with the midpoint element
switch (compareFn(key, items[mid])) {
.eq => return mid,
.gt => left = mid + 1,
.lt => right = mid - 1,
.lt => right = mid,
}
}
@ -47,6 +44,10 @@ test "std.sort.binarySearch" {
@as(?usize, null),
binarySearch(u32, 1, &[_]u32{0}, S.order_u32),
);
testing.expectEqual(
@as(?usize, null),
binarySearch(u32, 0, &[_]u32{1}, S.order_u32),
);
testing.expectEqual(
@as(?usize, 4),
binarySearch(u32, 5, &[_]u32{ 1, 2, 3, 4, 5 }, S.order_u32),