commit 447dc2bb9011078e80acbe3f51135ff1ad2bf163 (tree)
parent c45ba49b8b6e8abeb2e96d28860273247e61ab18
Author: Yuri Pieters <magejohnyjtp@gmail.com>
Date: Thu, 9 Apr 2020 01:49:42 +0100
sort.binarySearch: fix integer underflow (#4980)
When the key was smaller than any value in the array, an error was
ocurring with the mid being zero and having 1 subtracted from it.
Diffstat:
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/lib/std/sort.zig b/lib/std/sort.zig
@@ -10,16 +10,16 @@ pub fn binarySearch(comptime T: type, key: T, items: []const T, comptime compare
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,
}
}