nonempty_containers/
ne_vec.rs

1//! A non-empty vector type that guarantees at least one element is present. [NEVec] has an
2//! interface similar to [Vec] with additional methods to enforce the invariant. Get started with:
3//!
4//! ```rust, no_run
5//! # use nonempty_containers::{nev, NEVec};
6//! #
7//! let nev = NEVec::new(42, vec![1, 2, 3]);
8//! let singleton = NEVec::singleton(42);
9//! let r#macro = nev![1, 2, 3];
10//! ```
11//!
12//! [NEVec] conforms to [Index], [IntoIterator], [Deref], and many more, so operations are
13//! as [Vec]-like as possible. They are also usually zero-cost.
14//!
15//! ```rust, no_run
16//! # use nonempty_containers::nev;
17//! #
18//! let nev = nev![42, 1, 2, 3];
19//! assert_eq!(nev[0], 42);
20//! assert_eq!(nev.len(), 4);
21//! assert_eq!(nev.into_iter().sum::<i32>(), 48);
22//! ```
23//!
24//! When the feature `arbitrary` is enabled, [NEVec] implements [arbitrary::Arbitrary]
25//! for generation of randomly populated instances.
26
27use crate::errors::NonEmptyError;
28#[cfg(feature = "im")]
29use im::Vector;
30use std::collections::vec_deque::IntoIter;
31use std::collections::vec_deque::{Iter, IterMut};
32use std::collections::VecDeque;
33use std::ops::Index;
34
35/// Non-empty vector type.
36#[derive(Debug, Eq, PartialEq, Clone, Hash)]
37pub struct NEVec<T>(VecDeque<T>);
38
39impl<T> NEVec<T> {
40    /// Creates a new [NEVec], ensuring at least one element is present.
41    pub fn new(head: T, tail: Vec<T>) -> Self {
42        // We can afford to call [Vec::len()] here because it's O(1).
43        let mut vec = VecDeque::from(tail);
44        vec.push_front(head);
45        Self(vec)
46    }
47
48    /// Creates a new singleton [NEVec]. Semantically equivalent to:
49    /// ```no_run
50    /// # use nonempty_containers::NEVec;
51    /// # let value = 42;
52    /// #
53    /// NEVec::new(value, Vec::new());
54    /// ```
55    pub fn singleton(value: T) -> Self {
56        let mut vec = VecDeque::new();
57        vec.push_back(value);
58        Self(vec)
59    }
60
61    /// Returns the first element. This operation is safe as the invariant guarantees at least one
62    /// element is present.
63    pub fn head(&self) -> &T {
64        self.0.front().expect("[NonEmptyVec] invariant violated.")
65    }
66
67    /// Returns all elements except the last one. This may be empty if the [NEVec] is a
68    /// singleton.
69    pub fn init(&self) -> Iter<'_, T> {
70        self.0.range(..self.0.len() - 1)
71    }
72
73    /// Returns all elements except the first one. This may be empty if the [NEVec] is a
74    /// singleton.
75    pub fn tail(&self) -> Iter<'_, T> {
76        self.0.range(1..self.0.len())
77    }
78
79    /// Returns the last element. This operation is safe as the invariant guarantees at least one
80    /// element is present.
81    pub fn last(&self) -> &T {
82        self.0.back().expect("[NonEmptyVec] invariant violated.")
83    }
84
85    /// Attempts to create a [NEVec] from a [Vec], returning [None] if the [Vec] is empty.
86    /// ```rust
87    /// # use nonempty_containers::NEVec;
88    /// #
89    /// assert!(NEVec::from_vec(vec![42]).is_ok());
90    /// assert!(NEVec::from_vec(Vec::<u32>::new()).is_err());
91    /// ```
92    pub fn from_vec(vec: Vec<T>) -> Result<Self, NonEmptyError> {
93        match vec.is_empty() {
94            true => Err(NonEmptyError::Empty),
95            false => Ok(Self(VecDeque::from(vec))),
96        }
97    }
98
99    /// Attempts to create a [NEVec] from a [VecDeque], returning [None] if the [VecDeque] is
100    /// empty.
101    ///
102    /// ```rust
103    /// # use std::collections::VecDeque;
104    /// # use nonempty_containers::NEVec;
105    /// #
106    /// assert!(NEVec::from_deque(VecDeque::from(vec![42])).is_ok());
107    /// assert!(NEVec::from_deque(VecDeque::<u32>::new()).is_err());
108    /// ```
109    pub fn from_deque(deque: VecDeque<T>) -> Result<Self, NonEmptyError> {
110        match deque.is_empty() {
111            true => Err(NonEmptyError::Empty),
112            false => Ok(Self(deque)),
113        }
114    }
115
116    /// Attempts to create a [NEVec] from a [Vector], returning [None] if the [Vector] is
117    /// empty. This is only available when the `im` feature is enabled. Additionally, [Vector]
118    /// enforces that the element type must conform to [Clone].
119    ///
120    /// ```rust
121    /// # use nonempty_containers::NEVec;
122    /// #
123    /// assert!(NEVec::from_vector(im::vector![42]).is_ok());
124    /// assert!(NEVec::from_vector(im::Vector::<u32>::new()).is_err());
125    /// ```
126    #[cfg(feature = "im")]
127    pub fn from_vector(vector: Vector<T>) -> Result<Self, NonEmptyError>
128    where
129        T: Clone,
130    {
131        match vector.is_empty() {
132            true => Err(NonEmptyError::Empty),
133            false => Ok(Self(VecDeque::from_iter(vector.into_iter()))),
134        }
135    }
136
137    /// Creates a new [NEVec] from a [Vec] without checking if it's empty. This operation is
138    /// unsafe and should only be used by macros in this crate!
139    #[doc(hidden)]
140    pub fn __from_vec_unsafe(vec: Vec<T>) -> Self {
141        debug_assert!(!vec.is_empty());
142        Self::from_vec(vec).unwrap()
143    }
144
145    /// Creates a new [NEVec] from a [VecDeque] without checking if it's empty. This operation
146    /// is unsafe and should only be used by macros in this crate!
147    #[doc(hidden)]
148    pub fn __from_deque_unsafe(deque: VecDeque<T>) -> Self {
149        debug_assert!(!deque.is_empty());
150        Self::from_deque(deque).unwrap()
151    }
152
153    /// Creates a new [NEVec] from a [Vector] without checking if it's empty. This operation
154    /// is unsafe and should only be used by macros in this crate!
155    #[doc(hidden)]
156    #[cfg(feature = "im")]
157    pub fn __from_vector_unsafe(vector: Vector<T>) -> Self
158    where
159        T: Clone,
160    {
161        debug_assert!(!vector.is_empty());
162        Self::from_vector(vector).unwrap()
163    }
164
165    /// Returns the length of this [NEVec].
166    pub fn len(&self) -> usize {
167        self.0.len()
168    }
169
170    /// A [NEVec] is always non-empty.
171    pub fn is_empty(&self) -> bool {
172        false
173    }
174
175    /// Returns this [NEVec] as a slice.
176    pub fn as_slice(&mut self) -> &[T] {
177        self.0.make_contiguous();
178        self.0.as_slices().0
179    }
180
181    /// Pushes an element to the front of the [NEVec].
182    pub fn push_front(&mut self, value: T) {
183        self.0.push_front(value);
184    }
185
186    /// Pushes an element to the back of the [NEVec].
187    pub fn push_back(&mut self, value: T) {
188        self.0.push_back(value);
189    }
190
191    /// Tries to remove the first element.
192    pub fn pop_front(&mut self) -> Result<T, NonEmptyError> {
193        match self.0.len() {
194            0 => Err(NonEmptyError::Empty),
195            1 => Err(NonEmptyError::AlreadySingleton),
196            _ => Ok(self
197                .0
198                .pop_front()
199                .expect("[NonEmptyVec] invariant violated.")),
200        }
201    }
202
203    /// Tries to remove the last element.
204    pub fn pop_back(&mut self) -> Result<T, NonEmptyError> {
205        match self.0.len() {
206            0 => Err(NonEmptyError::Empty),
207            1 => Err(NonEmptyError::AlreadySingleton),
208            _ => Ok(self
209                .0
210                .pop_back()
211                .expect("[NonEmptyVec] invariant violated.")),
212        }
213    }
214
215    /// Splits the [NEVec] into the first element and the rest. This operation is guaranteed
216    /// to succeed because the invariant guarantees at least one element is present.
217    pub fn split_first(&self) -> (&T, Iter<'_, T>) {
218        (self.head(), self.tail())
219    }
220
221    /// Splits the [NEVec] into all elements except the last one and the last element. This
222    /// operation is guaranteed to succeed because the invariant guarantees at least one element is
223    /// present.
224    pub fn split_last(&self) -> (Iter<'_, T>, &T) {
225        (self.init(), self.last())
226    }
227
228    /// Like [NEVec::split_first], but consumes the [NEVec].
229    pub fn take_split_first(self) -> (T, IntoIter<T>) {
230        let mut iter = self.0.into_iter();
231        let head = iter.next().expect("[NonEmptyVec] invariant violated.");
232        (head, iter)
233    }
234
235    /// Like [NEVec::split_last], but consumes the [NEVec].
236    pub fn take_split_last(self) -> (IntoIter<T>, T) {
237        let mut iter = self.0.into_iter();
238        let last = iter.next_back().expect("[NonEmptyVec] invariant violated.");
239        (iter, last)
240    }
241    
242    /// Returns an iterator over the elements of the [NEVec].
243    pub fn iter(&self) -> Iter<'_, T> {
244        self.0.iter()
245    }
246    
247    /// Extends the [NEVec] with the elements from another collection.
248    pub fn extend<I: IntoIterator<Item = T>>(&mut self, other: I) {
249        self.0.extend(other);
250    }
251}
252
253impl<T> From<NEVec<T>> for Vec<T> {
254    fn from(ne: NEVec<T>) -> Self {
255        ne.0.into()
256    }
257}
258
259impl<T> From<NEVec<T>> for VecDeque<T> {
260    fn from(ne: NEVec<T>) -> Self {
261        ne.0
262    }
263}
264
265#[cfg(feature = "im")]
266impl<T> From<NEVec<T>> for Vector<T>
267where
268    T: Clone,
269{
270    fn from(ne: NEVec<T>) -> Self {
271        Vector::from_iter(ne.0.into_iter())
272    }
273}
274
275impl<T> TryFrom<Vec<T>> for NEVec<T> {
276    type Error = NonEmptyError;
277
278    fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
279        NEVec::from_vec(vec)
280    }
281}
282
283impl<T> From<(T, Vec<T>)> for NEVec<T> {
284    fn from(value: (T, Vec<T>)) -> Self {
285        let (head, tail) = value;
286        Self::new(head, tail)
287    }
288}
289
290impl<T> From<(T, VecDeque<T>)> for NEVec<T> {
291    fn from(value: (T, VecDeque<T>)) -> Self {
292        let (head, tail) = value;
293        Self::new(head, Vec::from(tail))
294    }
295}
296
297#[cfg(feature = "im")]
298impl<T: Clone> From<(T, Vector<T>)> for NEVec<T> {
299    fn from(value: (T, Vector<T>)) -> Self {
300        let (head, tail) = value;
301        Self::new(head, Vec::from_iter(tail.into_iter()))
302    }
303}
304
305impl<T> From<T> for NEVec<T> {
306    fn from(value: T) -> Self {
307        Self::singleton(value)
308    }
309}
310
311impl<'a, T> IntoIterator for &'a NEVec<T> {
312    type Item = &'a T;
313    type IntoIter = Iter<'a, T>;
314
315    fn into_iter(self) -> Self::IntoIter {
316        self.0.iter()
317    }
318}
319
320impl<'a, T> IntoIterator for &'a mut NEVec<T> {
321    type Item = &'a mut T;
322    type IntoIter = IterMut<'a, T>;
323
324    fn into_iter(self) -> Self::IntoIter {
325        self.0.iter_mut()
326    }
327}
328
329impl<T> IntoIterator for NEVec<T> {
330    type Item = T;
331    type IntoIter = IntoIter<T>;
332
333    fn into_iter(self) -> Self::IntoIter {
334        self.0.into_iter()
335    }
336}
337
338impl<T> Index<usize> for NEVec<T> {
339    type Output = T;
340
341    fn index(&self, index: usize) -> &Self::Output {
342        &self.0[index]
343    }
344}