Skip to content

Commit

Permalink
Merge pull request #4982 from MageJohn/fix/binarySearch
Browse files Browse the repository at this point in the history
 sort.binarySearch: fix integer underflow (#4980)
  • Loading branch information
andrewrk authored Apr 9, 2020
2 parents f1360be + f5f7708 commit 543031d
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions lib/std/sort.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}

Expand Down Expand Up @@ -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),
Expand Down

0 comments on commit 543031d

Please sign in to comment.