onevec/
lib.rs

1use std::num::NonZeroUsize;
2use std::ops::{Index, IndexMut};
3use std::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive};
4use std::{slice, vec};
5
6/// A `Vec<T>` wrapper with one-based indices allowing for memory layout optimization, e.g.
7/// `Option<NonZeroUsize>` is the same size as `usize` (8 or 4 bytes on most platforms)
8///
9/// For detailed methods documentation, see [`Vec`](std::vec::Vec).
10#[derive(Clone, Default, Debug, Eq, Hash, PartialEq)]
11pub struct OneVec<T>(Vec<T>);
12
13impl<T> OneVec<T> {
14    /// Constructs a new, empty `OneVec<T>`.
15    /// Does not allocate memory.
16    pub fn new() -> OneVec<T> {
17        OneVec(Vec::new())
18    }
19
20    /// Constructs a new, empty OneVec<T> with the specified capacity.
21    pub fn with_capacity(capacity: usize) -> OneVec<T> {
22        OneVec(Vec::with_capacity(capacity))
23    }
24
25    /// Creates a `OneVec<T>` from `Vec<T>`. This operation is a no-op.
26    pub fn from_vec(vec: Vec<T>) -> OneVec<T> {
27        OneVec(vec)
28    }
29
30    /// Returns the number of elements the vector can hold without reallocating.
31    pub fn capacity(&self) -> usize {
32        self.0.capacity()
33    }
34
35    /// Reserves capacity for at least additional more elements
36    /// to be inserted in the given `OneVec<T>`.
37    pub fn reserve(&mut self, additional: usize) {
38        self.0.reserve(additional)
39    }
40
41    /// Reserves the minimum capacity for exactly additional more elements
42    /// to be inserted in the given `OneVec<T>`.
43    pub fn reserve_exact(&mut self, additional: usize) {
44        self.0.reserve_exact(additional)
45    }
46
47    /// Shrinks the capacity of the vector as much as possible.
48    pub fn shrink_to_fit(&mut self) {
49        self.0.shrink_to_fit()
50    }
51
52    /// Shortens the vector, keeping the first len elements and dropping the rest.
53    pub fn truncate(&mut self, len: usize) {
54        self.0.truncate(len)
55    }
56
57    /// Extracts a slice containing the entire vector.
58    pub fn as_slice(&self) -> &[T] {
59        self.0.as_slice()
60    }
61
62    /// Extracts a mutable slice of the entire vector.
63    pub fn as_mut_slice(&mut self) -> &mut [T] {
64        self.0.as_mut_slice()
65    }
66
67    /// Consumes the `OneVec<T>`, returning the inner vector.
68    pub fn into_vec(self) -> Vec<T> {
69        self.0
70    }
71
72    /// Removes an element from the vector and returns it.
73    pub fn swap_remove(&mut self, index: NonZeroUsize) -> T {
74        self.0.swap_remove(index.get() - 1)
75    }
76
77    /// Inserts an element at position index within the vector,
78    /// shifting all elements after it to the right.
79    pub fn insert(&mut self, index: NonZeroUsize, element: T) {
80        self.0.insert(index.get() - 1, element)
81    }
82
83    /// Removes and returns the element at position index within the vector,
84    /// shifting all elements after it to the left.
85    pub fn remove(&mut self, index: NonZeroUsize) -> T {
86        self.0.remove(index.get() - 1)
87    }
88
89    /// Retains only the elements specified by the predicate.
90    pub fn retain<F>(&mut self, f: F)
91    where
92        F: FnMut(&T) -> bool,
93    {
94        self.0.retain(f)
95    }
96
97    /// Removes all but the first of consecutive elements in the vector
98    /// that resolve to the same key.
99    pub fn dedup_by_key<F, K>(&mut self, key: F)
100    where
101        F: FnMut(&mut T) -> K,
102        K: PartialEq,
103    {
104        self.0.dedup_by_key(key)
105    }
106
107    /// Removes all but the first of consecutive elements in the vector
108    /// satisfying a given equality relation.
109    pub fn dedup_by<F>(&mut self, same_bucket: F)
110    where
111        F: FnMut(&mut T, &mut T) -> bool,
112    {
113        self.0.dedup_by(same_bucket)
114    }
115
116    /// Appends an element to the back of a collection.
117    pub fn push(&mut self, value: T) {
118        self.0.push(value)
119    }
120
121    /// Removes the last element from a vector and returns it, or None if it is empty.
122    pub fn pop(&mut self) -> Option<T> {
123        self.0.pop()
124    }
125
126    /// Moves all the elements of other into Self, leaving other empty.
127    pub fn append(&mut self, other: &mut OneVec<T>) {
128        self.0.append(&mut other.0)
129    }
130
131    /// Clears the vector, removing all values.
132    pub fn clear(&mut self) {
133        self.0.clear()
134    }
135
136    /// Returns the number of elements in the vector, also referred to as its 'length'.
137    pub fn len(&self) -> usize {
138        self.0.len()
139    }
140
141    /// Returns true if the vector contains no elements.
142    pub fn is_empty(&self) -> bool {
143        self.0.is_empty()
144    }
145
146    /// Splits the collection into two at the given index.
147    ///
148    /// Returns a newly allocated Self. self contains elements [0, at),
149    /// and the returned Self contains elements [at, len).
150    pub fn split_off(&mut self, at: NonZeroUsize) -> OneVec<T> {
151        OneVec(self.0.split_off(at.get() - 1))
152    }
153
154    /// Returns an iterator over the vector.
155    pub fn iter(&self) -> slice::Iter<T> {
156        self.as_slice().iter()
157    }
158
159    /// Returns an iterator that allows modifying each value.
160    pub fn iter_mut(&mut self) -> slice::IterMut<T> {
161        self.as_mut_slice().iter_mut()
162    }
163}
164
165impl<T> IntoIterator for OneVec<T> {
166    type Item = T;
167    type IntoIter = vec::IntoIter<T>;
168
169    fn into_iter(self) -> vec::IntoIter<T> {
170        self.0.into_iter()
171    }
172}
173
174impl<T> Index<RangeFull> for OneVec<T> {
175    type Output = [T];
176
177    fn index(&self, _index: RangeFull) -> &[T] {
178        self.as_slice()
179    }
180}
181
182impl<T> IndexMut<RangeFull> for OneVec<T> {
183    fn index_mut(&mut self, _index: RangeFull) -> &mut [T] {
184        self.as_mut_slice()
185    }
186}
187
188impl<T> Index<Range<NonZeroUsize>> for OneVec<T> {
189    type Output = [T];
190
191    fn index(&self, index: Range<NonZeroUsize>) -> &[T] {
192        self.as_slice()
193            .index((index.start.get() - 1)..(index.end.get() - 1))
194    }
195}
196
197impl<T> IndexMut<Range<NonZeroUsize>> for OneVec<T> {
198    fn index_mut(&mut self, index: Range<NonZeroUsize>) -> &mut [T] {
199        self.as_mut_slice()
200            .index_mut((index.start.get() - 1)..(index.end.get() - 1))
201    }
202}
203
204impl<T> Index<RangeInclusive<NonZeroUsize>> for OneVec<T> {
205    type Output = [T];
206
207    fn index(&self, index: RangeInclusive<NonZeroUsize>) -> &[T] {
208        self.as_slice()
209            .index((index.start().get() - 1)..=(index.end().get() - 1))
210    }
211}
212
213impl<T> IndexMut<RangeInclusive<NonZeroUsize>> for OneVec<T> {
214    fn index_mut(&mut self, index: RangeInclusive<NonZeroUsize>) -> &mut [T] {
215        self.as_mut_slice()
216            .index_mut((index.start().get() - 1)..=(index.end().get() - 1))
217    }
218}
219
220impl<T> Index<RangeTo<NonZeroUsize>> for OneVec<T> {
221    type Output = [T];
222
223    fn index(&self, index: RangeTo<NonZeroUsize>) -> &[T] {
224        self.as_slice().index(..(index.end.get() - 1))
225    }
226}
227
228impl<T> IndexMut<RangeTo<NonZeroUsize>> for OneVec<T> {
229    fn index_mut(&mut self, index: RangeTo<NonZeroUsize>) -> &mut [T] {
230        self.as_mut_slice().index_mut(..(index.end.get() - 1))
231    }
232}
233
234impl<T> Index<RangeToInclusive<NonZeroUsize>> for OneVec<T> {
235    type Output = [T];
236
237    fn index(&self, index: RangeToInclusive<NonZeroUsize>) -> &[T] {
238        self.as_slice().index(..=(index.end.get() - 1))
239    }
240}
241
242impl<T> IndexMut<RangeToInclusive<NonZeroUsize>> for OneVec<T> {
243    fn index_mut(&mut self, index: RangeToInclusive<NonZeroUsize>) -> &mut [T] {
244        self.as_mut_slice().index_mut(..=(index.end.get() - 1))
245    }
246}
247
248impl<T> Index<RangeFrom<NonZeroUsize>> for OneVec<T> {
249    type Output = [T];
250
251    fn index(&self, index: RangeFrom<NonZeroUsize>) -> &[T] {
252        self.as_slice().index((index.start.get() - 1)..)
253    }
254}
255
256impl<T> IndexMut<RangeFrom<NonZeroUsize>> for OneVec<T> {
257    fn index_mut(&mut self, index: RangeFrom<NonZeroUsize>) -> &mut [T] {
258        self.as_mut_slice().index_mut((index.start.get() - 1)..)
259    }
260}
261
262impl<T> Index<NonZeroUsize> for OneVec<T> {
263    type Output = T;
264
265    fn index(&self, index: NonZeroUsize) -> &T {
266        &self.0[index.get() - 1]
267    }
268}
269
270impl<T> IndexMut<NonZeroUsize> for OneVec<T> {
271    fn index_mut(&mut self, index: NonZeroUsize) -> &mut T {
272        &mut self.0[index.get() - 1]
273    }
274}