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