Skip to main content

maplike/alloc/
vec.rs

1// SPDX-FileCopyrightText: 2025 maplike contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use _alloc::vec::Vec;
6
7use crate::{Get, Insert, IntoIter, KeyedCollection, Pop, Push, Remove, Set};
8
9impl<V> KeyedCollection for Vec<V> {
10    type Key = usize;
11    type Value = V;
12}
13
14impl<V> Get<usize> for Vec<V> {
15    #[inline(always)]
16    fn get(&self, index: &usize) -> Option<&V> {
17        self.as_slice().get(*index)
18    }
19}
20
21impl<V> Set<usize> for Vec<V> {
22    #[inline(always)]
23    fn set(&mut self, index: usize, value: V) {
24        self[index] = value;
25    }
26}
27
28impl<V: Clone> Insert<usize> for Vec<V> {
29    #[inline(always)]
30    fn insert(&mut self, index: usize, value: V) {
31        // If the `Vec`'s len is too small, resize it and fill the elements
32        // between with the same value as the new inserted one.
33        //
34        // This is somewhat of a hack, but it helps in making the `undoredo`
35        // work.
36        self.resize(index + 1, value);
37    }
38}
39
40impl<V> Remove<usize> for Vec<V> {
41    #[inline(always)]
42    fn remove(&mut self, index: &usize) -> Option<V> {
43        Some(self.swap_remove(*index))
44    }
45}
46
47impl<V> Push<usize> for Vec<V> {
48    #[inline(always)]
49    fn push(&mut self, value: V) -> usize {
50        Vec::push(self, value);
51        self.len() - 1
52    }
53}
54
55impl<V> Pop for Vec<V> {
56    #[inline(always)]
57    fn pop(&mut self) -> Option<V> {
58        Vec::pop(self)
59    }
60}
61
62impl<V> IntoIter<usize> for Vec<V> {
63    type IntoIter = core::iter::Enumerate<_alloc::vec::IntoIter<V>>;
64
65    fn into_iter(self) -> Self::IntoIter {
66        IntoIterator::into_iter(self).enumerate()
67    }
68}