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        for idx in 0..len {
122            // SAFETY: idx < len, so both are in-bounds and readable
123            if unsafe { *lhs.add(idx) != *rhs.add(idx) } {
124                return false;
125            }
126        }
127
128        true
129    }
130}
131
132// When each element can be compared byte-wise, we can compare all the bytes
133// from the whole size in one call to the intrinsics.
134#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
135const impl<A, B> SlicePartialEq<B> for A
136where
137    A: [const] BytewiseEq<B>,
138{
139    #[inline]
140    unsafe fn equal_same_length(lhs: *const Self, rhs: *const B, len: usize) -> bool {
141        // SAFETY: by our precondition, `lhs` and `rhs` are guaranteed to be valid
142        // for reading `len` values, which also means the size is guaranteed
143        // not to overflow because it exists in memory;
144        unsafe {
145            let size = crate::intrinsics::unchecked_mul(len, Self::SIZE);
146            compare_bytes(lhs as _, rhs as _, size) == 0
147        }
148    }
149}
150
151#[doc(hidden)]
152#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
153// intermediate trait for specialization of slice's PartialOrd
154const trait SlicePartialOrd: Sized {
155    fn partial_compare(left: &[Self], right: &[Self]) -> Option<Ordering>;
156}
157
158#[doc(hidden)]
159#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
160// intermediate trait for specialization of slice's PartialOrd chaining methods
161const trait SliceChain: Sized {
162    fn chaining_less(left: &[Self], right: &[Self]) -> ControlFlow<bool>;
163    fn chaining_greater(left: &[Self], right: &[Self]) -> ControlFlow<bool>;
164}
165
166type AlwaysBreak<B> = ControlFlow<B, !>;
167
168#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
169const impl<A: [const] PartialOrd> SlicePartialOrd for A {
170    default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
171        let elem_chain = const |a, b| match PartialOrd::partial_cmp(a, b) {
172            Some(Ordering::Equal) => ControlFlow::Continue(()),
173            non_eq => ControlFlow::Break(non_eq),
174        };
175
176        let len_chain = const |a: &_, b: &_| ControlFlow::Break(usize::partial_cmp(a, b));
177
178        let AlwaysBreak::Break(b) = chaining_impl(left, right, elem_chain, len_chain);
179        b
180    }
181}
182
183#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
184const impl<A: [const] PartialOrd> SliceChain for A {
185    default fn chaining_less(left: &[Self], right: &[Self]) -> ControlFlow<bool> {
186        chaining_impl(left, right, PartialOrd::__chaining_less, usize::__chaining_less)
187    }
188    default fn chaining_greater(left: &[Self], right: &[Self]) -> ControlFlow<bool> {
189        chaining_impl(left, right, PartialOrd::__chaining_greater, usize::__chaining_greater)
190    }
191}
192
193#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
194#[inline]
195const fn chaining_impl<'l, 'r, A: PartialOrd, B, C>(
196    left: &'l [A],
197    right: &'r [A],
198    elem_chain: impl [const] Fn(&'l A, &'r A) -> ControlFlow<B> + [const] Destruct,
199    len_chain: impl for<'a> [const] FnOnce(&'a usize, &'a usize) -> ControlFlow<B, C> + [const] Destruct,
200) -> ControlFlow<B, C> {
201    let l = cmp::min(left.len(), right.len());
202
203    // Slice to the loop iteration range to enable bound check
204    // elimination in the compiler
205    let lhs = &left[..l];
206    let rhs = &right[..l];
207
208    for i in 0..l {
209        elem_chain(&lhs[i], &rhs[i])?;
210    }
211
212    len_chain(&left.len(), &right.len())
213}
214
215// This is the impl that we would like to have. Unfortunately it's not sound.
216// See `partial_ord_slice.rs`.
217/*
218impl<A> SlicePartialOrd for A
219where
220    A: Ord,
221{
222    default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
223        Some(SliceOrd::compare(left, right))
224    }
225}
226*/
227
228#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
229const impl<A: [const] AlwaysApplicableOrd> SlicePartialOrd for A {
230    fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
231        Some(SliceOrd::compare(left, right))
232    }
233}
234
235#[rustc_specialization_trait]
236#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
237const trait AlwaysApplicableOrd: [const] SliceOrd + [const] Ord {}
238
239macro_rules! always_applicable_ord {
240    ($([$($p:tt)*] $t:ty,)*) => {
241        $(impl<$($p)*> AlwaysApplicableOrd for $t {})*
242    }
243}
244
245always_applicable_ord! {
246    [] u8, [] u16, [] u32, [] u64, [] u128, [] usize,
247    [] i8, [] i16, [] i32, [] i64, [] i128, [] isize,
248    [] bool, [] char,
249    [T: ?Sized] *const T, [T: ?Sized] *mut T,
250    [T: AlwaysApplicableOrd] &T,
251    [T: AlwaysApplicableOrd] &mut T,
252    [T: AlwaysApplicableOrd] Option<T>,
253}
254
255#[doc(hidden)]
256#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
257// intermediate trait for specialization of slice's Ord
258const trait SliceOrd: Sized {
259    fn compare(left: &[Self], right: &[Self]) -> Ordering;
260}
261
262#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
263const impl<A: [const] Ord> SliceOrd for A {
264    default fn compare(left: &[Self], right: &[Self]) -> Ordering {
265        let elem_chain = const |a, b| match Ord::cmp(a, b) {
266            Ordering::Equal => ControlFlow::Continue(()),
267            non_eq => ControlFlow::Break(non_eq),
268        };
269
270        let len_chain = const |a: &_, b: &_| ControlFlow::Break(usize::cmp(a, b));
271
272        let AlwaysBreak::Break(b) = chaining_impl(left, right, elem_chain, len_chain);
273        b
274    }
275}
276
277/// Marks that a type should be treated as an unsigned byte for comparisons.
278///
279/// # Safety
280/// * The type must be readable as an `u8`, meaning it has to have the same
281///   layout as `u8` and always be initialized.
282/// * For every `x` and `y` of this type, `Ord(x, y)` must return the same
283///   value as `Ord::cmp(transmute::<_, u8>(x), transmute::<_, u8>(y))`.
284#[rustc_specialization_trait]
285const unsafe trait UnsignedBytewiseOrd: [const] Ord {}
286
287#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
288const unsafe impl UnsignedBytewiseOrd for bool {}
289#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
290const unsafe impl UnsignedBytewiseOrd for u8 {}
291#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
292const unsafe impl UnsignedBytewiseOrd for NonZero<u8> {}
293#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
294const unsafe impl UnsignedBytewiseOrd for Option<NonZero<u8>> {}
295#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
296const unsafe impl UnsignedBytewiseOrd for ascii::Char {}
297
298// `compare_bytes` compares a sequence of unsigned bytes lexicographically, so
299// use it if the requirements for `UnsignedBytewiseOrd` are fulfilled.
300#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
301const impl<A: [const] Ord + [const] UnsignedBytewiseOrd> SliceOrd for A {
302    #[inline]
303    fn compare(left: &[Self], right: &[Self]) -> Ordering {
304        // Since the length of a slice is always less than or equal to
305        // isize::MAX, this never underflows.
306        let diff = left.len() as isize - right.len() as isize;
307        // This comparison gets optimized away (on x86_64 and ARM) because the
308        // subtraction updates flags.
309        let len = if left.len() < right.len() { left.len() } else { right.len() };
310        let left = left.as_ptr().cast();
311        let right = right.as_ptr().cast();
312        // SAFETY: `left` and `right` are references and are thus guaranteed to
313        // be valid. `UnsignedBytewiseOrd` is only implemented for types that
314        // are valid u8s and can be compared the same way. We use the minimum
315        // of both lengths which guarantees that both regions are valid for
316        // reads in that interval.
317        let mut order = unsafe { compare_bytes(left, right, len) as isize };
318        if order == 0 {
319            order = diff;
320        }
321        order.cmp(&0)
322    }
323}
324
325// Don't generate our own chaining loops for `memcmp`-able things either.
326
327#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
328const impl<A: [const] PartialOrd + [const] UnsignedBytewiseOrd> SliceChain for A {
329    #[inline]
330    fn chaining_less(left: &[Self], right: &[Self]) -> ControlFlow<bool> {
331        match SliceOrd::compare(left, right) {
332            Ordering::Equal => ControlFlow::Continue(()),
333            ne => ControlFlow::Break(ne.is_lt()),
334        }
335    }
336    #[inline]
337    fn chaining_greater(left: &[Self], right: &[Self]) -> ControlFlow<bool> {
338        match SliceOrd::compare(left, right) {
339            Ordering::Equal => ControlFlow::Continue(()),
340            ne => ControlFlow::Break(ne.is_gt()),
341        }
342    }
343}
344
345pub(super) trait SliceContains: Sized {
346    fn slice_contains(&self, x: &[Self]) -> bool;
347}
348
349impl<T> SliceContains for T
350where
351    T: PartialEq,
352{
353    #[expect(clippy::manual_contains, reason = "implements slice_contains")]
354    default fn slice_contains(&self, x: &[Self]) -> bool {
355        x.iter().any(|y| *y == *self)
356    }
357}
358
359impl<T: BytewiseEq> SliceContains for T {
360    #[inline]
361    #[expect(clippy::manual_contains, reason = "implements slice_contains")]
362    default fn slice_contains(&self, x: &[Self]) -> bool {
363        if size_of::<T>() == 1 {
364            // SAFETY: `BytewiseEq` guarantees that values have no padding or provenance and
365            // compare like their underlying bytes. Since `T` is one byte, both the value and
366            // slice can be read as `u8`s.
367            let (byte, bytes) = unsafe {
368                (transmute_copy::<T, u8>(self), from_raw_parts(x.as_ptr().cast::<u8>(), x.len()))
369            };
370            memchr::memchr(byte, bytes).is_some()
371        } else {
372            x.iter().any(|y| *y == *self)
373        }
374    }
375}
376
377macro_rules! impl_slice_contains {
378    ($($t:ty),*) => {
379        $(
380            impl SliceContains for $t {
381                #[inline]
382                fn slice_contains(&self, arr: &[$t]) -> bool {
383                    // Make our LANE_COUNT 4x the normal lane count (aiming for 128 bit vectors).
384                    // The compiler will nicely unroll it.
385                    const LANE_COUNT: usize = 4 * (128 / (size_of::<$t>() * 8));
386                    // SIMD
387                    let mut chunks = arr.chunks_exact(LANE_COUNT);
388                    for chunk in &mut chunks {
389                        if chunk.iter().fold(false, |acc, x| acc | (*x == *self)) {
390                            return true;
391                        }
392                    }
393                    // Scalar remainder
394                    return chunks.remainder().iter().any(|x| *x == *self);
395                }
396            }
397        )*
398    };
399}
400
401impl_slice_contains!(u16, u32, u64, i16, i32, i64, f32, f64, usize, isize, char);