Skip to content

Commit be64090

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 d8899c5 commit be64090

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
@@ -70,7 +70,24 @@ where
7070
return false;
7171
}
7272

73-
self.iter().zip(other.iter()).all(|(x, y)| x == y)
73+
let mut i = self.len();
74+
let mut ptr_self = self.as_ptr();
75+
let mut ptr_other = other.as_ptr();
76+
// SAFETY:
77+
// This is sound because:
78+
// - self.len == other.len
79+
// - self.len <= isize::MAX
80+
// so the two pointers will not overflow,
81+
// will remain in bounds of the slice,
82+
// and dereferencing them is sound.
83+
unsafe {
84+
while (i > 0) && (*ptr_self == *ptr_other) {
85+
i -= 1;
86+
ptr_self = ptr_self.add(1);
87+
ptr_other = ptr_other.add(1);
88+
}
89+
}
90+
i == 0
7491
}
7592
}
7693

0 commit comments

Comments
 (0)