From 30b27f350ccca8f2b08b54b256f7e1fdb8c8ddb0 Mon Sep 17 00:00:00 2001 From: Andrew Champion Date: Sat, 8 Jun 2019 16:26:34 +0100 Subject: [PATCH 1/2] core: check for pointer equality when comparing Eq slices Because Eq types must be reflexively equal, an equal-length slice to the same memory location must be equal. --- src/libcore/slice/mod.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 0e782bef39dd8..f972d13f7c391 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -5304,6 +5304,29 @@ impl SlicePartialEq for [A] } } +// Use an equal-pointer optimization when types are `Eq` +impl SlicePartialEq for [A] + where A: PartialEq + Eq +{ + default fn equal(&self, other: &[A]) -> bool { + if self.len() != other.len() { + return false; + } + + if self.as_ptr() == other.as_ptr() { + return true; + } + + for i in 0..self.len() { + if !self[i].eq(&other[i]) { + return false; + } + } + + true + } +} + // Use memcmp for bytewise equality when the types allow impl SlicePartialEq for [A] where A: PartialEq + BytewiseEquality @@ -5409,7 +5432,7 @@ impl SliceOrd for [u8] { #[doc(hidden)] /// Trait implemented for types that can be compared for equality using /// their bytewise representation -trait BytewiseEquality { } +trait BytewiseEquality: Eq + Copy { } macro_rules! impl_marker_for { ($traitname:ident, $($ty:ty)*) => { From d482589f292abda9a5c2895adf63189168f92a70 Mon Sep 17 00:00:00 2001 From: Andrew Champion Date: Sat, 8 Jun 2019 20:16:50 +0100 Subject: [PATCH 2/2] core: use iterators for slice equality comparison --- src/libcore/slice/mod.rs | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index f972d13f7c391..ea4ea956e59a8 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -5294,13 +5294,7 @@ impl SlicePartialEq for [A] return false; } - for i in 0..self.len() { - if !self[i].eq(&other[i]) { - return false; - } - } - - true + self.iter().zip(other.iter()).all(|(x, y)| x == y) } } @@ -5317,13 +5311,7 @@ impl SlicePartialEq for [A] return true; } - for i in 0..self.len() { - if !self[i].eq(&other[i]) { - return false; - } - } - - true + self.iter().zip(other.iter()).all(|(x, y)| x == y) } }