File tree 1 file changed +11
-12
lines changed
1 file changed +11
-12
lines changed Original file line number Diff line number Diff line change 1
1
//! Comparison traits for `[T]`.
2
2
3
- use crate :: cmp;
4
- use crate :: cmp:: Ordering :: { self , Greater , Less } ;
3
+ use crate :: cmp:: { self , Ordering } ;
5
4
use crate :: mem;
6
5
7
6
use super :: from_raw_parts;
@@ -189,18 +188,18 @@ impl<A: Ord> SliceOrd for A {
189
188
impl SliceOrd for u8 {
190
189
#[ inline]
191
190
fn compare ( left : & [ Self ] , right : & [ Self ] ) -> Ordering {
192
- let order =
193
- // SAFETY: `left` and `right` are references and are thus guaranteed to be valid.
194
- // We use the minimum of both lengths which guarantees that both regions are
195
- // valid for reads in that interval.
196
- unsafe { memcmp ( left. as_ptr ( ) , right. as_ptr ( ) , cmp:: min ( left. len ( ) , right. len ( ) ) ) } ;
191
+ // Since the length of a slice is always less than or equal to isize::MAX, this never underflows.
192
+ let diff = left. len ( ) as isize - right. len ( ) as isize ;
193
+ // This comparison gets optimized away (on x86_64 and ARM) because the subtraction updates flags.
194
+ let len = if left. len ( ) < right. len ( ) { left. len ( ) } else { right. len ( ) } ;
195
+ // SAFETY: `left` and `right` are references and are thus guaranteed to be valid.
196
+ // We use the minimum of both lengths which guarantees that both regions are
197
+ // valid for reads in that interval.
198
+ let mut order = unsafe { memcmp ( left. as_ptr ( ) , right. as_ptr ( ) , len) as isize } ;
197
199
if order == 0 {
198
- left. len ( ) . cmp ( & right. len ( ) )
199
- } else if order < 0 {
200
- Less
201
- } else {
202
- Greater
200
+ order = diff;
203
201
}
202
+ order. cmp ( & 0 )
204
203
}
205
204
}
206
205
You can’t perform that action at this time.
0 commit comments