Skip to main content

predsync_core/
managed.rs

1//! Borrowed-or-owned contiguous storage for no-alloc/alloc engines.
2
3#[cfg(feature = "alloc")]
4use alloc::vec::Vec;
5
6pub enum ManagedSlice<'a, T> {
7    Borrowed(&'a mut [T]),
8    #[cfg(feature = "alloc")]
9    Owned(Vec<T>),
10}
11
12impl<'a, T> ManagedSlice<'a, T> {
13    #[cfg(feature = "alloc")]
14    pub fn owned(vec: Vec<T>) -> Self {
15        Self::Owned(vec)
16    }
17
18    pub fn borrowed(slice: &'a mut [T]) -> Self {
19        Self::Borrowed(slice)
20    }
21
22    pub fn as_slice(&self) -> &[T] {
23        match self {
24            Self::Borrowed(s) => s,
25            #[cfg(feature = "alloc")]
26            Self::Owned(v) => v,
27        }
28    }
29
30    pub fn as_mut_slice(&mut self) -> &mut [T] {
31        match self {
32            Self::Borrowed(s) => s,
33            #[cfg(feature = "alloc")]
34            Self::Owned(v) => v,
35        }
36    }
37
38    pub fn len(&self) -> usize {
39        self.as_slice().len()
40    }
41
42    pub fn is_empty(&self) -> bool {
43        self.len() == 0
44    }
45
46    /// Keep only the first `len` elements in place.
47    pub fn truncate(&mut self, len: usize) {
48        match self {
49            Self::Borrowed(slice) => {
50                let original = core::mem::take(slice);
51                *slice = &mut original[..len];
52            }
53            #[cfg(feature = "alloc")]
54            Self::Owned(vec) => vec.truncate(len),
55        }
56    }
57
58    /// Keep only the first `len` elements, preserving borrowed/owned storage.
59    pub fn into_sliced(self, len: usize) -> Self {
60        match self {
61            Self::Borrowed(slice) => Self::borrowed(&mut slice[..len]),
62            #[cfg(feature = "alloc")]
63            Self::Owned(mut vec) => {
64                vec.truncate(len);
65                Self::owned(vec)
66            }
67        }
68    }
69}
70
71impl<'a, T> core::ops::Index<usize> for ManagedSlice<'a, T> {
72    type Output = T;
73    fn index(&self, index: usize) -> &Self::Output {
74        &self.as_slice()[index]
75    }
76}
77
78impl<'a, T> core::ops::IndexMut<usize> for ManagedSlice<'a, T> {
79    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
80        &mut self.as_mut_slice()[index]
81    }
82}
83
84impl<'a, T> core::ops::Deref for ManagedSlice<'a, T> {
85    type Target = [T];
86    fn deref(&self) -> &Self::Target {
87        self.as_slice()
88    }
89}
90
91impl<'a, T> core::ops::DerefMut for ManagedSlice<'a, T> {
92    fn deref_mut(&mut self) -> &mut Self::Target {
93        self.as_mut_slice()
94    }
95}