slice_utils/
chain.rs

1use crate::{Slice, SliceBorrowed, SliceMut, SliceOwned, Unique};
2
3/// Two chained slices; see [`Slice::chain`].
4pub struct Chain<S1, S2>(pub S1, pub S2);
5
6impl<S1, S2> Slice for Chain<S1, S2>
7where
8    S1: Slice,
9    S2: Slice<Output = S1::Output>,
10{
11    type Output = S1::Output;
12
13    fn len(&self) -> usize {
14        self.0.len() + self.1.len()
15    }
16
17    fn get_with<W: FnMut(&Self::Output) -> R, R>(&self, index: usize, f: &mut W) -> Option<R> {
18        self.0
19            .get_with(index, f)
20            .or_else(|| self.1.get_with(index - self.0.len(), f))
21    }
22}
23
24impl<S1, S2> SliceOwned for Chain<S1, S2>
25where
26    S1: SliceOwned,
27    S2: SliceOwned<Output = S1::Output>,
28{
29    fn get_owned(&self, index: usize) -> Option<Self::Output> {
30        self.0
31            .get_owned(index)
32            .or_else(|| self.1.get_owned(index - self.0.len()))
33    }
34}
35
36impl<S1, S2> SliceBorrowed for Chain<S1, S2>
37where
38    S1: SliceBorrowed,
39    S2: SliceBorrowed<Output = S1::Output>,
40{
41    fn get(&self, index: usize) -> Option<&Self::Output> {
42        self.0
43            .get(index)
44            .or_else(|| self.1.get(index - self.0.len()))
45    }
46}
47
48impl<S1, S2> SliceMut for Chain<S1, S2>
49where
50    S1: SliceMut,
51    S2: SliceMut<Output = S1::Output>,
52{
53    fn get_mut(&mut self, index: usize) -> Option<&mut Self::Output> {
54        let offset = self.0.len();
55        if let r @ Some(_) = self.0.get_mut(index) {
56            r
57        } else {
58            self.1.get_mut(index - offset)
59        }
60    }
61}
62
63// SAFETY: both slices are `Unique`, and aliasing rules prevent creating two
64// aliasing slices
65unsafe impl<S1, S2> Unique for Chain<S1, S2>
66where
67    S1: Unique,
68    S2: Unique,
69{
70}