Skip to main content

core/slice/
index.rs

1//! Indexing implementations for `[T]`.
2
3use crate::intrinsics::slice_get_unchecked;
4#[cfg(not(feature = "ferrocene_subset"))]
5use crate::marker::Destruct;
6use crate::panic::const_panic;
7use crate::ub_checks::assert_unsafe_precondition;
8#[cfg(not(feature = "ferrocene_subset"))]
9use crate::{ops, range};
10
11// Ferrocene addition: imports for certified subset
12#[cfg(feature = "ferrocene_subset")]
13#[rustfmt::skip]
14use crate::ops;
15
16#[stable(feature = "rust1", since = "1.0.0")]
17#[rustc_const_unstable(feature = "const_index", issue = "143775")]
18impl<T, I> const ops::Index<I> for [T]
19where
20    I: [const] SliceIndex<[T]>,
21{
22    type Output = I::Output;
23
24    #[inline(always)]
25    fn index(&self, index: I) -> &I::Output {
26        index.index(self)
27    }
28}
29
30#[stable(feature = "rust1", since = "1.0.0")]
31#[rustc_const_unstable(feature = "const_index", issue = "143775")]
32impl<T, I> const ops::IndexMut<I> for [T]
33where
34    I: [const] SliceIndex<[T]>,
35{
36    #[inline(always)]
37    fn index_mut(&mut self, index: I) -> &mut I::Output {
38        index.index_mut(self)
39    }
40}
41
42#[cfg_attr(not(panic = "immediate-abort"), inline(never), cold)]
43#[cfg_attr(panic = "immediate-abort", inline)]
44#[track_caller]
45const fn slice_index_fail(start: usize, end: usize, len: usize) -> ! {
46    if start > len {
47        const_panic!(
48            "slice start index is out of range for slice",
49            "range start index {start} out of range for slice of length {len}",
50            start: usize,
51            len: usize,
52        )
53    }
54
55    if end > len {
56        const_panic!(
57            "slice end index is out of range for slice",
58            "range end index {end} out of range for slice of length {len}",
59            end: usize,
60            len: usize,
61        )
62    }
63
64    if start > end {
65        const_panic!(
66            "slice index start is larger than end",
67            "slice index starts at {start} but ends at {end}",
68            start: usize,
69            end: usize,
70        )
71    }
72
73    // Only reachable if the range was a `RangeInclusive` or a
74    // `RangeToInclusive`, with `end == len`.
75    const_panic!(
76        "slice end index is out of range for slice",
77        "range end index {end} out of range for slice of length {len}",
78        end: usize,
79        len: usize,
80    )
81}
82
83// The UbChecks are great for catching bugs in the unsafe methods, but including
84// them in safe indexing is unnecessary and hurts inlining and debug runtime perf.
85// Both the safe and unsafe public methods share these helpers,
86// which use intrinsics directly to get *no* extra checks.
87
88#[inline(always)]
89const unsafe fn get_offset_len_noubcheck<T>(
90    ptr: *const [T],
91    offset: usize,
92    len: usize,
93) -> *const [T] {
94    let ptr = ptr as *const T;
95    // SAFETY: The caller already checked these preconditions
96    let ptr = unsafe { crate::intrinsics::offset(ptr, offset) };
97    crate::intrinsics::aggregate_raw_ptr(ptr, len)
98}
99
100#[inline(always)]
101const unsafe fn get_offset_len_mut_noubcheck<T>(
102    ptr: *mut [T],
103    offset: usize,
104    len: usize,
105) -> *mut [T] {
106    let ptr = ptr as *mut T;
107    // SAFETY: The caller already checked these preconditions
108    let ptr = unsafe { crate::intrinsics::offset(ptr, offset) };
109    crate::intrinsics::aggregate_raw_ptr(ptr, len)
110}
111
112mod private_slice_index {
113    #[cfg(not(feature = "ferrocene_subset"))]
114    use super::{ops, range};
115
116    // Ferrocene addition: imports for certified subset
117    #[cfg(feature = "ferrocene_subset")]
118    #[rustfmt::skip]
119    use super::ops;
120
121    #[stable(feature = "slice_get_slice", since = "1.28.0")]
122    pub trait Sealed {}
123
124    #[stable(feature = "slice_get_slice", since = "1.28.0")]
125    impl Sealed for usize {}
126    #[stable(feature = "slice_get_slice", since = "1.28.0")]
127    impl Sealed for ops::Range<usize> {}
128    #[stable(feature = "slice_get_slice", since = "1.28.0")]
129    impl Sealed for ops::RangeTo<usize> {}
130    #[stable(feature = "slice_get_slice", since = "1.28.0")]
131    impl Sealed for ops::RangeFrom<usize> {}
132    #[stable(feature = "slice_get_slice", since = "1.28.0")]
133    impl Sealed for ops::RangeFull {}
134    #[stable(feature = "slice_get_slice", since = "1.28.0")]
135    impl Sealed for ops::RangeInclusive<usize> {}
136    #[stable(feature = "slice_get_slice", since = "1.28.0")]
137    impl Sealed for ops::RangeToInclusive<usize> {}
138    #[stable(feature = "slice_index_with_ops_bound_pair", since = "1.53.0")]
139    impl Sealed for (ops::Bound<usize>, ops::Bound<usize>) {}
140
141    #[unstable(feature = "new_range_api", issue = "125687")]
142    #[cfg(not(feature = "ferrocene_subset"))]
143    impl Sealed for range::Range<usize> {}
144    #[cfg(not(feature = "ferrocene_subset"))]
145    #[stable(feature = "new_range_inclusive_api", since = "CURRENT_RUSTC_VERSION")]
146    impl Sealed for range::RangeInclusive<usize> {}
147    #[unstable(feature = "new_range_api", issue = "125687")]
148    #[cfg(not(feature = "ferrocene_subset"))]
149    impl Sealed for range::RangeToInclusive<usize> {}
150    #[unstable(feature = "new_range_api", issue = "125687")]
151    #[cfg(not(feature = "ferrocene_subset"))]
152    impl Sealed for range::RangeFrom<usize> {}
153
154    impl Sealed for ops::IndexRange {}
155
156    #[cfg(not(feature = "ferrocene_subset"))]
157    #[unstable(feature = "sliceindex_wrappers", issue = "146179")]
158    impl Sealed for crate::index::Last {}
159    #[cfg(not(feature = "ferrocene_subset"))]
160    #[unstable(feature = "sliceindex_wrappers", issue = "146179")]
161    impl<T> Sealed for crate::index::Clamp<T> where T: Sealed {}
162}
163
164/// A helper trait used for indexing operations.
165///
166/// Implementations of this trait have to promise that if the argument
167/// to `get_unchecked(_mut)` is a safe reference, then so is the result.
168#[stable(feature = "slice_get_slice", since = "1.28.0")]
169#[rustc_diagnostic_item = "SliceIndex"]
170#[rustc_on_unimplemented(
171    on(T = "str", label = "string indices are ranges of `usize`",),
172    on(
173        all(any(T = "str", T = "&str", T = "alloc::string::String"), Self = "{integer}"),
174        note = "you can use `.chars().nth()` or `.bytes().nth()`\n\
175                for more information, see chapter 8 in The Book: \
176                <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>"
177    ),
178    message = "the type `{T}` cannot be indexed by `{Self}`",
179    label = "slice indices are of type `usize` or ranges of `usize`"
180)]
181#[rustc_const_unstable(feature = "const_index", issue = "143775")]
182pub const unsafe trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
183    /// The output type returned by methods.
184    #[stable(feature = "slice_get_slice", since = "1.28.0")]
185    type Output: ?Sized;
186
187    /// Returns a shared reference to the output at this location, if in
188    /// bounds.
189    #[unstable(feature = "slice_index_methods", issue = "none")]
190    fn get(self, slice: &T) -> Option<&Self::Output>;
191
192    /// Returns a mutable reference to the output at this location, if in
193    /// bounds.
194    #[unstable(feature = "slice_index_methods", issue = "none")]
195    fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
196
197    /// Returns a pointer to the output at this location, without
198    /// performing any bounds checking.
199    ///
200    /// Calling this method with an out-of-bounds index or a dangling `slice` pointer
201    /// is *[undefined behavior]* even if the resulting pointer is not used.
202    ///
203    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
204    #[unstable(feature = "slice_index_methods", issue = "none")]
205    unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output;
206
207    /// Returns a mutable pointer to the output at this location, without
208    /// performing any bounds checking.
209    ///
210    /// Calling this method with an out-of-bounds index or a dangling `slice` pointer
211    /// is *[undefined behavior]* even if the resulting pointer is not used.
212    ///
213    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
214    #[unstable(feature = "slice_index_methods", issue = "none")]
215    unsafe fn get_unchecked_mut(self, slice: *mut T) -> *mut Self::Output;
216
217    /// Returns a shared reference to the output at this location, panicking
218    /// if out of bounds.
219    #[unstable(feature = "slice_index_methods", issue = "none")]
220    #[track_caller]
221    fn index(self, slice: &T) -> &Self::Output;
222
223    /// Returns a mutable reference to the output at this location, panicking
224    /// if out of bounds.
225    #[unstable(feature = "slice_index_methods", issue = "none")]
226    #[track_caller]
227    fn index_mut(self, slice: &mut T) -> &mut Self::Output;
228}
229
230/// The methods `index` and `index_mut` panic if the index is out of bounds.
231#[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
232#[rustc_const_unstable(feature = "const_index", issue = "143775")]
233unsafe impl<T> const SliceIndex<[T]> for usize {
234    type Output = T;
235
236    #[inline]
237    fn get(self, slice: &[T]) -> Option<&T> {
238        if self < slice.len() {
239            // SAFETY: `self` is checked to be in bounds.
240            unsafe { Some(slice_get_unchecked(slice, self)) }
241        } else {
242            None
243        }
244    }
245
246    #[inline]
247    fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
248        if self < slice.len() {
249            // SAFETY: `self` is checked to be in bounds.
250            unsafe { Some(slice_get_unchecked(slice, self)) }
251        } else {
252            None
253        }
254    }
255
256    #[inline]
257    #[track_caller]
258    unsafe fn get_unchecked(self, slice: *const [T]) -> *const T {
259        assert_unsafe_precondition!(
260            check_language_ub, // okay because of the `assume` below
261            "slice::get_unchecked requires that the index is within the slice",
262            (this: usize = self, len: usize = slice.len()) => this < len
263        );
264        // SAFETY: the caller guarantees that `slice` is not dangling, so it
265        // cannot be longer than `isize::MAX`. They also guarantee that
266        // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
267        // so the call to `add` is safe.
268        unsafe {
269            // Use intrinsics::assume instead of hint::assert_unchecked so that we don't check the
270            // precondition of this function twice.
271            crate::intrinsics::assume(self < slice.len());
272            slice_get_unchecked(slice, self)
273        }
274    }
275
276    #[inline]
277    #[track_caller]
278    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut T {
279        assert_unsafe_precondition!(
280            check_library_ub,
281            "slice::get_unchecked_mut requires that the index is within the slice",
282            (this: usize = self, len: usize = slice.len()) => this < len
283        );
284        // SAFETY: see comments for `get_unchecked` above.
285        unsafe { slice_get_unchecked(slice, self) }
286    }
287
288    #[inline]
289    fn index(self, slice: &[T]) -> &T {
290        // N.B., use intrinsic indexing
291        &(*slice)[self]
292    }
293
294    #[inline]
295    fn index_mut(self, slice: &mut [T]) -> &mut T {
296        // N.B., use intrinsic indexing
297        &mut (*slice)[self]
298    }
299}
300
301/// Because `IndexRange` guarantees `start <= end`, fewer checks are needed here
302/// than there are for a general `Range<usize>` (which might be `100..3`).
303#[rustc_const_unstable(feature = "const_index", issue = "143775")]
304unsafe impl<T> const SliceIndex<[T]> for ops::IndexRange {
305    type Output = [T];
306
307    #[inline]
308    fn get(self, slice: &[T]) -> Option<&[T]> {
309        if self.end() <= slice.len() {
310            // SAFETY: `self` is checked to be valid and in bounds above.
311            unsafe { Some(&*get_offset_len_noubcheck(slice, self.start(), self.len())) }
312        } else {
313            None
314        }
315    }
316
317    #[inline]
318    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
319        if self.end() <= slice.len() {
320            // SAFETY: `self` is checked to be valid and in bounds above.
321            unsafe { Some(&mut *get_offset_len_mut_noubcheck(slice, self.start(), self.len())) }
322        } else {
323            None
324        }
325    }
326
327    #[inline]
328    #[track_caller]
329    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
330        assert_unsafe_precondition!(
331            check_library_ub,
332            "slice::get_unchecked requires that the index is within the slice",
333            (end: usize = self.end(), len: usize = slice.len()) => end <= len
334        );
335        // SAFETY: the caller guarantees that `slice` is not dangling, so it
336        // cannot be longer than `isize::MAX`. They also guarantee that
337        // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
338        // so the call to `add` is safe.
339        unsafe { get_offset_len_noubcheck(slice, self.start(), self.len()) }
340    }
341
342    #[inline]
343    #[track_caller]
344    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
345        assert_unsafe_precondition!(
346            check_library_ub,
347            "slice::get_unchecked_mut requires that the index is within the slice",
348            (end: usize = self.end(), len: usize = slice.len()) => end <= len
349        );
350
351        // SAFETY: see comments for `get_unchecked` above.
352        unsafe { get_offset_len_mut_noubcheck(slice, self.start(), self.len()) }
353    }
354
355    #[inline]
356    fn index(self, slice: &[T]) -> &[T] {
357        if self.end() <= slice.len() {
358            // SAFETY: `self` is checked to be valid and in bounds above.
359            unsafe { &*get_offset_len_noubcheck(slice, self.start(), self.len()) }
360        } else {
361            slice_index_fail(self.start(), self.end(), slice.len())
362        }
363    }
364
365    #[inline]
366    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
367        if self.end() <= slice.len() {
368            // SAFETY: `self` is checked to be valid and in bounds above.
369            unsafe { &mut *get_offset_len_mut_noubcheck(slice, self.start(), self.len()) }
370        } else {
371            slice_index_fail(self.start(), self.end(), slice.len())
372        }
373    }
374}
375
376/// The methods `index` and `index_mut` panic if:
377/// - the start of the range is greater than the end of the range or
378/// - the end of the range is out of bounds.
379#[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
380#[rustc_const_unstable(feature = "const_index", issue = "143775")]
381unsafe impl<T> const SliceIndex<[T]> for ops::Range<usize> {
382    type Output = [T];
383
384    #[inline]
385    fn get(self, slice: &[T]) -> Option<&[T]> {
386        // Using checked_sub is a safe way to get `SubUnchecked` in MIR
387        if let Some(new_len) = usize::checked_sub(self.end, self.start)
388            && self.end <= slice.len()
389        {
390            // SAFETY: `self` is checked to be valid and in bounds above.
391            unsafe { Some(&*get_offset_len_noubcheck(slice, self.start, new_len)) }
392        } else {
393            None
394        }
395    }
396
397    #[inline]
398    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
399        if let Some(new_len) = usize::checked_sub(self.end, self.start)
400            && self.end <= slice.len()
401        {
402            // SAFETY: `self` is checked to be valid and in bounds above.
403            unsafe { Some(&mut *get_offset_len_mut_noubcheck(slice, self.start, new_len)) }
404        } else {
405            None
406        }
407    }
408
409    #[inline]
410    #[track_caller]
411    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
412        assert_unsafe_precondition!(
413            check_library_ub,
414            "slice::get_unchecked requires that the range is within the slice",
415            (
416                start: usize = self.start,
417                end: usize = self.end,
418                len: usize = slice.len()
419            ) => end >= start && end <= len
420        );
421
422        // SAFETY: the caller guarantees that `slice` is not dangling, so it
423        // cannot be longer than `isize::MAX`. They also guarantee that
424        // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
425        // so the call to `add` is safe and the length calculation cannot overflow.
426        unsafe {
427            // Using the intrinsic avoids a superfluous UB check,
428            // since the one on this method already checked `end >= start`.
429            let new_len = crate::intrinsics::unchecked_sub(self.end, self.start);
430            get_offset_len_noubcheck(slice, self.start, new_len)
431        }
432    }
433
434    #[inline]
435    #[track_caller]
436    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
437        assert_unsafe_precondition!(
438            check_library_ub,
439            "slice::get_unchecked_mut requires that the range is within the slice",
440            (
441                start: usize = self.start,
442                end: usize = self.end,
443                len: usize = slice.len()
444            ) => end >= start && end <= len
445        );
446        // SAFETY: see comments for `get_unchecked` above.
447        unsafe {
448            let new_len = crate::intrinsics::unchecked_sub(self.end, self.start);
449            get_offset_len_mut_noubcheck(slice, self.start, new_len)
450        }
451    }
452
453    #[inline(always)]
454    fn index(self, slice: &[T]) -> &[T] {
455        // Using checked_sub is a safe way to get `SubUnchecked` in MIR
456        if let Some(new_len) = usize::checked_sub(self.end, self.start)
457            && self.end <= slice.len()
458        {
459            // SAFETY: `self` is checked to be valid and in bounds above.
460            unsafe { &*get_offset_len_noubcheck(slice, self.start, new_len) }
461        } else {
462            slice_index_fail(self.start, self.end, slice.len())
463        }
464    }
465
466    #[inline]
467    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
468        // Using checked_sub is a safe way to get `SubUnchecked` in MIR
469        if let Some(new_len) = usize::checked_sub(self.end, self.start)
470            && self.end <= slice.len()
471        {
472            // SAFETY: `self` is checked to be valid and in bounds above.
473            unsafe { &mut *get_offset_len_mut_noubcheck(slice, self.start, new_len) }
474        } else {
475            slice_index_fail(self.start, self.end, slice.len())
476        }
477    }
478}
479
480#[unstable(feature = "new_range_api", issue = "125687")]
481#[rustc_const_unstable(feature = "const_index", issue = "143775")]
482#[cfg(not(feature = "ferrocene_subset"))]
483unsafe impl<T> const SliceIndex<[T]> for range::Range<usize> {
484    type Output = [T];
485
486    #[inline]
487    fn get(self, slice: &[T]) -> Option<&[T]> {
488        ops::Range::from(self).get(slice)
489    }
490
491    #[inline]
492    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
493        ops::Range::from(self).get_mut(slice)
494    }
495
496    #[inline]
497    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
498        // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
499        unsafe { ops::Range::from(self).get_unchecked(slice) }
500    }
501
502    #[inline]
503    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
504        // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
505        unsafe { ops::Range::from(self).get_unchecked_mut(slice) }
506    }
507
508    #[inline(always)]
509    fn index(self, slice: &[T]) -> &[T] {
510        ops::Range::from(self).index(slice)
511    }
512
513    #[inline]
514    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
515        ops::Range::from(self).index_mut(slice)
516    }
517}
518
519/// The methods `index` and `index_mut` panic if the end of the range is out of bounds.
520#[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
521#[rustc_const_unstable(feature = "const_index", issue = "143775")]
522unsafe impl<T> const SliceIndex<[T]> for ops::RangeTo<usize> {
523    type Output = [T];
524
525    #[inline]
526    fn get(self, slice: &[T]) -> Option<&[T]> {
527        (0..self.end).get(slice)
528    }
529
530    #[inline]
531    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
532        (0..self.end).get_mut(slice)
533    }
534
535    #[inline]
536    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
537        // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
538        unsafe { (0..self.end).get_unchecked(slice) }
539    }
540
541    #[inline]
542    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
543        // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
544        unsafe { (0..self.end).get_unchecked_mut(slice) }
545    }
546
547    #[inline(always)]
548    fn index(self, slice: &[T]) -> &[T] {
549        (0..self.end).index(slice)
550    }
551
552    #[inline]
553    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
554        (0..self.end).index_mut(slice)
555    }
556}
557
558/// The methods `index` and `index_mut` panic if the start of the range is out of bounds.
559#[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
560#[rustc_const_unstable(feature = "const_index", issue = "143775")]
561unsafe impl<T> const SliceIndex<[T]> for ops::RangeFrom<usize> {
562    type Output = [T];
563
564    #[inline]
565    fn get(self, slice: &[T]) -> Option<&[T]> {
566        (self.start..slice.len()).get(slice)
567    }
568
569    #[inline]
570    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
571        (self.start..slice.len()).get_mut(slice)
572    }
573
574    #[inline]
575    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
576        // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
577        unsafe { (self.start..slice.len()).get_unchecked(slice) }
578    }
579
580    #[inline]
581    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
582        // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
583        unsafe { (self.start..slice.len()).get_unchecked_mut(slice) }
584    }
585
586    #[inline]
587    fn index(self, slice: &[T]) -> &[T] {
588        if self.start > slice.len() {
589            slice_index_fail(self.start, slice.len(), slice.len())
590        }
591        // SAFETY: `self` is checked to be valid and in bounds above.
592        unsafe {
593            let new_len = crate::intrinsics::unchecked_sub(slice.len(), self.start);
594            &*get_offset_len_noubcheck(slice, self.start, new_len)
595        }
596    }
597
598    #[inline]
599    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
600        if self.start > slice.len() {
601            slice_index_fail(self.start, slice.len(), slice.len())
602        }
603        // SAFETY: `self` is checked to be valid and in bounds above.
604        unsafe {
605            let new_len = crate::intrinsics::unchecked_sub(slice.len(), self.start);
606            &mut *get_offset_len_mut_noubcheck(slice, self.start, new_len)
607        }
608    }
609}
610
611#[unstable(feature = "new_range_api", issue = "125687")]
612#[rustc_const_unstable(feature = "const_index", issue = "143775")]
613#[cfg(not(feature = "ferrocene_subset"))]
614unsafe impl<T> const SliceIndex<[T]> for range::RangeFrom<usize> {
615    type Output = [T];
616
617    #[inline]
618    fn get(self, slice: &[T]) -> Option<&[T]> {
619        ops::RangeFrom::from(self).get(slice)
620    }
621
622    #[inline]
623    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
624        ops::RangeFrom::from(self).get_mut(slice)
625    }
626
627    #[inline]
628    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
629        // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
630        unsafe { ops::RangeFrom::from(self).get_unchecked(slice) }
631    }
632
633    #[inline]
634    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
635        // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
636        unsafe { ops::RangeFrom::from(self).get_unchecked_mut(slice) }
637    }
638
639    #[inline]
640    fn index(self, slice: &[T]) -> &[T] {
641        ops::RangeFrom::from(self).index(slice)
642    }
643
644    #[inline]
645    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
646        ops::RangeFrom::from(self).index_mut(slice)
647    }
648}
649
650#[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
651#[rustc_const_unstable(feature = "const_index", issue = "143775")]
652unsafe impl<T> const SliceIndex<[T]> for ops::RangeFull {
653    type Output = [T];
654
655    #[inline]
656    fn get(self, slice: &[T]) -> Option<&[T]> {
657        Some(slice)
658    }
659
660    #[inline]
661    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
662        Some(slice)
663    }
664
665    #[inline]
666    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
667        slice
668    }
669
670    #[inline]
671    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
672        slice
673    }
674
675    #[inline]
676    fn index(self, slice: &[T]) -> &[T] {
677        slice
678    }
679
680    #[inline]
681    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
682        slice
683    }
684}
685
686/// The methods `index` and `index_mut` panic if:
687/// - the start of the range is greater than the end of the range or
688/// - the end of the range is out of bounds.
689#[stable(feature = "inclusive_range", since = "1.26.0")]
690#[rustc_const_unstable(feature = "const_index", issue = "143775")]
691unsafe impl<T> const SliceIndex<[T]> for ops::RangeInclusive<usize> {
692    type Output = [T];
693
694    #[inline]
695    fn get(self, slice: &[T]) -> Option<&[T]> {
696        if *self.end() >= slice.len() { None } else { self.into_slice_range().get(slice) }
697    }
698
699    #[inline]
700    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
701        if *self.end() >= slice.len() { None } else { self.into_slice_range().get_mut(slice) }
702    }
703
704    #[inline]
705    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
706        // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
707        unsafe { self.into_slice_range().get_unchecked(slice) }
708    }
709
710    #[inline]
711    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
712        // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
713        unsafe { self.into_slice_range().get_unchecked_mut(slice) }
714    }
715
716    #[inline]
717    fn index(self, slice: &[T]) -> &[T] {
718        let Self { mut start, mut end, exhausted } = self;
719        let len = slice.len();
720        if end < len {
721            end = end + 1;
722            start = if exhausted { end } else { start };
723            if let Some(new_len) = usize::checked_sub(end, start) {
724                // SAFETY: `self` is checked to be valid and in bounds above.
725                unsafe { return &*get_offset_len_noubcheck(slice, start, new_len) }
726            }
727        }
728        slice_index_fail(start, end, slice.len())
729    }
730
731    #[inline]
732    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
733        let Self { mut start, mut end, exhausted } = self;
734        let len = slice.len();
735        if end < len {
736            end = end + 1;
737            start = if exhausted { end } else { start };
738            if let Some(new_len) = usize::checked_sub(end, start) {
739                // SAFETY: `self` is checked to be valid and in bounds above.
740                unsafe { return &mut *get_offset_len_mut_noubcheck(slice, start, new_len) }
741            }
742        }
743        slice_index_fail(start, end, slice.len())
744    }
745}
746
747#[stable(feature = "new_range_inclusive_api", since = "CURRENT_RUSTC_VERSION")]
748#[rustc_const_unstable(feature = "const_index", issue = "143775")]
749#[cfg(not(feature = "ferrocene_subset"))]
750unsafe impl<T> const SliceIndex<[T]> for range::RangeInclusive<usize> {
751    type Output = [T];
752
753    #[inline]
754    fn get(self, slice: &[T]) -> Option<&[T]> {
755        ops::RangeInclusive::from(self).get(slice)
756    }
757
758    #[inline]
759    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
760        ops::RangeInclusive::from(self).get_mut(slice)
761    }
762
763    #[inline]
764    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
765        // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
766        unsafe { ops::RangeInclusive::from(self).get_unchecked(slice) }
767    }
768
769    #[inline]
770    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
771        // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
772        unsafe { ops::RangeInclusive::from(self).get_unchecked_mut(slice) }
773    }
774
775    #[inline]
776    fn index(self, slice: &[T]) -> &[T] {
777        ops::RangeInclusive::from(self).index(slice)
778    }
779
780    #[inline]
781    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
782        ops::RangeInclusive::from(self).index_mut(slice)
783    }
784}
785
786/// The methods `index` and `index_mut` panic if the end of the range is out of bounds.
787#[stable(feature = "inclusive_range", since = "1.26.0")]
788#[rustc_const_unstable(feature = "const_index", issue = "143775")]
789unsafe impl<T> const SliceIndex<[T]> for ops::RangeToInclusive<usize> {
790    type Output = [T];
791
792    #[inline]
793    fn get(self, slice: &[T]) -> Option<&[T]> {
794        (0..=self.end).get(slice)
795    }
796
797    #[inline]
798    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
799        (0..=self.end).get_mut(slice)
800    }
801
802    #[inline]
803    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
804        // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
805        unsafe { (0..=self.end).get_unchecked(slice) }
806    }
807
808    #[inline]
809    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
810        // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
811        unsafe { (0..=self.end).get_unchecked_mut(slice) }
812    }
813
814    #[inline]
815    fn index(self, slice: &[T]) -> &[T] {
816        (0..=self.end).index(slice)
817    }
818
819    #[inline]
820    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
821        (0..=self.end).index_mut(slice)
822    }
823}
824
825/// The methods `index` and `index_mut` panic if the end of the range is out of bounds.
826#[stable(feature = "inclusive_range", since = "1.26.0")]
827#[rustc_const_unstable(feature = "const_index", issue = "143775")]
828#[cfg(not(feature = "ferrocene_subset"))]
829unsafe impl<T> const SliceIndex<[T]> for range::RangeToInclusive<usize> {
830    type Output = [T];
831
832    #[inline]
833    fn get(self, slice: &[T]) -> Option<&[T]> {
834        (0..=self.last).get(slice)
835    }
836
837    #[inline]
838    fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
839        (0..=self.last).get_mut(slice)
840    }
841
842    #[inline]
843    unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
844        // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
845        unsafe { (0..=self.last).get_unchecked(slice) }
846    }
847
848    #[inline]
849    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
850        // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
851        unsafe { (0..=self.last).get_unchecked_mut(slice) }
852    }
853
854    #[inline]
855    fn index(self, slice: &[T]) -> &[T] {
856        (0..=self.last).index(slice)
857    }
858
859    #[inline]
860    fn index_mut(self, slice: &mut [T]) -> &mut [T] {
861        (0..=self.last).index_mut(slice)
862    }
863}
864
865/// Performs bounds checking of a range.
866///
867/// This method is similar to [`Index::index`] for slices, but it returns a
868/// [`Range`] equivalent to `range`. You can use this method to turn any range
869/// into `start` and `end` values.
870///
871/// `bounds` is the range of the slice to use for bounds checking. It should
872/// be a [`RangeTo`] range that ends at the length of the slice.
873///
874/// The returned [`Range`] is safe to pass to [`slice::get_unchecked`] and
875/// [`slice::get_unchecked_mut`] for slices with the given range.
876///
877/// [`Range`]: ops::Range
878/// [`RangeTo`]: ops::RangeTo
879/// [`slice::get_unchecked`]: slice::get_unchecked
880/// [`slice::get_unchecked_mut`]: slice::get_unchecked_mut
881///
882/// # Panics
883///
884/// Panics if `range` would be out of bounds.
885///
886/// # Examples
887///
888/// ```
889/// #![feature(slice_range)]
890///
891/// use std::slice;
892///
893/// let v = [10, 40, 30];
894/// assert_eq!(1..2, slice::range(1..2, ..v.len()));
895/// assert_eq!(0..2, slice::range(..2, ..v.len()));
896/// assert_eq!(1..3, slice::range(1.., ..v.len()));
897/// ```
898///
899/// Panics when [`Index::index`] would panic:
900///
901/// ```should_panic
902/// #![feature(slice_range)]
903///
904/// use std::slice;
905///
906/// let _ = slice::range(2..1, ..3);
907/// ```
908///
909/// ```should_panic
910/// #![feature(slice_range)]
911///
912/// use std::slice;
913///
914/// let _ = slice::range(1..4, ..3);
915/// ```
916///
917/// ```should_panic
918/// #![feature(slice_range)]
919///
920/// use std::slice;
921///
922/// let _ = slice::range(1..=usize::MAX, ..3);
923/// ```
924///
925/// [`Index::index`]: ops::Index::index
926#[track_caller]
927#[unstable(feature = "slice_range", issue = "76393")]
928#[must_use]
929#[rustc_const_unstable(feature = "const_range", issue = "none")]
930#[cfg(not(feature = "ferrocene_subset"))]
931pub const fn range<R>(range: R, bounds: ops::RangeTo<usize>) -> ops::Range<usize>
932where
933    R: [const] ops::RangeBounds<usize> + [const] Destruct,
934{
935    let len = bounds.end;
936    into_slice_range(len, (range.start_bound().copied(), range.end_bound().copied()))
937}
938
939/// Performs bounds checking of a range without panicking.
940///
941/// This is a version of [`range()`] that returns [`None`] instead of panicking.
942///
943/// # Examples
944///
945/// ```
946/// #![feature(slice_range)]
947///
948/// use std::slice;
949///
950/// let v = [10, 40, 30];
951/// assert_eq!(Some(1..2), slice::try_range(1..2, ..v.len()));
952/// assert_eq!(Some(0..2), slice::try_range(..2, ..v.len()));
953/// assert_eq!(Some(1..3), slice::try_range(1.., ..v.len()));
954/// ```
955///
956/// Returns [`None`] when [`Index::index`] would panic:
957///
958/// ```
959/// #![feature(slice_range)]
960///
961/// use std::slice;
962///
963/// assert_eq!(None, slice::try_range(2..1, ..3));
964/// assert_eq!(None, slice::try_range(1..4, ..3));
965/// assert_eq!(None, slice::try_range(1..=usize::MAX, ..3));
966/// ```
967///
968/// [`Index::index`]: ops::Index::index
969#[unstable(feature = "slice_range", issue = "76393")]
970#[must_use]
971#[cfg(not(feature = "ferrocene_subset"))]
972pub fn try_range<R>(range: R, bounds: ops::RangeTo<usize>) -> Option<ops::Range<usize>>
973where
974    R: ops::RangeBounds<usize>,
975{
976    let len = bounds.end;
977    try_into_slice_range(len, (range.start_bound().copied(), range.end_bound().copied()))
978}
979
980/// Converts a pair of `ops::Bound`s into `ops::Range` without performing any
981/// bounds checking or (in debug) overflow checking.
982pub(crate) const fn into_range_unchecked(
983    len: usize,
984    (start, end): (ops::Bound<usize>, ops::Bound<usize>),
985) -> ops::Range<usize> {
986    use ops::Bound;
987    let start = match start {
988        Bound::Included(i) => i,
989        Bound::Excluded(i) => i + 1,
990        Bound::Unbounded => 0,
991    };
992    let end = match end {
993        Bound::Included(i) => i + 1,
994        Bound::Excluded(i) => i,
995        Bound::Unbounded => len,
996    };
997    start..end
998}
999
1000/// Converts pair of `ops::Bound`s into `ops::Range`.
1001/// Returns `None` on overflowing indices.
1002#[rustc_const_unstable(feature = "const_range", issue = "none")]
1003#[inline]
1004pub(crate) const fn try_into_slice_range(
1005    len: usize,
1006    (start, end): (ops::Bound<usize>, ops::Bound<usize>),
1007) -> Option<ops::Range<usize>> {
1008    let end = match end {
1009        ops::Bound::Included(end) if end >= len => return None,
1010        // Cannot overflow because `end < len` implies `end < usize::MAX`.
1011        ops::Bound::Included(end) => end + 1,
1012
1013        ops::Bound::Excluded(end) if end > len => return None,
1014        ops::Bound::Excluded(end) => end,
1015
1016        ops::Bound::Unbounded => len,
1017    };
1018
1019    let start = match start {
1020        ops::Bound::Excluded(start) if start >= end => return None,
1021        // Cannot overflow because `start < end` implies `start < usize::MAX`.
1022        ops::Bound::Excluded(start) => start + 1,
1023
1024        ops::Bound::Included(start) if start > end => return None,
1025        ops::Bound::Included(start) => start,
1026
1027        ops::Bound::Unbounded => 0,
1028    };
1029
1030    Some(start..end)
1031}
1032
1033/// Converts pair of `ops::Bound`s into `ops::Range`.
1034/// Panics on overflowing indices.
1035#[inline]
1036pub(crate) const fn into_slice_range(
1037    len: usize,
1038    (start, end): (ops::Bound<usize>, ops::Bound<usize>),
1039) -> ops::Range<usize> {
1040    let end = match end {
1041        ops::Bound::Included(end) if end >= len => slice_index_fail(0, end, len),
1042        // Cannot overflow because `end < len` implies `end < usize::MAX`.
1043        ops::Bound::Included(end) => end + 1,
1044
1045        ops::Bound::Excluded(end) if end > len => slice_index_fail(0, end, len),
1046        ops::Bound::Excluded(end) => end,
1047
1048        ops::Bound::Unbounded => len,
1049    };
1050
1051    let start = match start {
1052        ops::Bound::Excluded(start) if start >= end => slice_index_fail(start, end, len),
1053        // Cannot overflow because `start < end` implies `start < usize::MAX`.
1054        ops::Bound::Excluded(start) => start + 1,
1055
1056        ops::Bound::Included(start) if start > end => slice_index_fail(start, end, len),
1057        ops::Bound::Included(start) => start,
1058
1059        ops::Bound::Unbounded => 0,
1060    };
1061
1062    start..end
1063}
1064
1065#[stable(feature = "slice_index_with_ops_bound_pair", since = "1.53.0")]
1066unsafe impl<T> SliceIndex<[T]> for (ops::Bound<usize>, ops::Bound<usize>) {
1067    type Output = [T];
1068
1069    #[inline]
1070    fn get(self, slice: &[T]) -> Option<&Self::Output> {
1071        try_into_slice_range(slice.len(), self)?.get(slice)
1072    }
1073
1074    #[inline]
1075    fn get_mut(self, slice: &mut [T]) -> Option<&mut Self::Output> {
1076        try_into_slice_range(slice.len(), self)?.get_mut(slice)
1077    }
1078
1079    #[inline]
1080    unsafe fn get_unchecked(self, slice: *const [T]) -> *const Self::Output {
1081        // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
1082        unsafe { into_range_unchecked(slice.len(), self).get_unchecked(slice) }
1083    }
1084
1085    #[inline]
1086    unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut Self::Output {
1087        // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
1088        unsafe { into_range_unchecked(slice.len(), self).get_unchecked_mut(slice) }
1089    }
1090
1091    #[inline]
1092    fn index(self, slice: &[T]) -> &Self::Output {
1093        into_slice_range(slice.len(), self).index(slice)
1094    }
1095
1096    #[inline]
1097    fn index_mut(self, slice: &mut [T]) -> &mut Self::Output {
1098        into_slice_range(slice.len(), self).index_mut(slice)
1099    }
1100}