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