Skip to main content

core/slice/
cmp.rs

1//! Comparison traits for `[T]`.
2
3use super::{from_raw_parts, memchr};
4use crate::ascii;
5use crate::cmp::{self, BytewiseEq, Ordering};
6use crate::intrinsics::compare_bytes;
7use crate::marker::Destruct;
8use crate::mem::{SizedTypeProperties, transmute_copy};
9use crate::num::NonZero;
10use crate::ops::ControlFlow;
11
12#[stable(feature = "rust1", since = "1.0.0")]
13#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
14const impl<T, U> PartialEq<[U]> for [T]
15where
16    T: [const] PartialEq<U>,
17{
18    #[inline]
19    fn eq(&self, other: &[U]) -> bool {
20        let len = self.len();
21        if len == other.len() {
22            // SAFETY: Just checked that they're the same length, and the pointers
23            // come from references-to-slices so they're guaranteed readable.
24            unsafe { SlicePartialEq::equal_same_length(self.as_ptr(), other.as_ptr(), len) }
25        } else {
26            false
27        }
28    }
29}
30
31#[stable(feature = "rust1", since = "1.0.0")]
32#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
33const impl<T: [const] Eq> Eq for [T] {}
34
35/// Implements comparison of slices [lexicographically](Ord#lexicographical-comparison).
36#[stable(feature = "rust1", since = "1.0.0")]
37#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
38const impl<T: [const] Ord> Ord for [T] {
39    fn cmp(&self, other: &[T]) -> Ordering {
40        SliceOrd::compare(self, other)
41    }
42}
43
44#[inline]
45const fn as_underlying(x: ControlFlow<bool>) -> u8 {
46    // SAFETY: This will only compile if `bool` and `ControlFlow<bool>` have the same
47    // size (which isn't guaranteed but this is libcore). Because they have the same
48    // size, it's a niched implementation, which in one byte means there can't be
49    // any uninitialized memory. The callers then only check for `0` or `1` from this,
50    // which must necessarily match the `Break` variant, and we're fine no matter
51    // what ends up getting picked as the value representing `Continue(())`.
52    unsafe { crate::mem::transmute(x) }
53}
54
55/// Implements comparison of slices [lexicographically](Ord#lexicographical-comparison).
56#[stable(feature = "rust1", since = "1.0.0")]
57#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
58const impl<T: [const] PartialOrd> PartialOrd for [T] {
59    #[inline]
60    fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
61        SlicePartialOrd::partial_compare(self, other)
62    }
63    #[inline]
64    fn lt(&self, other: &Self) -> bool {
65        // This is certainly not the obvious way to implement these methods.
66        // Unfortunately, using anything that looks at the discriminant means that
67        // LLVM sees a check for `2` (aka `ControlFlow<bool>::Continue(())`) and
68        // gets very distracted by that, ending up generating extraneous code.
69        // This should be changed to something simpler once either LLVM is smarter,
70        // see <https://github.com/llvm/llvm-project/issues/132678>, or we generate
71        // niche discriminant checks in a way that doesn't trigger it.
72
73        as_underlying(self.__chaining_less(other)) == 1
74    }
75    #[inline]
76    fn le(&self, other: &Self) -> bool {
77        as_underlying(self.__chaining_less(other)) != 0
78    }
79    #[inline]
80    fn gt(&self, other: &Self) -> bool {
81        as_underlying(self.__chaining_greater(other)) == 1
82    }
83    #[inline]
84    fn ge(&self, other: &Self) -> bool {
85        as_underlying(self.__chaining_greater(other)) != 0
86    }
87    #[inline]
88    fn __chaining_less(&self, other: &Self) -> ControlFlow<bool> {
89        SliceChain::chaining_less(self, other)
90    }
91    #[inline]
92    fn __chaining_greater(&self, other: &Self) -> ControlFlow<bool> {
93        SliceChain::chaining_greater(self, other)
94    }
95}
96
97#[doc(hidden)]
98// intermediate trait for specialization of slice's PartialEq
99#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
100const trait SlicePartialEq<B> {
101    /// # Safety
102    /// `lhs` and `rhs` are both readable for `len` elements
103    unsafe fn equal_same_length(lhs: *const Self, rhs: *const B, len: usize) -> bool;
104}
105
106// Generic slice equality
107#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
108const impl<A, B> SlicePartialEq<B> for A
109where
110    A: [const] PartialEq<B>,
111{
112    // It's not worth trying to inline the loops underneath here *in MIR*,
113    // and preventing it encourages more useful inlining upstream,
114    // such as in `<str as PartialEq>::eq`.
115    // The codegen backend can still inline it later if needed.
116    #[rustc_no_mir_inline]
117    default unsafe fn equal_same_length(lhs: *const Self, rhs: *const B, len: usize) -> bool {
118        // Implemented as explicit indexing rather
119        // than zipped iterators for performance reasons.
120        // See PR https://github.com/rust-lang/rust/pull/116846
121        // FIXME(const_hack): make this a `for idx in 0..len` loop.
122        let mut idx = 0;
123        while idx < len {
124            // SAFETY: idx < len, so both are in-bounds and readable
125            if unsafe { *lhs.add(idx) != *rhs.add(idx) } {
126                return false;
127            }
128            idx += 1;
129        }
130
131        true
132    }
133}
134
135// When each element can be compared byte-wise, we can compare all the bytes
136// from the whole size in one call to the intrinsics.
137#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
138const impl<A, B> SlicePartialEq<B> for A
139where
140    A: [const] BytewiseEq<B>,
141{
142    #[inline]
143    unsafe fn equal_same_length(lhs: *const Self, rhs: *const B, len: usize) -> bool {
144        // SAFETY: by our precondition, `lhs` and `rhs` are guaranteed to be valid
145        // for reading `len` values, which also means the size is guaranteed
146        // not to overflow because it exists in memory;
147        unsafe {
148            let size = crate::intrinsics::unchecked_mul(len, Self::SIZE);
149            compare_bytes(lhs as _, rhs as _, size) == 0
150        }
151    }
152}
153
154#[doc(hidden)]
155#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
156// intermediate trait for specialization of slice's PartialOrd
157const trait SlicePartialOrd: Sized {
158    fn partial_compare(left: &[Self], right: &[Self]) -> Option<Ordering>;
159}
160
161#[doc(hidden)]
162#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
163// intermediate trait for specialization of slice's PartialOrd chaining methods
164const trait SliceChain: Sized {
165    fn chaining_less(left: &[Self], right: &[Self]) -> ControlFlow<bool>;
166    fn chaining_greater(left: &[Self], right: &[Self]) -> ControlFlow<bool>;
167}
168
169type AlwaysBreak<B> = ControlFlow<B, !>;
170
171#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
172const impl<A: [const] PartialOrd> SlicePartialOrd for A {
173    default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
174        let elem_chain = const |a, b| match PartialOrd::partial_cmp(a, b) {
175            Some(Ordering::Equal) => ControlFlow::Continue(()),
176            non_eq => ControlFlow::Break(non_eq),
177        };
178
179        let len_chain = const |a: &_, b: &_| ControlFlow::Break(usize::partial_cmp(a, b));
180
181        let AlwaysBreak::Break(b) = chaining_impl(left, right, elem_chain, len_chain);
182        b
183    }
184}
185
186#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
187const impl<A: [const] PartialOrd> SliceChain for A {
188    default fn chaining_less(left: &[Self], right: &[Self]) -> ControlFlow<bool> {
189        chaining_impl(left, right, PartialOrd::__chaining_less, usize::__chaining_less)
190    }
191    default fn chaining_greater(left: &[Self], right: &[Self]) -> ControlFlow<bool> {
192        chaining_impl(left, right, PartialOrd::__chaining_greater, usize::__chaining_greater)
193    }
194}
195
196#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
197#[inline]
198const fn chaining_impl<'l, 'r, A: PartialOrd, B, C>(
199    left: &'l [A],
200    right: &'r [A],
201    elem_chain: impl [const] Fn(&'l A, &'r A) -> ControlFlow<B> + [const] Destruct,
202    len_chain: impl for<'a> [const] FnOnce(&'a usize, &'a usize) -> ControlFlow<B, C> + [const] Destruct,
203) -> ControlFlow<B, C> {
204    let l = cmp::min(left.len(), right.len());
205
206    // Slice to the loop iteration range to enable bound check
207    // elimination in the compiler
208    let lhs = &left[..l];
209    let rhs = &right[..l];
210
211    // FIXME(const-hack): revert this to `for i in 0..l` once `impl const Iterator for Range<T>`
212    let mut i: usize = 0;
213    while i < l {
214        elem_chain(&lhs[i], &rhs[i])?;
215        i += 1;
216    }
217
218    len_chain(&left.len(), &right.len())
219}
220
221// This is the impl that we would like to have. Unfortunately it's not sound.
222// See `partial_ord_slice.rs`.
223/*
224impl<A> SlicePartialOrd for A
225where
226    A: Ord,
227{
228    default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
229        Some(SliceOrd::compare(left, right))
230    }
231}
232*/
233
234#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
235const impl<A: [const] AlwaysApplicableOrd> SlicePartialOrd for A {
236    fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
237        Some(SliceOrd::compare(left, right))
238    }
239}
240
241#[rustc_specialization_trait]
242#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
243const trait AlwaysApplicableOrd: [const] SliceOrd + [const] Ord {}
244
245macro_rules! always_applicable_ord {
246    ($([$($p:tt)*] $t:ty,)*) => {
247        $(impl<$($p)*> AlwaysApplicableOrd for $t {})*
248    }
249}
250
251always_applicable_ord! {
252    [] u8, [] u16, [] u32, [] u64, [] u128, [] usize,
253    [] i8, [] i16, [] i32, [] i64, [] i128, [] isize,
254    [] bool, [] char,
255    [T: ?Sized] *const T, [T: ?Sized] *mut T,
256    [T: AlwaysApplicableOrd] &T,
257    [T: AlwaysApplicableOrd] &mut T,
258    [T: AlwaysApplicableOrd] Option<T>,
259}
260
261#[doc(hidden)]
262#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
263// intermediate trait for specialization of slice's Ord
264const trait SliceOrd: Sized {
265    fn compare(left: &[Self], right: &[Self]) -> Ordering;
266}
267
268#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
269const impl<A: [const] Ord> SliceOrd for A {
270    default fn compare(left: &[Self], right: &[Self]) -> Ordering {
271        let elem_chain = const |a, b| match Ord::cmp(a, b) {
272            Ordering::Equal => ControlFlow::Continue(()),
273            non_eq => ControlFlow::Break(non_eq),
274        };
275
276        let len_chain = const |a: &_, b: &_| ControlFlow::Break(usize::cmp(a, b));
277
278        let AlwaysBreak::Break(b) = chaining_impl(left, right, elem_chain, len_chain);
279        b
280    }
281}
282
283/// Marks that a type should be treated as an unsigned byte for comparisons.
284///
285/// # Safety
286/// * The type must be readable as an `u8`, meaning it has to have the same
287///   layout as `u8` and always be initialized.
288/// * For every `x` and `y` of this type, `Ord(x, y)` must return the same
289///   value as `Ord::cmp(transmute::<_, u8>(x), transmute::<_, u8>(y))`.
290#[rustc_specialization_trait]
291const unsafe trait UnsignedBytewiseOrd: [const] Ord {}
292
293#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
294const unsafe impl UnsignedBytewiseOrd for bool {}
295#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
296const unsafe impl UnsignedBytewiseOrd for u8 {}
297#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
298const unsafe impl UnsignedBytewiseOrd for NonZero<u8> {}
299#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
300const unsafe impl UnsignedBytewiseOrd for Option<NonZero<u8>> {}
301#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
302const unsafe impl UnsignedBytewiseOrd for ascii::Char {}
303
304// `compare_bytes` compares a sequence of unsigned bytes lexicographically, so
305// use it if the requirements for `UnsignedBytewiseOrd` are fulfilled.
306#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
307const impl<A: [const] Ord + [const] UnsignedBytewiseOrd> SliceOrd for A {
308    #[inline]
309    fn compare(left: &[Self], right: &[Self]) -> Ordering {
310        // Since the length of a slice is always less than or equal to
311        // isize::MAX, this never underflows.
312        let diff = left.len() as isize - right.len() as isize;
313        // This comparison gets optimized away (on x86_64 and ARM) because the
314        // subtraction updates flags.
315        let len = if left.len() < right.len() { left.len() } else { right.len() };
316        let left = left.as_ptr().cast();
317        let right = right.as_ptr().cast();
318        // SAFETY: `left` and `right` are references and are thus guaranteed to
319        // be valid. `UnsignedBytewiseOrd` is only implemented for types that
320        // are valid u8s and can be compared the same way. We use the minimum
321        // of both lengths which guarantees that both regions are valid for
322        // reads in that interval.
323        let mut order = unsafe { compare_bytes(left, right, len) as isize };
324        if order == 0 {
325            order = diff;
326        }
327        order.cmp(&0)
328    }
329}
330
331// Don't generate our own chaining loops for `memcmp`-able things either.
332
333#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
334const impl<A: [const] PartialOrd + [const] UnsignedBytewiseOrd> SliceChain for A {
335    #[inline]
336    fn chaining_less(left: &[Self], right: &[Self]) -> ControlFlow<bool> {
337        match SliceOrd::compare(left, right) {
338            Ordering::Equal => ControlFlow::Continue(()),
339            ne => ControlFlow::Break(ne.is_lt()),
340        }
341    }
342    #[inline]
343    fn chaining_greater(left: &[Self], right: &[Self]) -> ControlFlow<bool> {
344        match SliceOrd::compare(left, right) {
345            Ordering::Equal => ControlFlow::Continue(()),
346            ne => ControlFlow::Break(ne.is_gt()),
347        }
348    }
349}
350
351pub(super) trait SliceContains: Sized {
352    fn slice_contains(&self, x: &[Self]) -> bool;
353}
354
355impl<T> SliceContains for T
356where
357    T: PartialEq,
358{
359    #[expect(clippy::manual_contains, reason = "implements slice_contains")]
360    default fn slice_contains(&self, x: &[Self]) -> bool {
361        x.iter().any(|y| *y == *self)
362    }
363}
364
365impl<T: BytewiseEq> SliceContains for T {
366    #[inline]
367    #[expect(clippy::manual_contains, reason = "implements slice_contains")]
368    default fn slice_contains(&self, x: &[Self]) -> bool {
369        if size_of::<T>() == 1 {
370            // SAFETY: `BytewiseEq` guarantees that values have no padding or provenance and
371            // compare like their underlying bytes. Since `T` is one byte, both the value and
372            // slice can be read as `u8`s.
373            let (byte, bytes) = unsafe {
374                (transmute_copy::<T, u8>(self), from_raw_parts(x.as_ptr().cast::<u8>(), x.len()))
375            };
376            memchr::memchr(byte, bytes).is_some()
377        } else {
378            x.iter().any(|y| *y == *self)
379        }
380    }
381}
382
383macro_rules! impl_slice_contains {
384    ($($t:ty),*) => {
385        $(
386            impl SliceContains for $t {
387                #[inline]
388                fn slice_contains(&self, arr: &[$t]) -> bool {
389                    // Make our LANE_COUNT 4x the normal lane count (aiming for 128 bit vectors).
390                    // The compiler will nicely unroll it.
391                    const LANE_COUNT: usize = 4 * (128 / (size_of::<$t>() * 8));
392                    // SIMD
393                    let mut chunks = arr.chunks_exact(LANE_COUNT);
394                    for chunk in &mut chunks {
395                        if chunk.iter().fold(false, |acc, x| acc | (*x == *self)) {
396                            return true;
397                        }
398                    }
399                    // Scalar remainder
400                    return chunks.remainder().iter().any(|x| *x == *self);
401                }
402            }
403        )*
404    };
405}
406
407impl_slice_contains!(u16, u32, u64, i16, i32, i64, f32, f64, usize, isize, char);