Skip to content

Commit

Permalink
core: check for pointer equality when comparing Eq slices
Browse files Browse the repository at this point in the history
Because Eq types must be reflexively equal, an equal-length slice to the
same memory location must be equal.
  • Loading branch information
aschampion committed Jun 8, 2019
1 parent 7f90abe commit 30b27f3
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/libcore/slice/mod.rs
Expand Up @@ -5304,6 +5304,29 @@ impl<A, B> SlicePartialEq<B> for [A]
}
}

// Use an equal-pointer optimization when types are `Eq`
impl<A> SlicePartialEq<A> for [A]
where A: PartialEq<A> + 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<A> SlicePartialEq<A> for [A]
where A: PartialEq<A> + BytewiseEquality
Expand Down Expand Up @@ -5409,7 +5432,7 @@ impl SliceOrd<u8> 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)*) => {
Expand Down

0 comments on commit 30b27f3

Please sign in to comment.