diff options
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/alloc.rs | 7 | ||||
| -rw-r--r-- | src/libcore/cmp.rs | 12 | ||||
| -rw-r--r-- | src/libcore/tests/cmp.rs | 8 |
3 files changed, 24 insertions, 3 deletions
diff --git a/src/libcore/alloc.rs b/src/libcore/alloc.rs index 4cfd6527deb..5c24e3d8f5d 100644 --- a/src/libcore/alloc.rs +++ b/src/libcore/alloc.rs @@ -239,8 +239,11 @@ impl Layout { #[unstable(feature = "alloc_layout_extra", issue = "55724")] #[inline] pub fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutErr> { - let padded_size = self.size().checked_add(self.padding_needed_for(self.align())) - .ok_or(LayoutErr { private: () })?; + // This cannot overflow. Quoting from the invariant of Layout: + // > `size`, when rounded up to the nearest multiple of `align`, + // > must not overflow (i.e., the rounded value must be less than + // > `usize::MAX`) + let padded_size = self.size() + self.padding_needed_for(self.align()); let alloc_size = padded_size.checked_mul(n) .ok_or(LayoutErr { private: () })?; diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index a5f355cd9a7..fd4be02e20f 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -1005,6 +1005,7 @@ pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T { // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types mod impls { + use crate::hint::unreachable_unchecked; use crate::cmp::Ordering::{self, Less, Greater, Equal}; macro_rules! partial_eq_impl { @@ -1125,7 +1126,16 @@ mod impls { impl Ord for bool { #[inline] fn cmp(&self, other: &bool) -> Ordering { - (*self as u8).cmp(&(*other as u8)) + // Casting to i8's and converting the difference to an Ordering generates + // more optimal assembly. + // See <https://github.com/rust-lang/rust/issues/66780> for more info. + match (*self as i8) - (*other as i8) { + -1 => Less, + 0 => Equal, + 1 => Greater, + // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else + _ => unsafe { unreachable_unchecked() }, + } } } diff --git a/src/libcore/tests/cmp.rs b/src/libcore/tests/cmp.rs index 5e6778e222a..56a2f4acf6e 100644 --- a/src/libcore/tests/cmp.rs +++ b/src/libcore/tests/cmp.rs @@ -10,6 +10,14 @@ fn test_int_totalord() { } #[test] +fn test_bool_totalord() { + assert_eq!(true.cmp(&false), Greater); + assert_eq!(false.cmp(&true), Less); + assert_eq!(true.cmp(&true), Equal); + assert_eq!(false.cmp(&false), Equal); +} + +#[test] fn test_mut_int_totalord() { assert_eq!((&mut 5).cmp(&&mut 10), Less); assert_eq!((&mut 10).cmp(&&mut 5), Greater); |
