authorgravatar for magejohnyjtp@gmail.comYuri Pieters <magejohnyjtp@gmail.com> 2020-04-09 01:49:42+01:00
committergravatar for magejohnyjtp@gmail.comYuri Pieters <magejohnyjtp@gmail.com> 2020-04-09 01:58:57+01:00
log447dc2bb9011078e80acbe3f51135ff1ad2bf163
treeba5f2446a0197bc5030e16a5fe21072abc667232
parentc45ba49b8b6e8abeb2e96d28860273247e61ab18

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.

1 files changed, 3 insertions(+), 3 deletions(-)

lib/std/sort.zig+3-3
...@@ -10,16 +10,16 @@ pub fn binarySearch(comptime T: type, key: T, items: []const T, comptime compare...@@ -10,16 +10,16 @@ pub fn binarySearch(comptime T: type, key: T, items: []const T, comptime compare
10 return null;10 return null;
1111
12 var left: usize = 0;12 var left: usize = 0;
13 var right: usize = items.len - 1;13 var right: usize = items.len;
1414
15 while (left <= right) {15 while (left < right) {
16 // Avoid overflowing in the midpoint calculation16 // Avoid overflowing in the midpoint calculation
17 const mid = left + (right - left) / 2;17 const mid = left + (right - left) / 2;
18 // Compare the key with the midpoint element18 // Compare the key with the midpoint element
19 switch (compareFn(key, items[mid])) {19 switch (compareFn(key, items[mid])) {
20 .eq => return mid,20 .eq => return mid,
21 .gt => left = mid + 1,21 .gt => left = mid + 1,
22 .lt => right = mid - 1,22 .lt => right = mid,
23 }23 }
24 }24 }
2525