devela/sys/mem/slice/
ext.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// devela::sys::mem::slice::ext
//
//!
//

use super::Slice;
#[cfg(feature = "alloc")]
use crate::data::Vec;

/// Marker trait to prevent downstream implementations of the [`ExtSlice`] trait.
trait Sealed {}
impl<T> Sealed for [T] {}
impl<T> Sealed for &[T] {}
impl<T> Sealed for &mut [T] {}
impl<T, const LEN: usize> Sealed for [T; LEN] {}
#[cfg(feature = "alloc")]
impl<T> Sealed for Vec<T> {}

/// Extension trait providing additional methods for [`&[T]`][slice].
///
/// This trait is sealed and cannot be implemented for any other type.
#[cfg_attr(feature = "nightly_doc", doc(notable_trait))]
#[expect(private_bounds, reason = "Sealed")]
pub trait ExtSlice<T>: Sealed {
    /* split */

    /// Returns a left subslice of `slice` with the given maximum `len`.
    ///
    /// If `left_len > slice.len()` it returns the full slice.
    ///
    /// See also [`Slice::lsplit`] for the standalone `const` version.
    #[must_use]
    fn slice_lsplit(&self, len: usize) -> &[T];

    /// Returns a right subslice of `slice` with the given maximum `len`.
    ///
    /// If `left_len > slice.len()` it returns the full slice.
    ///
    /// See also [`Slice::rsplit`] for the standalone `const` version.
    #[must_use]
    fn slice_rsplit(&self, len: usize) -> &[T];

    /// Returns a middle subslice of `slice` with the given maximum `len`
    /// and a left bias.
    ///
    /// In case of a non-perfect middle split, it will have one character more
    /// on the left.
    ///
    /// If `len > slice.len()` returns the full `slice`.
    ///
    /// See also [`Slice::msplit_left`] for the standalone `const` version.
    #[must_use]
    fn slice_msplit_left(&self, len: usize) -> &[T];

    /// Returns a middle subslice of `slice` with the given maximum `len`
    /// and a right bias.
    ///
    /// In case of a non-perfect middle split, it will have one character more
    /// on the right.
    ///
    /// If `len > slice.len()` returns the full `slice`.
    ///
    /// See also [`Slice::msplit_right`] for the standalone `const` version.
    #[must_use]
    fn slice_msplit_right(&self, len: usize) -> &[T];

    /* convert */

    /// Converts `&[T]` to `[U; N]` when `U` implements `From<T>`.
    ///
    /// # Panics
    /// Panics if the length of the slice is less than the length of the array.
    /// # Examples
    /// ```
    /// # use devela::ExtSlice;
    /// assert_eq![[1_u16, 2, 3], [1_u8, 2, 3].slice_into_array::<u16, 3>()];
    /// assert_eq![[1_u16, 2, 3], [1_u8, 2, 3].slice_into_array::<u16, 3>()];
    /// ```
    /// # Features
    /// If the `unsafe_array` feature is enabled it uses `MaybeUninit` to improve performance.
    #[must_use]
    // IMPROVE make a try_slice_into_array version:
    // WAIT: [try_array_from_fn](https://github.com/rust-lang/rust/issues/89379)
    // - https://doc.rust-lang.org/nightly/core/array/fn.try_from_fn.html
    fn slice_into_array<U, const N: usize>(&self) -> [U; N]
    where
        T: Clone,
        U: From<T>;

    /// Converts `&[T]` to `Vec<U>` when `U` implements `From<T>`.
    /// # Examples
    /// ```
    /// # use devela::ExtSlice;
    /// assert_eq![vec![1_i16, 2, 3], [1_u8, 2, 3].slice_into_vec::<i16>()];
    /// assert_eq![vec![1_i16, 2, 3], [1_u8, 2, 3].slice_into_vec::<i16>()];
    /// ```
    #[must_use]
    #[cfg(feature = "alloc")]
    #[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "alloc")))]
    fn slice_into_vec<U>(&self) -> Vec<U>
    where
        T: Clone,
        U: From<T>;

    /// Tries to convert `&[T]` to `Vec<U>` when `U` implements `TryFrom<T>`.
    /// # Examples
    /// ```
    /// # use devela::ExtSlice;
    /// assert_eq![Ok(vec![1_i32, 2, 3]), [1_i64, 2, 3].slice_try_into_vec()];
    /// assert_eq![Ok(vec![1_i32, 2, 3]), [1_i64, 2, 3].slice_try_into_vec::<_, i32>()];
    /// ```
    #[cfg(feature = "alloc")]
    #[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "alloc")))]
    fn slice_try_into_vec<E, U>(&self) -> Result<Vec<U>, E>
    where
        T: Clone,
        U: TryFrom<T, Error = E>;
}

/// Extension trait providing additional methods for [`&mut [T]`][slice].
///
/// This trait is sealed and cannot be implemented for any other type.
#[cfg_attr(feature = "nightly_doc", doc(notable_trait))]
pub trait ExtSliceMut<T>: ExtSlice<T> {
    /* split */

    /// Returns a mutable left subslice of `slice` with the given maximum `len`.
    ///
    /// If `left_len > slice.len()` it returns the full slice.
    #[must_use]
    fn slice_lsplit_mut(&mut self, len: usize) -> &mut [T];

    /// Returns a mutable right subslice of `slice` with the given maximum `len`.
    ///
    /// If `left_len > slice.len()` it returns the full slice.
    #[must_use]
    fn slice_rsplit_mut(&mut self, len: usize) -> &mut [T];

    /// Returns a mutable middle subslice of `slice` with the given maximum `len`
    /// and a left bias.
    ///
    /// In case of a non-perfect middle split, it will have one character more
    /// on the left.
    ///
    /// If `len > slice.len()` returns the full `slice`.
    #[must_use]
    fn slice_msplit_left_mut(&mut self, len: usize) -> &mut [T];

    /// Returns a mutable middle subslice of `slice` with the given maximum `len`
    /// and a right bias.
    ///
    /// In case of a non-perfect middle split, it will have one character more
    /// on the right.
    ///
    /// If `len > slice.len()` returns the full `slice`.
    #[must_use]
    fn slice_msplit_right_mut(&mut self, len: usize) -> &mut [T];
}

macro_rules! impl_ext_slice {
    ($t:ty, for $for:ty, impl: $($impl:tt)*) => {
        impl<$($impl)*> ExtSlice<$t> for $for {
            /* split */

            fn slice_lsplit(&self, len: usize) -> &[T] { Slice::lsplit(self, len) }
            fn slice_rsplit(&self, len: usize) -> &[T] { Slice::rsplit(self, len) }
            fn slice_msplit_left(&self, len: usize) -> &[T] { Slice::msplit_left(self, len) }
            fn slice_msplit_right(&self, len: usize) -> &[T] { Slice::msplit_right(self, len) }

            /* collection */

            fn slice_into_array<U, const N: usize>(&self) -> [U; N] where T: Clone, U: From<T> {
                if self.len() >= N {
                    #[cfg(any(feature = "safe_data", not(feature = "unsafe_array")))]
                    {
                        let mut array: [U; N] = crate::array_from_fn(|i| U::from(self[i].clone()));
                        for (i, item) in self.iter().take(N).enumerate() {
                            array[i] = U::from(item.clone());
                        }
                        array
                    }
                    // SAFETY: we make sure of initializing every array element
                    #[cfg(all(not(feature = "safe_data"), feature = "unsafe_array"))]
                    {
                        use crate::MaybeUninit;
                        let mut array: [MaybeUninit<U>; N] =
                            unsafe { MaybeUninit::uninit().assume_init() };
                        for i in 0..N { array[i] = MaybeUninit::new(U::from(self[i].clone())); }
                        array.map(|x| unsafe { x.assume_init() })
                    }
                } else {
                    panic!("Slice length is less than the requested array size")
                }
            }
            #[cfg(feature = "alloc")]
            fn slice_into_vec<U>(&self) -> Vec<U> where T: Clone, U: From<T> {
                self.iter().map(|t| U::from(t.clone())).collect::<Vec<_>>().into_iter().collect()
            }
            #[cfg(feature = "alloc")]
            fn slice_try_into_vec<E, U>(&self) -> Result<Vec<U>, E>
                where T: Clone, U: TryFrom<T, Error = E> {
                    self
                        // 1. Vec<Result<_>>:
                        .iter()
                        .map(|t| U::try_from(t.clone()))
                        .collect::<Vec<_>>()
                        // 2. Result<Vec<_>>:
                        .into_iter()
                        .collect::<Result<Vec<_>, _>>()
            }
        }
    };
    (mut: $t:ty, for $for:ty, impl: $($impl:tt)*) => {
        impl_ext_slice![$t, for $for, impl: $($impl)*];

        impl<$($impl)*> ExtSliceMut<$t> for $for {
            /* split */

            fn slice_lsplit_mut(&mut self, len: usize) -> &mut [T] { Slice::lsplit_mut(self, len) }
            fn slice_rsplit_mut(&mut self, len: usize) -> &mut [T] { Slice::rsplit_mut(self, len) }
            fn slice_msplit_left_mut(&mut self, len: usize) -> &mut [T] {
                Slice::msplit_left_mut(self, len) }
            fn slice_msplit_right_mut(&mut self, len: usize) -> &mut [T] {
                Slice::msplit_right_mut(self, len) }
        }
    };
}
impl_ext_slice![mut: T, for [T], impl: T];
impl_ext_slice![T, for &[T], impl: T];
impl_ext_slice![mut: T, for &mut [T], impl: T];
impl_ext_slice![mut: T, for [T; LEN], impl: T, const LEN: usize];
#[cfg(feature = "alloc")]
impl_ext_slice![mut: T, for Vec<T>, impl: T];