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