value_traits/traits/
slices.rs

1/*
2 * SPDX-FileCopyrightText: 2025 Tommaso Fontana
3 * SPDX-FileCopyrightText: 2025 Sebastiano Vigna
4 * SPDX-FileCopyrightText: 2025 Inria
5 *
6 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
7 */
8
9//! Traits for value-based slices.
10//!
11//! Value-based slices are analogous to Rust's built-in slices, but they operate
12//! on values rather than references. This allows for more flexibility in how
13//! slices are used and manipulated.
14//!
15//! For example, a value-based slice can be defined functionally, implicitly, or
16//! using a succinct/compressed representation.
17//!
18//! The fundamental trait for value-based slices is [`SliceByValue`], which
19//! specifies the type of the values and the length of the slice. Additional
20//! functionality is provided by the [`SliceByValueGet`], [`SliceByValueSet`],
21//! and [`SliceByValueRepl`] traits, which allow for getting, setting, and
22//! replacing values in the slice, respectively. Note that, contrarily to the
23//! standard slices, replacement can be obtained by a pair of get/set
24//! operations: [`SliceByValueRepl`] is just more efficient.
25//!
26//! The [`SliceByValueSubslice`] trait provides methods for obtaining subslices
27//! given a range of indices, and the [`SliceByValueSubsliceMut`] trait provides
28//! mutable versions of these methods.
29//!
30//! Both traits are a combination of underlying traits that provide more
31//! specific subslicing functionality depending on the type of range used. In
32//! the intended usage, these traits are interesting only for implementors, or
33//! in the case an implementation does not provide the full set of ranges.
34//!
35//! ## Examples
36//!
37//! As a very simple worked-out example, let us a by-value read-only slice of
38//! `usize` using a vector of `u8` as a basic form of compression:
39//!
40//! ```rust
41//! use value_traits::slices::*;
42//!
43//! struct CompSlice<'a>(&'a [u8]);
44//!
45//! impl<'a> SliceByValue for CompSlice<'a> {
46//!     type Value = usize;
47//!     fn len(&self) -> usize {
48//!         self.0.len()
49//!     }
50//! }
51//!
52//! impl<'a> SliceByValueGet for CompSlice<'a> {
53//!     unsafe fn get_value_unchecked(&self, index: usize) -> usize {
54//!         self.0.get_value_unchecked(index) as usize
55//!     }
56//! }
57//!
58//! fn f(slice_by_value: impl SliceByValueGet<Value = usize>, index: usize) -> usize {
59//!     slice_by_value.index_value(index)
60//! }
61//!
62//! fn main() {
63//!     let vec = vec![0_u8, 1, 2, 3];
64//!     let slice_by_value = CompSlice(&vec);
65//!     // Note that we can pass a reference
66//!     assert_eq!(f(&slice_by_value, 0), 0);
67//!     assert_eq!(f(&slice_by_value, 1), 1);
68//!     assert_eq!(f(&slice_by_value, 2), 2);
69//!     assert_eq!(f(&slice_by_value, 3), 3);
70//! }
71//!
72//! ```
73//! In this example, instead, we define functionally a slice containing the
74//! first 100 squares:
75//!
76//! ```rust
77//! use value_traits::slices::*;
78//!
79//! struct Squares();
80//!
81//! impl<'a> SliceByValue for Squares {
82//!     type Value = usize;
83//!     fn len(&self) -> usize {
84//!         100
85//!     }
86//! }
87//!
88//! impl<'a> SliceByValueGet for Squares {
89//!     unsafe fn get_value_unchecked(&self, index: usize) -> usize {
90//!         index * index
91//!     }
92//! }
93//!
94//! fn f(slice_by_value: &impl SliceByValueGet<Value = usize>, index: usize) -> usize {
95//!     slice_by_value.index_value(index)
96//! }
97//!
98//! fn main() {
99//!     let squares = Squares();
100//!     for i in 0..100 {
101//!         assert_eq!(squares.index_value(i), i * i);
102//!     }
103//! }
104//! ```
105
106use core::{
107    hint::unreachable_unchecked,
108    ops::{
109        Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
110    },
111};
112
113use crate::{ImplBound, Ref};
114
115/// Basic slice-by-value trait, specifying just the type of the values and the
116/// length of the slice.
117pub trait SliceByValue {
118    /// The type of the values in the slice.
119    type Value;
120    /// See [`slice::len`].
121    fn len(&self) -> usize;
122
123    /// See [`slice::is_empty`].
124    fn is_empty(&self) -> bool {
125        self.len() == 0
126    }
127}
128
129impl<S: SliceByValue + ?Sized> SliceByValue for &S {
130    type Value = S::Value;
131    #[inline]
132    fn len(&self) -> usize {
133        (**self).len()
134    }
135}
136
137impl<S: SliceByValue + ?Sized> SliceByValue for &mut S {
138    type Value = S::Value;
139    #[inline]
140    fn len(&self) -> usize {
141        (**self).len()
142    }
143}
144
145#[inline(always)]
146fn assert_index(index: usize, len: usize) {
147    if index >= len {
148        panic!("index out of bounds: the len is {len} but the index is {index}");
149    }
150}
151
152#[inline(always)]
153fn assert_range(range: &impl RangeCheck, len: usize) {
154    if !range.is_valid(len) {
155        panic!("range {range:?} out of range for slice of length {len}: ");
156    }
157}
158
159/// Read-only slice-by-value trait.
160///
161/// The only method that must be implemented is
162/// [`get_value_unchecked`](`SliceByValueGet::get_value_unchecked`).
163pub trait SliceByValueGet: SliceByValue {
164    /// See [the `Index` implementation for slices](slice#impl-Index%3CI%3E-for-%5BT%5D).
165    fn index_value(&self, index: usize) -> Self::Value {
166        assert_index(index, self.len());
167        // SAFETY: index is without bounds
168        unsafe { self.get_value_unchecked(index) }
169    }
170
171    /// See [`slice::get_unchecked`].
172    ///
173    /// For a safe alternative see [`get_value`](SliceByValueGet::get_value)
174    /// or [`index_value`](SliceByValueGet::index_value).
175    ///
176    /// # Safety
177    ///
178    /// The index must be within bounds.
179    unsafe fn get_value_unchecked(&self, index: usize) -> Self::Value;
180
181    /// See [`slice::get`].
182    fn get_value(&self, index: usize) -> Option<Self::Value> {
183        if index < self.len() {
184            // SAFETY: index is without bounds
185            unsafe { Some(self.get_value_unchecked(index)) }
186        } else {
187            None
188        }
189    }
190}
191
192impl<S: SliceByValueGet + ?Sized> SliceByValueGet for &S {
193    fn get_value(&self, index: usize) -> Option<Self::Value> {
194        (**self).get_value(index)
195    }
196    fn index_value(&self, index: usize) -> Self::Value {
197        (**self).index_value(index)
198    }
199    unsafe fn get_value_unchecked(&self, index: usize) -> Self::Value {
200        unsafe { (**self).get_value_unchecked(index) }
201    }
202}
203
204impl<S: SliceByValueGet + ?Sized> SliceByValueGet for &mut S {
205    fn get_value(&self, index: usize) -> Option<Self::Value> {
206        (**self).get_value(index)
207    }
208    fn index_value(&self, index: usize) -> Self::Value {
209        (**self).index_value(index)
210    }
211    unsafe fn get_value_unchecked(&self, index: usize) -> Self::Value {
212        unsafe { (**self).get_value_unchecked(index) }
213    }
214}
215
216/// Mutable slice-by-value trait providing setting methods.
217///
218/// The only method that must be implemented is
219/// [`set_value_unchecked`](`SliceByValueSet::set_value_unchecked`).
220///
221/// If you need to set a value and get the previous value, use
222/// [`SliceByValueRepl`] instead.
223pub trait SliceByValueSet: SliceByValue {
224    /// Sets the value at the given index to the given value without doing
225    /// bounds checking.
226    ///
227    /// For a safe alternative see [`set_value`](SliceByValueSet::set_value).
228    ///
229    /// # Safety
230    ///
231    /// The index must be within bounds.
232    unsafe fn set_value_unchecked(&mut self, index: usize, value: Self::Value);
233
234    /// Sets the value at the given index to the given value.
235    ///
236    /// # Panics
237    ///
238    /// This method will panic is the index is not within bounds.
239    fn set_value(&mut self, index: usize, value: Self::Value) {
240        assert_index(index, self.len());
241        // SAFETY: index is without bounds
242        unsafe {
243            self.set_value_unchecked(index, value);
244        }
245    }
246}
247
248impl<S: SliceByValueSet + ?Sized> SliceByValueSet for &mut S {
249    fn set_value(&mut self, index: usize, value: Self::Value) {
250        (**self).set_value(index, value)
251    }
252    unsafe fn set_value_unchecked(&mut self, index: usize, value: Self::Value) {
253        (**self).set_value_unchecked(index, value)
254    }
255}
256
257/// Mutable slice-by-value trait providing replacement methods.
258///
259/// If you just need to set a value, use [`SliceByValueSet`] instead.
260pub trait SliceByValueRepl: SliceByValue {
261    /// Sets the value at the given index to the given value and
262    /// returns the previous value, without doing bounds checking.
263    ///
264    /// For a safe alternative see [`SliceByValueRepl::replace_value`].
265    ///
266    /// # Safety
267    ///
268    /// The index must be within bounds.
269    unsafe fn replace_value_unchecked(&mut self, index: usize, value: Self::Value) -> Self::Value;
270
271    /// Sets the value at the given index to the given value and
272    /// returns the previous value.
273    ///
274    /// # Panics
275    ///
276    /// This method will panic is the index is not within bounds.
277    fn replace_value(&mut self, index: usize, value: Self::Value) -> Self::Value {
278        assert_index(index, self.len());
279        // SAFETY: index is without bounds
280        unsafe { self.replace_value_unchecked(index, value) }
281    }
282}
283
284impl<S: SliceByValueRepl + ?Sized> SliceByValueRepl for &mut S {
285    fn replace_value(&mut self, index: usize, value: Self::Value) -> Self::Value {
286        (**self).replace_value(index, value)
287    }
288    unsafe fn replace_value_unchecked(&mut self, index: usize, value: Self::Value) -> Self::Value {
289        (**self).replace_value_unchecked(index, value)
290    }
291}
292
293/// A range that can check whether it is within the bounds of a slice.
294///
295/// This traits makes it possible to monomorphize the six different
296/// range checks that are necessary to handle the six type of
297/// ranges available in [`core::ops`].
298pub trait RangeCheck: RangeBounds<usize> + core::fmt::Debug {
299    /// Returns `true` if the range is within the bounds of a slice of given
300    /// length
301    fn is_valid(&self, len: usize) -> bool;
302}
303
304impl RangeCheck for Range<usize> {
305    fn is_valid(&self, len: usize) -> bool {
306        self.start <= len && self.end <= len && self.start <= self.end
307    }
308}
309
310impl RangeCheck for RangeFrom<usize> {
311    fn is_valid(&self, len: usize) -> bool {
312        self.start <= len
313    }
314}
315
316impl RangeCheck for RangeFull {
317    fn is_valid(&self, _len: usize) -> bool {
318        true
319    }
320}
321
322impl RangeCheck for RangeInclusive<usize> {
323    fn is_valid(&self, len: usize) -> bool {
324        // This can be significantly improved once
325        // https://rust-lang.github.io/rfcs/3550-new-range.html is implemented
326        let start = match self.start_bound() {
327            Bound::Included(s) => *s,
328            // SAFETY: we cannot take this branch
329            _ => unsafe { unreachable_unchecked() },
330        };
331        let end = match self.end_bound() {
332            Bound::Included(s) => *s,
333            // SAFETY: we cannot take this branch
334            _ => unsafe { unreachable_unchecked() },
335        };
336        start < len && end < len && start <= end
337    }
338}
339
340impl RangeCheck for RangeTo<usize> {
341    fn is_valid(&self, len: usize) -> bool {
342        self.end <= len
343    }
344}
345
346impl RangeCheck for RangeToInclusive<usize> {
347    fn is_valid(&self, len: usize) -> bool {
348        self.end < len
349    }
350}
351
352/// A GAT-like trait specifying the subslice type.
353///
354/// It implicitly restricts the lifetime `'a` used in `SliceByValueRange` to be
355/// `where Self: 'a`. Moreover, it requires [`SliceByValueGet`].
356///
357/// As in other theoretical applications of GATs (Generic Associated Types),
358/// like [lenders](https://crates.io/crates/lender), using a GAT to express the
359/// type of a subslice is problematic because when bounding the type itself in a
360/// `where` clause using Higher-Ranked Trait Bounds (HRTBs) the bound must be
361/// true for all lifetimes, including `'static`, resulting in the sliced type
362/// having to be `'static` as well.
363///
364/// This is a result of HRTBs not having a way to express qualifiers (`for<'any
365/// where Self: 'any> Self: Trait`) and effectively making HRTBs only useful
366/// when you want to express a trait constraint on ALL lifetimes, including
367/// `'static` (`for<'all> Self: trait`)
368///
369/// Please see [Sabrina's Blog][1] for more information, and how a trait like
370/// this can be used to solve it by implicitly restricting HRTBs.
371///
372/// [1]:
373///     <https://sabrinajewson.org/blog/the-better-alternative-to-lifetime-gats>
374pub trait SliceByValueSubsliceGat<'a, __Implicit: ImplBound = Ref<'a, Self>>:
375    SliceByValueGet
376{
377    type Subslice: 'a + SliceByValueGet<Value = Self::Value> + SliceByValueSubslice;
378}
379
380impl<'a, T: SliceByValueSubsliceGat<'a> + ?Sized> SliceByValueSubsliceGat<'a> for &T {
381    type Subslice = <T as SliceByValueSubsliceGat<'a>>::Subslice;
382}
383
384impl<'a, T: SliceByValueSubsliceGat<'a> + ?Sized> SliceByValueSubsliceGat<'a> for &mut T {
385    type Subslice = <T as SliceByValueSubsliceGat<'a>>::Subslice;
386}
387
388/// A convenience type representing the type of subslice
389/// of a type implementing [`SliceByValueSubsliceGat`].
390#[allow(type_alias_bounds)] // yeah the type alias bounds are not enforced, but they are useful for documentation
391pub type Subslice<'a, T: SliceByValueSubsliceGat<'a>> =
392    <T as SliceByValueSubsliceGat<'a>>::Subslice;
393
394/// A trait implementing subslicing for a specific range parameter.
395///
396/// The user should never see this trait. [`SliceByValueSubslice`] combines all
397/// instances of this trait with `R` equal to the various kind of standard
398/// ranges ([`core::ops::Range`], [`core::ops::RangeFull`], etc.).
399///
400/// The only method that must be implemented is
401/// [`get_subslice_unchecked`](`SliceByValueSubsliceRange::get_subslice_unchecked`).
402pub trait SliceByValueSubsliceRange<R: RangeCheck>: for<'a> SliceByValueSubsliceGat<'a> {
403    /// See [the `Index` implementation for slices](slice#impl-Index%3CI%3E-for-%5BT%5D).
404    fn index_subslice(&self, range: R) -> Subslice<'_, Self> {
405        assert_range(&range, self.len());
406        unsafe {
407            // SAFETY: The range is checked to be within bounds.
408            self.get_subslice_unchecked(range)
409        }
410    }
411
412    /// See [`slice::get_unchecked`].
413    ///
414    /// For a safe alternative see
415    /// [`get_subslice`](SliceByValueSubsliceRange::get_subslice) or
416    /// [`index_subslice`](SliceByValueSubsliceRange::index_subslice).
417    ///
418    /// # Safety
419    ///
420    /// The range must be within bounds.
421    unsafe fn get_subslice_unchecked(&self, range: R) -> Subslice<'_, Self>;
422
423    /// See [`slice::get`].
424    fn get_subslice(&self, range: R) -> Option<Subslice<'_, Self>> {
425        if range.is_valid(self.len()) {
426            // SAFETY: range is checked to be within bounds.
427            unsafe { Some(self.get_subslice_unchecked(range)) }
428        } else {
429            None
430        }
431    }
432}
433
434impl<R: RangeCheck, S: SliceByValueSubsliceRange<R> + ?Sized> SliceByValueSubsliceRange<R> for &S {
435    fn get_subslice(&self, range: R) -> Option<Subslice<'_, Self>> {
436        (**self).get_subslice(range)
437    }
438    fn index_subslice(&self, range: R) -> Subslice<'_, Self> {
439        (**self).index_subslice(range)
440    }
441    unsafe fn get_subslice_unchecked(&self, range: R) -> Subslice<'_, Self> {
442        unsafe { (**self).get_subslice_unchecked(range) }
443    }
444}
445impl<R: RangeCheck, S: SliceByValueSubsliceRange<R> + ?Sized> SliceByValueSubsliceRange<R>
446    for &mut S
447{
448    fn get_subslice(&self, range: R) -> Option<Subslice<'_, Self>> {
449        (**self).get_subslice(range)
450    }
451    fn index_subslice(&self, range: R) -> Subslice<'_, Self> {
452        (**self).index_subslice(range)
453    }
454    unsafe fn get_subslice_unchecked(&self, range: R) -> Subslice<'_, Self> {
455        unsafe { (**self).get_subslice_unchecked(range) }
456    }
457}
458
459// TODO: can we implement traits conditionally on the associated type? Like,
460// replace only if it present in the root slice?
461
462/// A GAT-like trait specifying the mutable subslice type.
463///
464/// See [`SliceByValueSubsliceGat`].
465pub trait SliceByValueSubsliceGatMut<'a, __Implicit = &'a Self>:
466    SliceByValueSet + SliceByValueRepl
467{
468    type Subslice: 'a
469        + SliceByValueSet<Value = Self::Value>
470        + SliceByValueRepl<Value = Self::Value>
471        + SliceByValueSubsliceGatMut<'a, Subslice = Self::Subslice> // recursion
472        + SliceByValueSubsliceMut;
473}
474
475impl<'a, T: SliceByValueSubsliceGatMut<'a> + ?Sized> SliceByValueSubsliceGatMut<'a> for &mut T {
476    type Subslice = <T as SliceByValueSubsliceGatMut<'a>>::Subslice;
477}
478
479/// A convenience type representing the type of subslice
480/// of a type implementing [`SliceByValueSubsliceGatMut`].
481#[allow(type_alias_bounds)] // yeah the type alias bounds are not enforced, but they are useful for documentation
482pub type SubsliceMut<'a, T: SliceByValueSubsliceGatMut<'a>> =
483    <T as SliceByValueSubsliceGatMut<'a>>::Subslice;
484
485/// A trait implementing mutable subslicing for a specific range parameter.
486///
487///  The user should never see this trait. [`SliceByValueSubsliceMut`] combines
488/// all instances of this trait with `R` equal to the various kind of standard
489/// ranges ([`core::ops::Range`], [`core::ops::RangeFull`], etc.).
490///
491/// The only method that must be implemented is
492/// [`get_subslice_unchecked_mut`](`SliceByValueSubsliceRangeMut::get_subslice_unchecked_mut`).
493pub trait SliceByValueSubsliceRangeMut<R: RangeCheck>:
494    for<'a> SliceByValueSubsliceGatMut<'a>
495{
496    /// See [the `Index` implementation for slices](slice#impl-Index%3CI%3E-for-%5BT%5D).
497    fn index_subslice_mut(&mut self, range: R) -> SubsliceMut<'_, Self> {
498        assert_range(&range, self.len());
499        unsafe {
500            // SAFETY: The range is checked to be within bounds.
501            self.get_subslice_unchecked_mut(range)
502        }
503    }
504
505    /// See [`slice::get_unchecked`].
506    ///
507    /// For a safe alternative see
508    /// [`get_subslice_mut`](SliceByValueSubsliceRangeMut::get_subslice_mut) or
509    /// [`index_subslice_mut`](SliceByValueSubsliceRangeMut::index_subslice_mut).
510    ///
511    /// # Safety
512    ///
513    /// The range must be within bounds.
514    unsafe fn get_subslice_unchecked_mut(&mut self, range: R) -> SubsliceMut<'_, Self>;
515
516    /// See [`slice::get`].
517    fn get_subslice_mut(&mut self, range: R) -> Option<SubsliceMut<'_, Self>> {
518        if range.is_valid(self.len()) {
519            // SAFETY: range is checked to be within bounds.
520            unsafe { Some(self.get_subslice_unchecked_mut(range)) }
521        } else {
522            None
523        }
524    }
525}
526
527impl<R: RangeCheck, S: SliceByValueSubsliceRangeMut<R> + ?Sized> SliceByValueSubsliceRangeMut<R>
528    for &mut S
529{
530    fn get_subslice_mut(&mut self, range: R) -> Option<SubsliceMut<'_, Self>> {
531        (**self).get_subslice_mut(range)
532    }
533    fn index_subslice_mut(&mut self, range: R) -> SubsliceMut<'_, Self> {
534        (**self).index_subslice_mut(range)
535    }
536    unsafe fn get_subslice_unchecked_mut(&mut self, range: R) -> SubsliceMut<'_, Self> {
537        (**self).get_subslice_unchecked_mut(range)
538    }
539}
540
541/// A convenience trait combining all instances of [`SliceByValueSubsliceRange`]
542/// with `R` equal to the various kind of standard ranges ([`core::ops::Range`],
543/// [`core::ops::RangeFull`], etc.).
544///
545/// A blanket implementation automatically implements the trait if all necessary
546/// implementations of [`SliceByValueSubsliceRange`] are available.
547pub trait SliceByValueSubslice:
548    SliceByValueSubsliceRange<Range<usize>>
549    + SliceByValueSubsliceRange<RangeFrom<usize>>
550    + SliceByValueSubsliceRange<RangeFull>
551    + SliceByValueSubsliceRange<RangeInclusive<usize>>
552    + SliceByValueSubsliceRange<RangeTo<usize>>
553    + SliceByValueSubsliceRange<RangeToInclusive<usize>>
554{
555}
556
557impl<U> SliceByValueSubslice for U
558where
559    U: SliceByValueSubsliceRange<Range<usize>>,
560    U: SliceByValueSubsliceRange<RangeFrom<usize>>,
561    U: SliceByValueSubsliceRange<RangeFull>,
562    U: SliceByValueSubsliceRange<RangeInclusive<usize>>,
563    U: SliceByValueSubsliceRange<RangeTo<usize>>,
564    U: SliceByValueSubsliceRange<RangeToInclusive<usize>>,
565{
566}
567
568/// A convenience trait combining all instances of
569/// [`SliceByValueSubsliceRangeMut`] with `R` equal to the various kind of
570/// standard ranges ([`core::ops::Range`], [`core::ops::RangeFull`], etc.).
571///
572/// A blanket implementation automatically implements the trait if all necessary
573/// implementations of [`SliceByValueSubsliceMut`] are available.
574pub trait SliceByValueSubsliceMut:
575    SliceByValueSubsliceRangeMut<Range<usize>>
576    + SliceByValueSubsliceRangeMut<RangeFrom<usize>>
577    + SliceByValueSubsliceRangeMut<RangeFull>
578    + SliceByValueSubsliceRangeMut<RangeInclusive<usize>>
579    + SliceByValueSubsliceRangeMut<RangeTo<usize>>
580    + SliceByValueSubsliceRangeMut<RangeToInclusive<usize>>
581{
582}
583
584impl<U> SliceByValueSubsliceMut for U
585where
586    U: SliceByValueSubsliceRangeMut<Range<usize>>,
587    U: SliceByValueSubsliceRangeMut<RangeFrom<usize>>,
588    U: SliceByValueSubsliceRangeMut<RangeFull>,
589    U: SliceByValueSubsliceRangeMut<RangeInclusive<usize>>,
590    U: SliceByValueSubsliceRangeMut<RangeTo<usize>>,
591    U: SliceByValueSubsliceRangeMut<RangeToInclusive<usize>>,
592{
593}
594
595#[cfg(feature = "alloc")]
596mod alloc_impls {
597    use super::*;
598    #[cfg(all(feature = "alloc", not(feature = "std")))]
599    use alloc::boxed::Box;
600
601    impl<S: SliceByValue + ?Sized> SliceByValue for Box<S> {
602        type Value = S::Value;
603        #[inline]
604        fn len(&self) -> usize {
605            (**self).len()
606        }
607    }
608
609    impl<S: SliceByValueGet + ?Sized> SliceByValueGet for Box<S> {
610        fn get_value(&self, index: usize) -> Option<Self::Value> {
611            (**self).get_value(index)
612        }
613        fn index_value(&self, index: usize) -> Self::Value {
614            (**self).index_value(index)
615        }
616        unsafe fn get_value_unchecked(&self, index: usize) -> Self::Value {
617            unsafe { (**self).get_value_unchecked(index) }
618        }
619    }
620
621    impl<S: SliceByValueSet + ?Sized> SliceByValueSet for Box<S> {
622        fn set_value(&mut self, index: usize, value: Self::Value) {
623            (**self).set_value(index, value)
624        }
625        unsafe fn set_value_unchecked(&mut self, index: usize, value: Self::Value) {
626            unsafe { (**self).set_value_unchecked(index, value) }
627        }
628    }
629
630    impl<S: SliceByValueRepl + ?Sized> SliceByValueRepl for Box<S> {
631        fn replace_value(&mut self, index: usize, value: Self::Value) -> Self::Value {
632            (**self).replace_value(index, value)
633        }
634        unsafe fn replace_value_unchecked(
635            &mut self,
636            index: usize,
637            value: Self::Value,
638        ) -> Self::Value {
639            unsafe { (**self).replace_value_unchecked(index, value) }
640        }
641    }
642
643    impl<'a, S: SliceByValueSubsliceGat<'a> + ?Sized> SliceByValueSubsliceGat<'a> for Box<S> {
644        type Subslice = S::Subslice;
645    }
646    impl<'a, S: SliceByValueSubsliceGatMut<'a> + ?Sized> SliceByValueSubsliceGatMut<'a> for Box<S> {
647        type Subslice = S::Subslice;
648    }
649
650    macro_rules! impl_range_alloc {
651        ($range:ty) => {
652            impl<S: SliceByValueSubsliceRange<$range> + ?Sized> SliceByValueSubsliceRange<$range>
653                for Box<S>
654            {
655                #[inline]
656                fn get_subslice(&self, index: $range) -> Option<Subslice<'_, Self>> {
657                    (**self).get_subslice(index)
658                }
659
660                #[inline]
661                fn index_subslice(&self, index: $range) -> Subslice<'_, Self> {
662                    (**self).index_subslice(index)
663                }
664
665                #[inline]
666                unsafe fn get_subslice_unchecked(&self, index: $range) -> Subslice<'_, Self> {
667                    unsafe { (**self).get_subslice_unchecked(index) }
668                }
669            }
670            impl<S: SliceByValueSubsliceRangeMut<$range> + ?Sized>
671                SliceByValueSubsliceRangeMut<$range> for Box<S>
672            {
673                #[inline]
674                fn get_subslice_mut(&mut self, index: $range) -> Option<SubsliceMut<'_, Self>> {
675                    (**self).get_subslice_mut(index)
676                }
677
678                #[inline]
679                fn index_subslice_mut(&mut self, index: $range) -> SubsliceMut<'_, Self> {
680                    (**self).index_subslice_mut(index)
681                }
682
683                #[inline]
684                unsafe fn get_subslice_unchecked_mut(
685                    &mut self,
686                    index: $range,
687                ) -> SubsliceMut<'_, Self> {
688                    unsafe { (**self).get_subslice_unchecked_mut(index) }
689                }
690            }
691        };
692    }
693
694    impl_range_alloc!(RangeFull);
695    impl_range_alloc!(RangeFrom<usize>);
696    impl_range_alloc!(RangeTo<usize>);
697    impl_range_alloc!(Range<usize>);
698    impl_range_alloc!(RangeInclusive<usize>);
699    impl_range_alloc!(RangeToInclusive<usize>);
700}
701
702#[cfg(feature = "std")]
703mod std_impls {
704    use super::*;
705    use std::{rc::Rc, sync::Arc};
706
707    impl<S: SliceByValue + ?Sized> SliceByValue for Arc<S> {
708        type Value = S::Value;
709        #[inline]
710        fn len(&self) -> usize {
711            (**self).len()
712        }
713    }
714
715    impl<S: SliceByValueGet + ?Sized> SliceByValueGet for Arc<S> {
716        fn get_value(&self, index: usize) -> Option<Self::Value> {
717            (**self).get_value(index)
718        }
719        fn index_value(&self, index: usize) -> Self::Value {
720            (**self).index_value(index)
721        }
722        unsafe fn get_value_unchecked(&self, index: usize) -> Self::Value {
723            (**self).get_value_unchecked(index)
724        }
725    }
726    impl<'a, S: SliceByValueSubsliceGat<'a> + ?Sized> SliceByValueSubsliceGat<'a> for Arc<S> {
727        type Subslice = S::Subslice;
728    }
729
730    impl<S: SliceByValue + ?Sized> SliceByValue for Rc<S> {
731        type Value = S::Value;
732        #[inline]
733        fn len(&self) -> usize {
734            (**self).len()
735        }
736    }
737
738    impl<S: SliceByValueGet + ?Sized> SliceByValueGet for Rc<S> {
739        fn get_value(&self, index: usize) -> Option<Self::Value> {
740            (**self).get_value(index)
741        }
742        fn index_value(&self, index: usize) -> Self::Value {
743            (**self).index_value(index)
744        }
745        unsafe fn get_value_unchecked(&self, index: usize) -> Self::Value {
746            (**self).get_value_unchecked(index)
747        }
748    }
749
750    impl<'a, S: SliceByValueSubsliceGat<'a> + ?Sized> SliceByValueSubsliceGat<'a> for Rc<S> {
751        type Subslice = S::Subslice;
752    }
753
754    macro_rules! impl_range_arc_and_rc {
755        ($range:ty) => {
756            impl<S: SliceByValueSubsliceRange<$range> + ?Sized> SliceByValueSubsliceRange<$range>
757                for Rc<S>
758            {
759                #[inline]
760                fn get_subslice(&self, index: $range) -> Option<Subslice<'_, Self>> {
761                    (**self).get_subslice(index)
762                }
763
764                #[inline]
765                fn index_subslice(&self, index: $range) -> Subslice<'_, Self> {
766                    (**self).index_subslice(index)
767                }
768
769                #[inline]
770                unsafe fn get_subslice_unchecked(&self, index: $range) -> Subslice<'_, Self> {
771                    unsafe { (**self).get_subslice_unchecked(index) }
772                }
773            }
774            impl<S: SliceByValueSubsliceRange<$range> + ?Sized> SliceByValueSubsliceRange<$range>
775                for Arc<S>
776            {
777                #[inline]
778                fn get_subslice(&self, index: $range) -> Option<Subslice<'_, Self>> {
779                    (**self).get_subslice(index)
780                }
781
782                #[inline]
783                fn index_subslice(&self, index: $range) -> Subslice<'_, Self> {
784                    (**self).index_subslice(index)
785                }
786
787                #[inline]
788                unsafe fn get_subslice_unchecked(&self, index: $range) -> Subslice<'_, Self> {
789                    unsafe { (**self).get_subslice_unchecked(index) }
790                }
791            }
792        };
793    }
794
795    impl_range_arc_and_rc!(RangeFull);
796    impl_range_arc_and_rc!(RangeFrom<usize>);
797    impl_range_arc_and_rc!(RangeTo<usize>);
798    impl_range_arc_and_rc!(Range<usize>);
799    impl_range_arc_and_rc!(RangeInclusive<usize>);
800    impl_range_arc_and_rc!(RangeToInclusive<usize>);
801}
802
803#[macro_export]
804macro_rules! impl_subslices {
805    ($ty:ty) => {
806        pub struct SubsliceImpl<'a> {
807            slice: &'a $ty,
808            start: usize,
809            end: usize,
810        }
811
812        impl<'a> SliceByValue for SubsliceImpl<'a> {
813            type Value = <$ty as SliceByValue>::Value;
814
815            #[inline]
816            fn len(&self) -> usize {
817                self.end - self.start
818            }
819        }
820
821        impl<'a> SliceByValueSubsliceGat<'a> for $ty {
822            type Subslice = SubsliceImpl<'a>;
823        }
824
825        impl<'a> SliceByValueSubsliceRange<core::ops::Range<usize>> for $ty {
826            unsafe fn get_subslice_unchecked(
827                &self,
828                range: core::ops::Range<usize>,
829            ) -> Subslice<'_, Self> {
830                unsafe {
831                    SubsliceImpl {
832                        slice: &self,
833                        start: range.start,
834                        end: range.end,
835                    }
836                }
837            }
838        }
839        impl<'a> SliceByValueSubsliceRange<core::ops::RangeFrom<usize>> for $ty {
840            unsafe fn get_subslice_unchecked(
841                &self,
842                range: core::ops::RangeFrom<usize>,
843            ) -> Subslice<'_, Self> {
844                unsafe {
845                    SubsliceImpl {
846                        slice: &self,
847                        start: range.start,
848                        end: self.len(),
849                    }
850                }
851            }
852        }
853        impl<'a> SliceByValueSubsliceRange<core::ops::RangeToInclusive<usize>> for $ty {
854            unsafe fn get_subslice_unchecked(
855                &self,
856                range: core::ops::RangeToInclusive<usize>,
857            ) -> Subslice<'_, Self> {
858                unsafe {
859                    SubsliceImpl {
860                        slice: &self,
861                        start: 0,
862                        end: range.end + 1,
863                    }
864                }
865            }
866        }
867        impl<'a> SliceByValueSubsliceRange<core::ops::RangeFull> for $ty {
868            unsafe fn get_subslice_unchecked(
869                &self,
870                _range: core::ops::RangeFull,
871            ) -> Subslice<'_, Self> {
872                unsafe {
873                    SubsliceImpl {
874                        slice: &self,
875                        start: 0,
876                        end: self.len(),
877                    }
878                }
879            }
880        }
881        impl<'a> SliceByValueSubsliceRange<core::ops::RangeInclusive<usize>> for $ty {
882            unsafe fn get_subslice_unchecked(
883                &self,
884                range: core::ops::RangeInclusive<usize>,
885            ) -> Subslice<'_, Self> {
886                use core::ops::{Bound, RangeBounds};
887                use std::hint::unreachable_unchecked;
888
889                let start = match range.start_bound() {
890                    Bound::Included(s) => *s,
891                    // SAFETY: we cannot take this branch
892                    _ => unsafe { unreachable_unchecked() },
893                };
894                let end = match range.end_bound() {
895                    Bound::Included(s) => *s,
896                    // SAFETY: we cannot take this branch
897                    _ => unsafe { unreachable_unchecked() },
898                };
899                unsafe {
900                    SubsliceImpl {
901                        slice: &self,
902                        start: start,
903                        end: end + 1,
904                    }
905                }
906            }
907        }
908
909        impl<'a> SliceByValueSubsliceRange<core::ops::RangeTo<usize>> for $ty {
910            unsafe fn get_subslice_unchecked(
911                &self,
912                range: core::ops::RangeTo<usize>,
913            ) -> Subslice<'_, Self> {
914                unsafe {
915                    SubsliceImpl {
916                        slice: &self,
917                        start: 0,
918                        end: range.end,
919                    }
920                }
921            }
922        }
923
924        impl<'a> SliceByValueGet for SubsliceImpl<'a> {
925            unsafe fn get_value_unchecked(&self, index: usize) -> Self::Value {
926                self.slice.get_value_unchecked(index + self.start)
927            }
928        }
929
930        impl<'a, 'b> SliceByValueSubsliceGat<'b> for SubsliceImpl<'a> {
931            type Subslice = SubsliceImpl<'b>;
932        }
933
934        impl<'a> SliceByValueSubsliceRange<core::ops::Range<usize>> for SubsliceImpl<'a> {
935            unsafe fn get_subslice_unchecked(
936                &self,
937                range: core::ops::Range<usize>,
938            ) -> Subslice<'_, Self> {
939                unsafe {
940                    SubsliceImpl {
941                        slice: self.slice,
942                        start: self.start + range.start,
943                        end: self.start + range.end,
944                    }
945                }
946            }
947        }
948        impl<'a> SliceByValueSubsliceRange<core::ops::RangeFrom<usize>> for SubsliceImpl<'a> {
949            unsafe fn get_subslice_unchecked(
950                &self,
951                range: core::ops::RangeFrom<usize>,
952            ) -> Subslice<'_, Self> {
953                unsafe {
954                    SubsliceImpl {
955                        slice: self.slice,
956                        start: self.start + range.start,
957                        end: self.end,
958                    }
959                }
960            }
961        }
962        impl<'a> SliceByValueSubsliceRange<core::ops::RangeToInclusive<usize>>
963            for SubsliceImpl<'a>
964        {
965            unsafe fn get_subslice_unchecked(
966                &self,
967                range: core::ops::RangeToInclusive<usize>,
968            ) -> Subslice<'_, Self> {
969                unsafe {
970                    SubsliceImpl {
971                        slice: self.slice,
972                        start: self.start,
973                        end: self.start + range.end + 1,
974                    }
975                }
976            }
977        }
978        impl<'a> SliceByValueSubsliceRange<core::ops::RangeFull> for SubsliceImpl<'a> {
979            unsafe fn get_subslice_unchecked(
980                &self,
981                _range: core::ops::RangeFull,
982            ) -> Subslice<'_, Self> {
983                unsafe {
984                    SubsliceImpl {
985                        slice: self.slice,
986                        start: self.start,
987                        end: self.end,
988                    }
989                }
990            }
991        }
992        impl<'a> SliceByValueSubsliceRange<core::ops::RangeInclusive<usize>> for SubsliceImpl<'a> {
993            unsafe fn get_subslice_unchecked(
994                &self,
995                range: core::ops::RangeInclusive<usize>,
996            ) -> Subslice<'_, Self> {
997                use core::ops::{Bound, RangeBounds};
998                use std::hint::unreachable_unchecked;
999                let start = match range.start_bound() {
1000                    Bound::Included(s) => *s,
1001                    // SAFETY: we cannot take this branch
1002                    _ => unsafe { unreachable_unchecked() },
1003                };
1004                let end = match range.end_bound() {
1005                    Bound::Included(s) => *s,
1006                    // SAFETY: we cannot take this branch
1007                    _ => unsafe { unreachable_unchecked() },
1008                };
1009                unsafe {
1010                    SubsliceImpl {
1011                        slice: self.slice,
1012                        start: self.start + start,
1013                        end: self.start + end + 1,
1014                    }
1015                }
1016            }
1017        }
1018
1019        impl<'a> SliceByValueSubsliceRange<core::ops::RangeTo<usize>> for SubsliceImpl<'a> {
1020            unsafe fn get_subslice_unchecked(
1021                &self,
1022                range: core::ops::RangeTo<usize>,
1023            ) -> Subslice<'_, Self> {
1024                unsafe {
1025                    SubsliceImpl {
1026                        slice: self.slice,
1027                        start: self.start,
1028                        end: self.start + range.end,
1029                    }
1030                }
1031            }
1032        }
1033
1034        pub struct Iter<'a, 'b> {
1035            subslice: &'b SubsliceImpl<'a>,
1036            index: usize,
1037        }
1038
1039        impl<'a, 'b> Iterator for Iter<'a, 'b> {
1040            type Item = <$ty as SliceByValue>::Value;
1041
1042            #[inline]
1043            fn next(&mut self) -> Option<Self::Item> {
1044                if self.index < self.subslice.len() {
1045                    let value = unsafe { self.subslice.get_value_unchecked(self.index) };
1046                    self.index += 1;
1047                    Some(value)
1048                } else {
1049                    None
1050                }
1051            }
1052        }
1053
1054        impl<'a> IterableByValue for SubsliceImpl<'a> {
1055            type Item = <$ty as SliceByValue>::Value;
1056            type Iter<'b>
1057                = Iter<'a, 'b>
1058            where
1059                Self: 'b;
1060
1061            #[inline]
1062            fn iter_value(&self) -> Self::Iter<'_> {
1063                Iter {
1064                    subslice: self,
1065                    index: 0,
1066                }
1067            }
1068        }
1069
1070        impl<'a> IterableByValueFrom for SubsliceImpl<'a> {
1071            type IterFrom<'b>
1072                = Iter<'a, 'b>
1073            where
1074                Self: 'b;
1075
1076            #[inline]
1077            fn iter_value_from(&self, from: usize) -> Self::Iter<'_> {
1078                let len = self.len();
1079                if from > len {
1080                    panic!(
1081                        "index out of bounds: the len is {len} but the starting index is {from}"
1082                    );
1083                }
1084                Iter {
1085                    subslice: self,
1086                    index: from,
1087                }
1088            }
1089        }
1090    };
1091}
1092
1093#[macro_export]
1094macro_rules! impl_subslices_mut {
1095    ($ty:ty) => {
1096        pub struct SubsliceImplMut<'a> {
1097            slice: &'a mut $ty,
1098            start: usize,
1099            end: usize,
1100        }
1101
1102        impl<'a> SliceByValue for SubsliceImplMut<'a> {
1103            type Value = <$ty as SliceByValue>::Value;
1104
1105            #[inline]
1106            fn len(&self) -> usize {
1107                self.end - self.start
1108            }
1109        }
1110
1111        impl<'a> SliceByValueSubsliceGatMut<'a> for $ty {
1112            type Subslice = SubsliceImplMut<'a>;
1113        }
1114
1115        impl<'a> SliceByValueSubsliceRangeMut<core::ops::Range<usize>> for $ty {
1116            unsafe fn get_subslice_unchecked_mut(
1117                &mut self,
1118                range: core::ops::Range<usize>,
1119            ) -> SubsliceMut<'_, Self> {
1120                unsafe {
1121                    SubsliceImplMut {
1122                        slice: self,
1123                        start: range.start,
1124                        end: range.end,
1125                    }
1126                }
1127            }
1128        }
1129        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeFrom<usize>> for $ty {
1130            unsafe fn get_subslice_unchecked_mut(
1131                &mut self,
1132                range: core::ops::RangeFrom<usize>,
1133            ) -> SubsliceMut<'_, Self> {
1134                unsafe {
1135                    let end = self.len();
1136                    SubsliceImplMut {
1137                        slice: self,
1138                        start: range.start,
1139                        end,
1140                    }
1141                }
1142            }
1143        }
1144        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeToInclusive<usize>> for $ty {
1145            unsafe fn get_subslice_unchecked_mut(
1146                &mut self,
1147                range: core::ops::RangeToInclusive<usize>,
1148            ) -> SubsliceMut<'_, Self> {
1149                unsafe {
1150                    SubsliceImplMut {
1151                        slice: self,
1152                        start: 0,
1153                        end: range.end + 1,
1154                    }
1155                }
1156            }
1157        }
1158        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeFull> for $ty {
1159            unsafe fn get_subslice_unchecked_mut(
1160                &mut self,
1161                _range: core::ops::RangeFull,
1162            ) -> SubsliceMut<'_, Self> {
1163                unsafe {
1164                    let end = self.len();
1165                    SubsliceImplMut {
1166                        slice: self,
1167                        start: 0,
1168                        end,
1169                    }
1170                }
1171            }
1172        }
1173        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeInclusive<usize>> for $ty {
1174            unsafe fn get_subslice_unchecked_mut(
1175                &mut self,
1176                range: core::ops::RangeInclusive<usize>,
1177            ) -> SubsliceMut<'_, Self> {
1178                use core::ops::{Bound, RangeBounds};
1179                use std::hint::unreachable_unchecked;
1180
1181                let start = match range.start_bound() {
1182                    Bound::Included(s) => *s,
1183                    // SAFETY: we cannot take this branch
1184                    _ => unsafe { unreachable_unchecked() },
1185                };
1186                let end = match range.end_bound() {
1187                    Bound::Included(s) => *s,
1188                    // SAFETY: we cannot take this branch
1189                    _ => unsafe { unreachable_unchecked() },
1190                };
1191                unsafe {
1192                    SubsliceImplMut {
1193                        slice: self,
1194                        start: start,
1195                        end: end + 1,
1196                    }
1197                }
1198            }
1199        }
1200
1201        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeTo<usize>> for $ty {
1202            unsafe fn get_subslice_unchecked_mut(
1203                &mut self,
1204                range: core::ops::RangeTo<usize>,
1205            ) -> SubsliceMut<'_, Self> {
1206                unsafe {
1207                    SubsliceImplMut {
1208                        slice: self,
1209                        start: 0,
1210                        end: range.end,
1211                    }
1212                }
1213            }
1214        }
1215
1216        impl<'a> SliceByValueGet for SubsliceImplMut<'a> {
1217            unsafe fn get_value_unchecked(&self, index: usize) -> <$ty as SliceByValue>::Value {
1218                self.slice.get_value_unchecked(index + self.start)
1219            }
1220        }
1221
1222        impl<'a, 'b> SliceByValueSubsliceGat<'b> for SubsliceImplMut<'a> {
1223            type Subslice = SubsliceImpl<'b>;
1224        }
1225
1226        impl<'a> SliceByValueSubsliceRange<core::ops::Range<usize>> for SubsliceImplMut<'a> {
1227            unsafe fn get_subslice_unchecked(
1228                &self,
1229                range: core::ops::Range<usize>,
1230            ) -> Subslice<'_, Self> {
1231                unsafe {
1232                    SubsliceImpl {
1233                        slice: self.slice,
1234                        start: self.start + range.start,
1235                        end: self.start + range.end,
1236                    }
1237                }
1238            }
1239        }
1240        impl<'a> SliceByValueSubsliceRange<core::ops::RangeFrom<usize>> for SubsliceImplMut<'a> {
1241            unsafe fn get_subslice_unchecked(
1242                &self,
1243                range: core::ops::RangeFrom<usize>,
1244            ) -> Subslice<'_, Self> {
1245                unsafe {
1246                    SubsliceImpl {
1247                        slice: self.slice,
1248                        start: self.start + range.start,
1249                        end: self.end,
1250                    }
1251                }
1252            }
1253        }
1254        impl<'a> SliceByValueSubsliceRange<core::ops::RangeToInclusive<usize>>
1255            for SubsliceImplMut<'a>
1256        {
1257            unsafe fn get_subslice_unchecked(
1258                &self,
1259                range: core::ops::RangeToInclusive<usize>,
1260            ) -> Subslice<'_, Self> {
1261                unsafe {
1262                    SubsliceImpl {
1263                        slice: self.slice,
1264                        start: self.start,
1265                        end: self.start + range.end + 1,
1266                    }
1267                }
1268            }
1269        }
1270        impl<'a> SliceByValueSubsliceRange<core::ops::RangeFull> for SubsliceImplMut<'a> {
1271            unsafe fn get_subslice_unchecked(
1272                &self,
1273                _range: core::ops::RangeFull,
1274            ) -> Subslice<'_, Self> {
1275                unsafe {
1276                    SubsliceImpl {
1277                        slice: self.slice,
1278                        start: self.start,
1279                        end: self.end,
1280                    }
1281                }
1282            }
1283        }
1284        impl<'a> SliceByValueSubsliceRange<core::ops::RangeInclusive<usize>>
1285            for SubsliceImplMut<'a>
1286        {
1287            unsafe fn get_subslice_unchecked(
1288                &self,
1289                range: core::ops::RangeInclusive<usize>,
1290            ) -> Subslice<'_, Self> {
1291                use core::ops::{Bound, RangeBounds};
1292                use std::hint::unreachable_unchecked;
1293                let start = match range.start_bound() {
1294                    Bound::Included(s) => *s,
1295                    // SAFETY: we cannot take this branch
1296                    _ => unsafe { unreachable_unchecked() },
1297                };
1298                let end = match range.end_bound() {
1299                    Bound::Included(s) => *s,
1300                    // SAFETY: we cannot take this branch
1301                    _ => unsafe { unreachable_unchecked() },
1302                };
1303                unsafe {
1304                    SubsliceImpl {
1305                        slice: self.slice,
1306
1307                        start: self.start + start,
1308                        end: self.start + end + 1,
1309                    }
1310                }
1311            }
1312        }
1313
1314        impl<'a> SliceByValueSubsliceRange<core::ops::RangeTo<usize>> for SubsliceImplMut<'a> {
1315            unsafe fn get_subslice_unchecked(
1316                &self,
1317                range: core::ops::RangeTo<usize>,
1318            ) -> Subslice<'_, Self> {
1319                unsafe {
1320                    SubsliceImpl {
1321                        slice: self.slice,
1322                        start: self.start,
1323                        end: self.start + range.end,
1324                    }
1325                }
1326            }
1327        }
1328
1329        impl<'a> SliceByValueSet for SubsliceImplMut<'a> {
1330            unsafe fn set_value_unchecked(&mut self, index: usize, value: Self::Value) {
1331                self.slice.set_value_unchecked(index + self.start, value)
1332            }
1333        }
1334
1335        impl<'a> SliceByValueRepl for SubsliceImplMut<'a> {
1336            unsafe fn replace_value_unchecked(
1337                &mut self,
1338                index: usize,
1339                value: Self::Value,
1340            ) -> Self::Value {
1341                self.slice
1342                    .replace_value_unchecked(index + self.start, value)
1343            }
1344        }
1345
1346        impl<'a, 'b> SliceByValueSubsliceGatMut<'b> for SubsliceImplMut<'a> {
1347            type Subslice = SubsliceImplMut<'b>;
1348        }
1349
1350        impl<'a> SliceByValueSubsliceRangeMut<core::ops::Range<usize>> for SubsliceImplMut<'a> {
1351            unsafe fn get_subslice_unchecked_mut(
1352                &mut self,
1353                range: core::ops::Range<usize>,
1354            ) -> SubsliceMut<'_, Self> {
1355                unsafe {
1356                    SubsliceImplMut {
1357                        slice: self.slice,
1358                        start: self.start + range.start,
1359                        end: self.start + range.end,
1360                    }
1361                }
1362            }
1363        }
1364        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeFrom<usize>> for SubsliceImplMut<'a> {
1365            unsafe fn get_subslice_unchecked_mut(
1366                &mut self,
1367                range: core::ops::RangeFrom<usize>,
1368            ) -> SubsliceMut<'_, Self> {
1369                unsafe {
1370                    SubsliceImplMut {
1371                        slice: self.slice,
1372                        start: self.start + range.start,
1373                        end: self.end,
1374                    }
1375                }
1376            }
1377        }
1378        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeToInclusive<usize>>
1379            for SubsliceImplMut<'a>
1380        {
1381            unsafe fn get_subslice_unchecked_mut(
1382                &mut self,
1383                range: core::ops::RangeToInclusive<usize>,
1384            ) -> SubsliceMut<'_, Self> {
1385                unsafe {
1386                    SubsliceImplMut {
1387                        slice: self.slice,
1388                        start: self.start,
1389                        end: self.start + range.end + 1,
1390                    }
1391                }
1392            }
1393        }
1394        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeFull> for SubsliceImplMut<'a> {
1395            unsafe fn get_subslice_unchecked_mut(
1396                &mut self,
1397                _range: core::ops::RangeFull,
1398            ) -> SubsliceMut<'_, Self> {
1399                unsafe {
1400                    SubsliceImplMut {
1401                        slice: self.slice,
1402                        start: self.start,
1403                        end: self.end,
1404                    }
1405                }
1406            }
1407        }
1408        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeInclusive<usize>>
1409            for SubsliceImplMut<'a>
1410        {
1411            unsafe fn get_subslice_unchecked_mut(
1412                &mut self,
1413                range: core::ops::RangeInclusive<usize>,
1414            ) -> SubsliceMut<'_, Self> {
1415                use core::ops::{Bound, RangeBounds};
1416                use std::hint::unreachable_unchecked;
1417                let start = match range.start_bound() {
1418                    Bound::Included(s) => *s,
1419                    // SAFETY: we cannot take this branch
1420                    _ => unsafe { unreachable_unchecked() },
1421                };
1422                let end = match range.end_bound() {
1423                    Bound::Included(s) => *s,
1424                    // SAFETY: we cannot take this branch
1425                    _ => unsafe { unreachable_unchecked() },
1426                };
1427                unsafe {
1428                    SubsliceImplMut {
1429                        slice: self.slice,
1430                        start: self.start + start,
1431                        end: self.start + end + 1,
1432                    }
1433                }
1434            }
1435        }
1436
1437        impl<'a> SliceByValueSubsliceRangeMut<core::ops::RangeTo<usize>> for SubsliceImplMut<'a> {
1438            unsafe fn get_subslice_unchecked_mut(
1439                &mut self,
1440                range: core::ops::RangeTo<usize>,
1441            ) -> SubsliceMut<'_, Self> {
1442                unsafe {
1443                    SubsliceImplMut {
1444                        slice: self.slice,
1445                        start: self.start,
1446                        end: self.start + range.end,
1447                    }
1448                }
1449            }
1450        }
1451        pub struct IterMut<'a, 'b> {
1452            subslice: &'b SubsliceImplMut<'a>,
1453            index: usize,
1454        }
1455
1456        impl<'a, 'b> Iterator for IterMut<'a, 'b> {
1457            type Item = <$ty as SliceByValue>::Value;
1458
1459            #[inline]
1460            fn next(&mut self) -> Option<Self::Item> {
1461                if self.index < self.subslice.len() {
1462                    let value = unsafe { self.subslice.get_value_unchecked(self.index) };
1463                    self.index += 1;
1464                    Some(value)
1465                } else {
1466                    None
1467                }
1468            }
1469        }
1470
1471        impl<'a> IterableByValue for SubsliceImplMut<'a> {
1472            type Item = <$ty as SliceByValue>::Value;
1473            type Iter<'b>
1474                = IterMut<'a, 'b>
1475            where
1476                Self: 'b;
1477
1478            #[inline]
1479            fn iter_value(&self) -> Self::Iter<'_> {
1480                IterMut {
1481                    subslice: self,
1482                    index: 0,
1483                }
1484            }
1485        }
1486
1487        impl<'a> IterableByValueFrom for SubsliceImplMut<'a> {
1488            type IterFrom<'b>
1489                = IterMut<'a, 'b>
1490            where
1491                Self: 'b;
1492
1493            #[inline]
1494            fn iter_value_from(&self, from: usize) -> Self::Iter<'_> {
1495                let len = self.len();
1496                if from > len {
1497                    panic!(
1498                        "index out of bounds: the len is {len} but the starting index is {from}"
1499                    );
1500                }
1501                IterMut {
1502                    subslice: self,
1503                    index: from,
1504                }
1505            }
1506        }
1507    };
1508}
1509
1510#[cfg(test)]
1511mod tests {
1512
1513    use super::*;
1514
1515    #[test]
1516    #[allow(clippy::reversed_empty_ranges)]
1517    fn test_good_ranges() {
1518        // Range
1519        assert!((0..1).is_valid(1));
1520        assert!(!(1..0).is_valid(1));
1521        assert!(!(0..1).is_valid(0));
1522
1523        // RangeFrom
1524        assert!((0..).is_valid(1));
1525        assert!((1..).is_valid(1));
1526        assert!(!(2..).is_valid(1));
1527
1528        // RangeFull
1529        assert!((..).is_valid(0));
1530        assert!((..).is_valid(1));
1531
1532        // RangeInclusive
1533        assert!((0..=1).is_valid(2));
1534        assert!(!(1..=0).is_valid(2));
1535        assert!(!(0..=1).is_valid(1));
1536
1537        // RangeTo
1538        assert!((..0).is_valid(1));
1539        assert!((..1).is_valid(1));
1540        assert!(!(..2).is_valid(1));
1541
1542        // RangeToInclusive
1543        assert!((..=0).is_valid(2));
1544        assert!((..=1).is_valid(2));
1545        assert!(!(..=2).is_valid(2));
1546    }
1547}