Skip to content

Commit 0cc5c97

Browse files
committed
A more efficient slice comparison implementation for T: !BytewiseEq
The previous implementation was not optimized properly by the compiler, which didn't leverage the fact that both length were equal.
1 parent 347452e commit 0cc5c97

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

library/core/src/slice/cmp.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,24 @@ where
6060
return false;
6161
}
6262

63-
self.iter().zip(other.iter()).all(|(x, y)| x == y)
63+
let mut i = self.len();
64+
let mut ptr_self = self.as_ptr();
65+
let mut ptr_other = other.as_ptr();
66+
// SAFETY:
67+
// This is sound because:
68+
// - self.len == other.len
69+
// - self.len <= isize::MAX
70+
// so the two pointers will not overflow,
71+
// will remain in bounds of the slice,
72+
// and dereferencing them is sound.
73+
unsafe {
74+
while (i > 0) && (*ptr_self == *ptr_other) {
75+
i -= 1;
76+
ptr_self = ptr_self.add(1);
77+
ptr_other = ptr_other.add(1);
78+
}
79+
}
80+
i == 0
6481
}
6582
}
6683

0 commit comments

Comments
 (0)