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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
use crate::{utils, Capacity};
use core::{
    array,
    cmp::Ordering,
    mem,
    ops::{Deref, DerefMut},
};

/// Represents a generic list of items
pub trait List: Sized {
    /// Represents the type of item within the list
    type Item;

    /// Creates a new list with **up to** N elements, each created using
    /// the provided function; when the provided function returns None, the
    /// underlying list implementation will determine what to do
    fn new_filled_with<F: FnMut(usize) -> Option<Self::Item>>(n: usize, f: F) -> Self;

    /// Returns the maximum capacity of the list
    fn max_capacity(&self) -> Capacity;

    /// Returns the actual length of the list, which may be less than the
    /// actual capacity
    fn len(&self) -> usize;

    /// Returns true if the list is empty
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a reference to an element found at the given index, or None
    /// if no element found
    fn get(&self, index: usize) -> Option<&Self::Item>;

    /// Returns a mutable reference to an element found at the given index, or
    /// None if no element found
    fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item>;

    /// Inserts an element at position `index` within the vector, shifting all
    /// elements after it to the right
    ///
    /// # Panics
    ///
    /// Panics if `index > len`
    fn insert(&mut self, index: usize, element: Self::Item);

    /// Removes and returns the element at position `index` within the vector,
    /// shifting all elements after it to the left.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of bounds
    fn remove(&mut self, index: usize) -> Self::Item;
}

/// Represents a fixed list that can grow up to a specific capacity `N`
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
pub struct FixedList<T: Default, const N: usize>(
    #[cfg_attr(
        feature = "serde-1",
        serde(
            bound(
                serialize = "T: serde::Serialize",
                deserialize = "T: serde::Deserialize<'de>"
            ),
            serialize_with = "utils::serialize_array",
            deserialize_with = "utils::deserialize_array"
        )
    )]
    [T; N],
    usize,
);

impl<T: Default, const N: usize> List for FixedList<T, N> {
    type Item = T;

    /// Will make a list that fills up to N, and any additional elements
    /// not filled in using the function will be completed with the default
    /// value; when the function returns None, the default value will also
    /// be used
    fn new_filled_with<F: FnMut(usize) -> Option<Self::Item>>(n: usize, mut f: F) -> Self {
        let arr = utils::make_array(|i| match f(i) {
            Some(data) if i < n => data,
            _ => T::default(),
        });

        Self(arr, N)
    }

    fn max_capacity(&self) -> Capacity {
        Capacity::Limited(N)
    }

    fn len(&self) -> usize {
        self.1
    }

    fn get(&self, index: usize) -> Option<&Self::Item> {
        self.0.get(index)
    }

    fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item> {
        self.0.get_mut(index)
    }

    fn insert(&mut self, index: usize, element: Self::Item) {
        #[cold]
        #[inline(never)]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!(
                "insertion index (is {}) should be <= len (is {})",
                index, len
            );
        }

        let len = self.len();
        if index > len {
            assert_failed(index, len);
        }

        self.0[index] = element;

        // space for the new element
        if index == len {
            self.1 += 1;
        }
    }

    fn remove(&mut self, index: usize) -> Self::Item {
        #[cold]
        #[inline(never)]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!("removal index (is {}) should be < len (is {})", index, len);
        }

        let len = self.len();
        if index >= len {
            assert_failed(index, len);
        }

        // First, remove the element by filling in with default value
        let data = mem::take(&mut self.0[index]);

        // Second, shift over all other elements
        for i in index + 1..len {
            let value = mem::take(&mut self.0[i]);
            self.0[i - 1] = value;
        }

        data
    }
}

impl<T: Default, const N: usize> Deref for FixedList<T, N> {
    type Target = [T; N];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T: Default, const N: usize> DerefMut for FixedList<T, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T: Default, const N: usize> From<FixedList<T, N>> for [T; N] {
    fn from(list: FixedList<T, N>) -> Self {
        list.0
    }
}

impl<T, U, const N: usize> PartialEq<[U; N]> for FixedList<T, N>
where
    T: PartialEq<U> + Default,
{
    fn eq(&self, other: &[U; N]) -> bool {
        PartialEq::eq(&self.0, &*other)
    }
}

impl<T, const N: usize> PartialOrd<[T; N]> for FixedList<T, N>
where
    T: PartialOrd<T> + Default,
{
    fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
        PartialOrd::partial_cmp(&self.0, &*other)
    }
}

impl<T: Default, const N: usize> IntoIterator for FixedList<T, N> {
    type Item = T;
    type IntoIter = array::IntoIter<Self::Item, N>;

    fn into_iter(self) -> Self::IntoIter {
        array::IntoIter::new(self.0)
    }
}

#[cfg(any(feature = "alloc", feature = "std"))]
#[doc(inline)]
#[cfg_attr(feature = "docs", doc(cfg(any(alloc, std))))]
pub use self::alloc::DynamicList;

#[cfg(any(feature = "alloc", feature = "std"))]
mod alloc {
    use super::*;
    use core::iter::FromIterator;
    use std::vec::Vec;

    /// Represents a dynamic list that can grow and shrink with unlimited capacity
    #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
    #[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
    pub struct DynamicList<T>(Vec<T>);

    impl<T> List for DynamicList<T> {
        type Item = T;

        /// Makes a new list of **up to** N by using the provided function;
        /// whenever the function returns None, the item is skipped and the
        /// list's length will not grow
        fn new_filled_with<F: FnMut(usize) -> Option<Self::Item>>(n: usize, mut f: F) -> Self {
            let mut inner = Vec::new();

            for i in 0..n {
                if let Some(data) = f(i) {
                    inner.push(data);
                }
            }

            Self(inner)
        }

        fn max_capacity(&self) -> Capacity {
            Capacity::Unlimited
        }

        fn len(&self) -> usize {
            self.0.len()
        }

        fn get(&self, index: usize) -> Option<&Self::Item> {
            self.0.get(index)
        }

        fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item> {
            self.0.get_mut(index)
        }

        fn insert(&mut self, index: usize, element: Self::Item) {
            self.0.insert(index, element)
        }

        fn remove(&mut self, index: usize) -> Self::Item {
            self.0.remove(index)
        }
    }

    impl<T> Deref for DynamicList<T> {
        type Target = Vec<T>;

        fn deref(&self) -> &Self::Target {
            &self.0
        }
    }

    impl<T> DerefMut for DynamicList<T> {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.0
        }
    }

    impl<T> From<DynamicList<T>> for Vec<T> {
        fn from(list: DynamicList<T>) -> Self {
            list.0
        }
    }

    impl<T> From<Vec<T>> for DynamicList<T> {
        fn from(vec: Vec<T>) -> Self {
            Self(vec)
        }
    }

    impl<T, const N: usize> From<[T; N]> for DynamicList<T> {
        fn from(arr: [T; N]) -> Self {
            Self(Vec::from(arr))
        }
    }

    impl<T> FromIterator<T> for DynamicList<T> {
        fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
            Self(iter.into_iter().collect())
        }
    }

    impl<T, U> PartialEq<Vec<U>> for DynamicList<T>
    where
        T: PartialEq<U>,
    {
        fn eq(&self, other: &Vec<U>) -> bool {
            PartialEq::eq(&*self.0, &**other)
        }
    }

    impl<T, U, const N: usize> PartialEq<[U; N]> for DynamicList<T>
    where
        T: PartialEq<U>,
    {
        fn eq(&self, other: &[U; N]) -> bool {
            PartialEq::eq(&*self.0, &*other)
        }
    }

    impl<T> PartialOrd<Vec<T>> for DynamicList<T>
    where
        T: PartialOrd<T>,
    {
        fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
            PartialOrd::partial_cmp(&*self.0, &**other)
        }
    }

    impl<T> IntoIterator for DynamicList<T> {
        type Item = T;
        type IntoIter = std::vec::IntoIter<Self::Item>;

        fn into_iter(self) -> Self::IntoIter {
            self.0.into_iter()
        }
    }
}