1use std::convert::TryFrom;
2use std::num::NonZeroUsize;
3use std::ops;
4use std::slice::{Iter, IterMut, SliceIndex};
5use std::vec::IntoIter;
6
7#[cfg(feature = "serde")]
8use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
9
10#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct NonEmpty<T>(Vec<T>);
18
19impl<T> NonEmpty<T> {
20 #[inline]
21 pub fn new(v: T) -> Self {
22 Self(vec![v])
23 }
24
25 #[inline]
30 pub unsafe fn new_unchecked(vec: Vec<T>) -> Self {
31 Self(vec)
32 }
33
34 #[inline]
35 pub fn as_slice(&self) -> &[T] {
36 &self.0
37 }
38
39 #[inline]
40 pub fn as_mut_slice(&mut self) -> &mut [T] {
41 &mut self.0
42 }
43
44 #[inline]
45 pub fn as_ptr(&self) -> *const T {
46 self.0.as_ptr()
47 }
48
49 #[inline]
50 pub fn as_mut_ptr(&mut self) -> *const T {
51 self.0.as_mut_ptr()
52 }
53
54 #[inline]
55 pub fn len(&self) -> NonZeroUsize {
56 unsafe { NonZeroUsize::new_unchecked(self.0.len()) }
57 }
58
59 #[inline]
60 pub const fn is_empty(&self) -> bool {
61 false
62 }
63
64 #[inline]
65 pub fn first(&self) -> &T {
66 unsafe { self.0.get_unchecked(0) }
67 }
68
69 #[inline]
70 pub fn first_mut(&mut self) -> &mut T {
71 unsafe { self.0.get_unchecked_mut(0) }
72 }
73
74 #[inline]
75 pub fn last(&self) -> &T {
76 let i = self.len().get() - 1;
77 unsafe { self.0.get_unchecked(i) }
78 }
79
80 #[inline]
81 pub fn last_mut(&mut self) -> &mut T {
82 let i = self.len().get() - 1;
83 unsafe { self.0.get_unchecked_mut(i) }
84 }
85
86 #[inline]
87 pub fn split_first(&self) -> (&T, &[T]) {
88 (&self[0], &self[1..])
89 }
90
91 #[inline]
92 pub fn split_first_mut(&mut self) -> (&mut T, &mut [T]) {
93 let split = self.0.split_at_mut(1);
94 (&mut split.0[0], split.1)
95 }
96
97 #[inline]
98 pub fn split_last(&self) -> (&T, &[T]) {
99 let len = self.len().get();
100 (&self[len - 1], &self[..(len - 1)])
101 }
102
103 #[inline]
104 pub fn split_last_mut(&mut self) -> (&mut T, &mut [T]) {
105 let i = self.len().get() - 1;
106 let split = self.0.split_at_mut(i);
107 (&mut split.1[0], split.0)
108 }
109
110 #[inline]
111 pub fn pop(&mut self) -> Option<T> {
112 if self.0.len() <= 1 {
113 None
114 } else {
115 self.0.pop()
116 }
117 }
118
119 #[inline]
120 pub fn push(&mut self, v: T) {
121 self.0.push(v)
122 }
123
124 #[inline]
125 pub fn truncate(&mut self, len: NonZeroUsize) {
126 self.0.truncate(len.get())
127 }
128
129 #[inline]
130 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
131 self.0.iter_mut()
132 }
133}
134
135impl<T> From<(Vec<T>, T)> for NonEmpty<T> {
136 fn from((mut xs, x): (Vec<T>, T)) -> NonEmpty<T> {
137 xs.push(x);
138 NonEmpty(xs)
139 }
140}
141
142impl<T> From<(T, Vec<T>)> for NonEmpty<T> {
143 fn from((x, mut xs): (T, Vec<T>)) -> NonEmpty<T> {
144 xs.insert(0, x);
145 NonEmpty(xs)
146 }
147}
148
149impl<T> From<NonEmpty<T>> for Vec<T> {
150 fn from(v: NonEmpty<T>) -> Self {
151 v.0
152 }
153}
154
155#[derive(Debug, PartialEq)]
156pub struct EmptyError;
157
158impl<T> TryFrom<Vec<T>> for NonEmpty<T> {
159 type Error = EmptyError;
160 fn try_from(xs: Vec<T>) -> Result<Self, Self::Error> {
161 if xs.is_empty() {
162 Err(EmptyError)
163 } else {
164 Ok(NonEmpty(xs))
165 }
166 }
167}
168
169impl<T> ops::Deref for NonEmpty<T> {
170 type Target = [T];
171
172 fn deref(&self) -> &[T] {
173 self.0.deref()
174 }
175}
176
177impl<T> AsRef<[T]> for NonEmpty<T> {
178 fn as_ref(&self) -> &[T] {
179 self
180 }
181}
182
183impl<T> AsMut<[T]> for NonEmpty<T> {
184 fn as_mut(&mut self) -> &mut [T] {
185 self.0.as_mut()
186 }
187}
188
189impl<T> AsRef<Vec<T>> for NonEmpty<T> {
190 fn as_ref(&self) -> &Vec<T> {
191 &self.0
192 }
193}
194
195impl<T, I: SliceIndex<[T]>> ops::Index<I> for NonEmpty<T> {
196 type Output = I::Output;
197
198 #[inline]
199 fn index(&self, index: I) -> &Self::Output {
200 ops::Index::index(self.as_slice(), index)
201 }
202}
203impl<T, I: SliceIndex<[T]>> ops::IndexMut<I> for NonEmpty<T> {
204 #[inline]
205 fn index_mut(&mut self, index: I) -> &mut Self::Output {
206 ops::IndexMut::index_mut(self.as_mut_slice(), index)
207 }
208}
209
210impl<T> IntoIterator for NonEmpty<T> {
211 type Item = T;
212 type IntoIter = IntoIter<T>;
213 #[inline]
214 fn into_iter(self) -> Self::IntoIter {
215 self.0.into_iter()
216 }
217}
218impl<'a, T> IntoIterator for &'a NonEmpty<T> {
219 type Item = &'a T;
220 type IntoIter = Iter<'a, T>;
221 #[inline]
222 fn into_iter(self) -> Self::IntoIter {
223 self.0.iter()
224 }
225}
226impl<'a, T> IntoIterator for &'a mut NonEmpty<T> {
227 type Item = &'a mut T;
228 type IntoIter = IterMut<'a, T>;
229 #[inline]
230 fn into_iter(self) -> Self::IntoIter {
231 self.0.iter_mut()
232 }
233}
234
235#[cfg(feature = "serde")]
236impl<T: Serialize> Serialize for NonEmpty<T> {
237 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
238 self.as_slice().serialize(serializer)
239 }
240}
241
242#[cfg(feature = "serde")]
243impl<'de, T: Deserialize<'de>> Deserialize<'de> for NonEmpty<T> {
244 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
245 Self::try_from(<Vec<T>>::deserialize(deserializer)?)
246 .map_err(|_| D::Error::custom("empty vector"))
247 }
248}
249
250#[macro_export]
294macro_rules! ne_vec {
295 () => {
296 ::std::compile_error!("`NonEmpty` vector must be non-empty")
297 };
298 ($($x:expr),+ $(,)?) => {
299 unsafe { $crate::NonEmpty::new_unchecked(vec![$($x),+]) }
300 };
301 ($elem:expr; 0) => {
302 ne_vec![]
304 };
305 ($elem:expr; $n:literal) => {{
306 const _ASSERT_NON_ZERO: [(); $n - 1] = [(); $n - 1];
308 unsafe { $crate::NonEmpty::new_unchecked(vec![$elem; $n]) }
309 }};
310 ($elem:expr; $n:expr) => {{
311 if $n == 0 {
313 ::std::panic!("`NonEmpty` vector must be non-empty");
314 }
315 unsafe { $crate::NonEmpty::new_unchecked(vec![$elem; $n]) }
316 }};
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322
323 #[test]
324 fn it_works() {
325 let mut list: NonEmpty<i32> = (vec![1, 2], 3).into();
327 assert_eq!(list, (1, vec![2, 3]).into());
328 assert_eq!(&*list, &[1, 2, 3]);
329
330 list[0] = 2;
332 assert_eq!(list[0], 2);
333 list[0] = 1;
334 assert_eq!(list[0], 1);
335
336 assert_eq!(list.len().get(), 3);
338 assert_eq!(list.as_slice(), &[1, 2, 3]);
339
340 assert_eq!(<NonEmpty<i32>>::try_from(vec![]).ok(), None);
342 assert_eq!(
343 &*<NonEmpty<i32>>::try_from(vec![1, 2, 3]).unwrap(),
344 &[1, 2, 3]
345 );
346
347 assert_eq!(
349 list.iter().map(|n| n * 2).collect::<Vec<_>>(),
350 vec![2, 4, 6]
351 );
352
353 let single = NonEmpty::new(15_i32);
355 assert_eq!(single.len().get(), 1);
356 assert_eq!(single[0], 15);
357 }
358
359 #[test]
360 fn into_iter() {
361 let mut list = ne_vec![1, 2, 3];
362
363 for (a, b) in [1, 2, 3].iter().zip(&list) {
364 assert_eq!(a, b);
365 }
366
367 for a in &mut list {
368 *a += 1;
369 }
370 assert_eq!(list.as_slice(), &[2, 3, 4]);
371
372 for (a, b) in vec![2, 3, 4].into_iter().zip(list) {
373 assert_eq!(a, b);
374 }
375 }
376
377 #[test]
378 fn initialize_macro() {
379 assert_eq!(ne_vec![1; 3].as_slice(), &[1, 1, 1]);
380 assert_eq!(ne_vec!["string"; 5].as_slice(), &["string"; 5]);
381 }
382
383 #[test]
384 #[should_panic]
385 fn initialize_macro_zero_size() {
386 let n = 0;
388 let _ = ne_vec![1; n];
389 }
390
391 #[cfg(feature = "serde")]
392 #[test]
393 fn serialize() {
394 use serde_json;
395
396 let vec: NonEmpty<u32> = (1, vec![]).into();
397 assert_eq!(
398 serde_json::from_str::<NonEmpty<u32>>(&serde_json::to_string(&vec).unwrap()).unwrap(),
399 vec
400 );
401 }
402}