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