Skip to content

Commit 30b27f3

Browse files
committed
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.
1 parent 7f90abe commit 30b27f3

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/libcore/slice/mod.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -5304,6 +5304,29 @@ impl<A, B> SlicePartialEq<B> for [A]
53045304
}
53055305
}
53065306

5307+
// Use an equal-pointer optimization when types are `Eq`
5308+
impl<A> SlicePartialEq<A> for [A]
5309+
where A: PartialEq<A> + Eq
5310+
{
5311+
default fn equal(&self, other: &[A]) -> bool {
5312+
if self.len() != other.len() {
5313+
return false;
5314+
}
5315+
5316+
if self.as_ptr() == other.as_ptr() {
5317+
return true;
5318+
}
5319+
5320+
for i in 0..self.len() {
5321+
if !self[i].eq(&other[i]) {
5322+
return false;
5323+
}
5324+
}
5325+
5326+
true
5327+
}
5328+
}
5329+
53075330
// Use memcmp for bytewise equality when the types allow
53085331
impl<A> SlicePartialEq<A> for [A]
53095332
where A: PartialEq<A> + BytewiseEquality
@@ -5409,7 +5432,7 @@ impl SliceOrd<u8> for [u8] {
54095432
#[doc(hidden)]
54105433
/// Trait implemented for types that can be compared for equality using
54115434
/// their bytewise representation
5412-
trait BytewiseEquality { }
5435+
trait BytewiseEquality: Eq + Copy { }
54135436

54145437
macro_rules! impl_marker_for {
54155438
($traitname:ident, $($ty:ty)*) => {

0 commit comments

Comments
 (0)