File tree 2 files changed +19
-3
lines changed
2 files changed +19
-3
lines changed Original file line number Diff line number Diff line change @@ -2154,11 +2154,12 @@ impl<T> [T] {
2154
2154
where
2155
2155
F : FnMut ( & ' a T ) -> Ordering ,
2156
2156
{
2157
+ let mut size = self . len ( ) ;
2157
2158
let mut left = 0 ;
2158
- let mut right = self . len ( ) ;
2159
+ let mut right = size ;
2159
2160
while left < right {
2160
- // never overflow because `slice::len()` max is `isize::MAX`.
2161
- let mid = ( left + right ) / 2 ;
2161
+ let mid = left + size / 2 ;
2162
+
2162
2163
// SAFETY: the call is made safe by the following invariants:
2163
2164
// - `mid >= 0`
2164
2165
// - `mid < size`: `mid` is limited by `[left; right)` bound.
@@ -2174,6 +2175,8 @@ impl<T> [T] {
2174
2175
} else {
2175
2176
return Ok ( mid) ;
2176
2177
}
2178
+
2179
+ size = right - left;
2177
2180
}
2178
2181
Err ( left)
2179
2182
}
Original file line number Diff line number Diff line change 1
1
use core:: cell:: Cell ;
2
+ use core:: cmp:: Ordering ;
2
3
use core:: result:: Result :: { Err , Ok } ;
3
4
4
5
#[ test]
@@ -64,6 +65,17 @@ fn test_binary_search() {
64
65
assert_eq ! ( b. binary_search( & 6 ) , Err ( 4 ) ) ;
65
66
assert_eq ! ( b. binary_search( & 7 ) , Ok ( 4 ) ) ;
66
67
assert_eq ! ( b. binary_search( & 8 ) , Err ( 5 ) ) ;
68
+
69
+ let b = [ ( ) ; usize:: MAX ] ;
70
+ assert_eq ! ( b. binary_search( & ( ) ) , Ok ( usize :: MAX / 2 ) ) ;
71
+ }
72
+
73
+ #[ test]
74
+ fn test_binary_search_by_overflow ( ) {
75
+ let b = [ ( ) ; usize:: MAX ] ;
76
+ assert_eq ! ( b. binary_search_by( |_| Ordering :: Equal ) , Ok ( usize :: MAX / 2 ) ) ;
77
+ assert_eq ! ( b. binary_search_by( |_| Ordering :: Greater ) , Err ( 0 ) ) ;
78
+ assert_eq ! ( b. binary_search_by( |_| Ordering :: Less ) , Err ( usize :: MAX ) ) ;
67
79
}
68
80
69
81
#[ test]
@@ -1982,6 +1994,7 @@ fn test_copy_within_panics_dest_too_long() {
1982
1994
// The length is only 13, so a slice of length 4 starting at index 10 is out of bounds.
1983
1995
bytes. copy_within ( 0 ..4 , 10 ) ;
1984
1996
}
1997
+
1985
1998
#[ test]
1986
1999
#[ should_panic( expected = "slice index starts at 2 but ends at 1" ) ]
1987
2000
fn test_copy_within_panics_src_inverted ( ) {
You can’t perform that action at this time.
0 commit comments