singlevec/
lib.rs

1// Copyright 2024 Brian Langenberger
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! `SingleVec` is `Vec`-like container type optimized for storing a single item.
10//!
11//! 0 or 1 items are stored internally as a standard `Option` -
12//! which can be kept on the stack -
13//! but falls back to a standard `Vec` for multiple items -
14//! which are stored on the heap.
15//!
16//! Although `SingleVec` shares many of the same traits and methods as `Vec`,
17//! it also shares many of the same methods as `Option` and `Iterator`
18//! where appropriate.
19//! Since only a single optional item is intended to be the common case,
20//! those methods can avoid iteration altogether.
21//!
22//! ## Other Features
23//! * `serde` provides `Serialize` and `Deserialize` support,
24//!   provided that the inner type also has the same implementation.
25
26#![warn(missing_docs)]
27#![forbid(unsafe_code)]
28
29#[cfg(feature = "serde")]
30use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
31#[cfg(feature = "serde")]
32use serde::ser::{Serialize, SerializeSeq, Serializer};
33
34/// A `Vec`-like type optimized for storing 0 or 1 items.
35#[derive(Clone, Debug)]
36pub enum SingleVec<T> {
37    /// The common case of 0 or 1 items.
38    One(Option<T>),
39    /// The fallback case of 2 or more items.
40    Many(Vec<T>),
41}
42
43impl<T> SingleVec<T> {
44    /// Constructs a new, empty `SingleVec`
45    #[inline]
46    pub fn new() -> Self {
47        Self::One(None)
48    }
49
50    /// Appends an item to the back of the collection.
51    ///
52    /// # Example
53    /// ```
54    /// use singlevec::SingleVec;
55    /// let mut v = SingleVec::default();
56    /// v.push(1);
57    /// assert_eq!(v.as_slice(), &[1]);
58    /// v.push(2);
59    /// assert_eq!(v.as_slice(), &[1, 2]);
60    /// ```
61    #[inline]
62    pub fn push(&mut self, i: T) {
63        // hint to the compiler that pushing more than one
64        // item into singlevec is intended to be the
65        // exceptional case
66
67        #[cold]
68        fn move_to_vec<T>(o: &mut Option<T>, i: T) -> Vec<T> {
69            let mut v = Vec::with_capacity(2);
70            v.extend(o.take());
71            v.push(i);
72            v
73        }
74
75        match self {
76            Self::One(o @ None) => {
77                *o = Some(i);
78            }
79            Self::One(o @ Some(_)) => {
80                *self = Self::Many(move_to_vec(o, i));
81            }
82            Self::Many(v) => {
83                v.push(i);
84            }
85        }
86    }
87
88    /// Removes the last element from a `SingleVec` and returns it,
89    /// or None if it is empty.
90    ///
91    /// # Examples
92    /// ```
93    /// use singlevec::SingleVec;
94    /// let mut v = SingleVec::from([1, 2, 3]);
95    /// assert_eq!(v.pop(), Some(3));
96    /// assert_eq!(v.as_slice(), &[1, 2]);
97    /// ```
98    ///
99    /// ```
100    /// use singlevec::SingleVec;
101    /// let mut v = SingleVec::from([1]);
102    /// assert_eq!(v.pop(), Some(1));
103    /// assert_eq!(v.pop(), None);
104    /// assert!(v.is_empty());
105    /// ```
106    #[inline]
107    pub fn pop(&mut self) -> Option<T> {
108        match self {
109            Self::One(o) => o.take(),
110            Self::Many(v) => v.pop(),
111        }
112    }
113
114    /// Inserts an element at position index within the vector, shifting all elements after it to the right.
115    /// # Panics
116    ///
117    /// Panics if `index > len`.
118    pub fn insert(&mut self, index: usize, e: T) {
119        match self {
120            Self::One(None) if index == 0 => {
121                *self = Self::One(Some(e));
122            }
123            Self::One(None) => panic!("insertion index (is {index}) should be <= len (is 0)"),
124            Self::One(Some(_)) => match index {
125                0 => {
126                    let Some(o) = self.pop() else {
127                        unreachable!();
128                    };
129                    let mut v = Vec::new();
130                    v.push(e);
131                    v.push(o);
132                    *self = Self::Many(v);
133                }
134                1 => {
135                    let Some(o) = self.pop() else {
136                        unreachable!();
137                    };
138                    let mut v = Vec::new();
139                    v.push(o);
140                    v.push(e);
141                    *self = Self::Many(v);
142                }
143                _ => panic!("insertion index (is {index}) should be <= len (is 1)"),
144            },
145            Self::Many(v) => v.insert(index, e),
146        }
147    }
148
149    /// Removes and returns the element at position `index` within the vector,
150    /// shifting all elements after it to the left.
151    ///
152    /// # Panics
153    ///
154    /// Panics if `index` is out of bounds.
155    pub fn remove(&mut self, index: usize) -> T {
156        match self {
157            Self::One(None) => panic!("removal index (is {index}) should be < len (is 0)"),
158            Self::One(Some(_)) if index == 0 => {
159                let Some(o) = self.pop() else {
160                    unreachable!();
161                };
162                *self = Self::One(None);
163                o
164            }
165            Self::One(Some(_)) => {
166                panic!("removal index (is {index}) should be < len (is 1)");
167            }
168            Self::Many(v) => v.remove(index),
169        }
170    }
171
172    /// Extracts a slice containing the entire `SingleVec`.
173    #[inline]
174    pub fn as_slice(&self) -> &[T] {
175        match self {
176            Self::One(o) => o.as_slice(),
177            Self::Many(v) => v.as_slice(),
178        }
179    }
180
181    /// Extracts a mutable slice containing the entire `SingleVec`.
182    #[inline]
183    pub fn as_mut_slice(&mut self) -> &mut [T] {
184        match self {
185            Self::One(o) => o.as_mut_slice(),
186            Self::Many(v) => v.as_mut_slice(),
187        }
188    }
189
190    /// Converts from `&SingleVec<T>` to `SingleVec<&T>`
191    #[inline]
192    pub fn as_ref(&self) -> SingleVec<&T> {
193        match self {
194            Self::One(o) => SingleVec::One(o.as_ref()),
195            Self::Many(v) => SingleVec::Many(v.iter().collect()),
196        }
197    }
198
199    /// Converts from `&mut SingleVec<T>` to `SingleVec<&mut T>`
200    #[inline]
201    pub fn as_mut(&mut self) -> SingleVec<&mut T> {
202        match self {
203            Self::One(o) => SingleVec::One(o.as_mut()),
204            Self::Many(v) => SingleVec::Many(v.iter_mut().collect()),
205        }
206    }
207
208    /// Clears the `SingleVec`, removing all values.
209    ///
210    /// # Example
211    /// ```
212    /// use singlevec::SingleVec;
213    /// let mut v = SingleVec::from([1, 2, 3]);
214    /// v.clear();
215    /// assert!(v.is_empty());
216    /// ```
217    #[inline]
218    pub fn clear(&mut self) {
219        *self = Self::default();
220    }
221
222    /// Uses a closure to determine which elements should remain in the output.
223    /// Given an element the closure must return `true` or `false`.
224    /// The remaining items are those for which the closure returns `true`.
225    ///
226    /// # Examples
227    /// ```
228    /// use singlevec::SingleVec;
229    /// let v = SingleVec::from([0i32, 1, 2]);
230    /// assert_eq!(v.filter(|x| x.is_positive()).as_slice(), &[1, 2]);
231    /// ```
232    ///
233    /// ```
234    /// use singlevec::SingleVec;
235    /// let v = SingleVec::from([0, 1, 2]);
236    /// assert_eq!(v.filter(|x| *x > 1).as_slice(), &[2]);
237    /// ```
238    #[inline]
239    pub fn filter(self, f: impl FnMut(&T) -> bool) -> Self {
240        match self {
241            Self::One(o) => Self::One(o.filter(f)),
242            Self::Many(v) => v.into_iter().filter(f).collect(),
243        }
244    }
245
246    /// Maps a `SingleVec<T>` to a `SingleVec<U>`
247    /// by applying a conversion function to each element.
248    ///
249    /// # Examples
250    /// ```
251    /// use singlevec::SingleVec;
252    /// let v = SingleVec::from(["Hello"]);
253    /// assert_eq!(v.map(|s| s.len()), [5].into());
254    /// ```
255    ///
256    /// ```
257    /// use singlevec::SingleVec;
258    /// let v = SingleVec::from(["Hello", "World!"]);
259    /// assert_eq!(v.map(|s| s.len()), [5, 6].into());
260    /// ```
261    #[inline]
262    pub fn map<U>(self, f: impl FnMut(T) -> U) -> SingleVec<U> {
263        match self {
264            Self::One(o) => SingleVec::One(o.map(f)),
265            Self::Many(v) => SingleVec::Many(v.into_iter().map(f).collect()),
266        }
267    }
268
269    /// Combines both a filter and map into a single operation.
270    ///
271    /// The returned `SingleVec` contains only items for which
272    /// the supplied closure returns `Some(value)`.
273    ///
274    /// # Examples
275    /// ```
276    /// use singlevec::SingleVec;
277    /// let v = SingleVec::from(Some("5"));
278    /// assert_eq!(v.filter_map(|s| s.parse().ok()), [5].into());
279    /// ```
280    ///
281    /// ```
282    /// use singlevec::SingleVec;
283    /// let v = SingleVec::from(["1", "two", "NaN", "four", "5"]);
284    /// assert_eq!(v.filter_map(|s| s.parse().ok()), [1, 5].into());
285    /// ```
286    #[inline]
287    pub fn filter_map<U>(self, mut f: impl FnMut(T) -> Option<U>) -> SingleVec<U> {
288        match self {
289            Self::One(None) => SingleVec::One(None),
290            Self::One(Some(t)) => SingleVec::One(f(t)),
291            Self::Many(v) => v.into_iter().filter_map(f).collect(),
292        }
293    }
294
295    /// Reduces `SingleVec` to a single item by repeatedly applying a reducing operation.
296    ///
297    /// The reducing function is a closure with two arguments:
298    /// an accumulator, and an element.
299    ///
300    /// If the `SingleVec` contains a single item, returns that item.
301    ///
302    /// For a `SingleVec` with more than one item this is the same as fold()
303    /// with the first element as the initial accumulator value,
304    /// folding every subsequent element into it.
305    ///
306    /// # Examples
307    ///
308    /// ```
309    /// use singlevec::SingleVec;
310    /// let v = SingleVec::from([1, 2, 3]);
311    /// assert_eq!(v.reduce(|acc, x| acc + x), Some(6));
312    /// ```
313    ///
314    /// ```
315    /// use singlevec::SingleVec;
316    /// let v = SingleVec::from([1]);
317    /// assert_eq!(v.reduce(|acc, x| acc + x), Some(1));
318    /// ```
319    ///
320    /// ```
321    /// use singlevec::SingleVec;
322    /// let v = SingleVec::default();
323    /// assert_eq!(v.reduce(|acc: i32, x| acc + x), None);
324    /// ```
325    #[inline]
326    pub fn reduce(self, f: impl FnMut(T, T) -> T) -> Option<T> {
327        match self {
328            Self::One(o) => o,
329            Self::Many(v) => v.into_iter().reduce(f),
330        }
331    }
332
333    /// Folds every `SingleVec` element into an accumulator by applying a closure.
334    ///
335    /// Takes an initial value and a closure with two arguments:
336    /// an accumulator, and an element.
337    /// The closure returns the value that the accumulator should have
338    /// for the next iteration.
339    ///
340    /// The initial value is the value the accumulator will have on the first call.
341    ///
342    /// Returns the final accumulator
343    ///
344    /// # Example
345    /// ```
346    /// use singlevec::SingleVec;
347    /// let v = SingleVec::from([1, 2, 3]);
348    /// assert_eq!(v.fold(0, |acc, x| acc + x), 6);
349    /// ```
350    #[inline]
351    pub fn fold<B>(self, init: B, mut f: impl FnMut(B, T) -> B) -> B {
352        match self {
353            Self::One(None) => init,
354            Self::One(Some(o)) => f(init, o),
355            Self::Many(v) => v.into_iter().fold(init, f),
356        }
357    }
358
359    /// Zips `SingleVec` with another `SingleVec`
360    ///
361    /// # Examples
362    ///
363    /// ```
364    /// use singlevec::SingleVec;
365    /// let v1 = SingleVec::from([1]);
366    /// let v2 = SingleVec::from([2]);
367    /// assert_eq!(v1.zip(v2), [(1, 2)].into());
368    /// ```
369    ///
370    /// ```
371    /// use singlevec::SingleVec;
372    /// let v1 = SingleVec::from([1, 2]);
373    /// let v2 = SingleVec::from([3, 4]);
374    /// assert_eq!(v1.zip(v2), [(1, 3), (2, 4)].into());
375    /// ```
376    ///
377    /// ```
378    /// use singlevec::SingleVec;
379    /// let v1 = SingleVec::from([1, 2, 3]);
380    /// let v2 = SingleVec::from([4, 5]);
381    /// assert_eq!(v1.zip(v2), [(1, 4), (2, 5)].into());
382    /// ```
383    #[inline]
384    pub fn zip<U>(self, other: SingleVec<U>) -> SingleVec<(T, U)> {
385        match (self, other) {
386            (Self::One(x), SingleVec::One(y)) => SingleVec::One(x.zip(y)),
387            (i, j) => i.into_iter().zip(j).collect(),
388        }
389    }
390
391    /// Retains only the elements specified by the predicate.
392    ///
393    /// Removes all elements e for which `f(&e)` returns `false`.
394    /// This method operates in place, visiting each element exactly
395    /// once in the original order,
396    /// and preserves the order of the retained elements.
397    ///
398    /// # Examples
399    /// ```
400    /// use singlevec::SingleVec;
401    /// let mut v = SingleVec::from([1, 2, 3, 4]);
402    /// v.retain(|&x| x % 2 == 0);
403    /// assert_eq!(v.as_slice(), [2, 4]);
404    /// ```
405    ///
406    /// ```
407    /// use singlevec::SingleVec;
408    /// let mut v = SingleVec::from([1]);
409    /// v.retain(|&x| x % 2 == 0);
410    /// assert!(v.is_empty());
411    /// ```
412    #[inline]
413    pub fn retain(&mut self, mut f: impl FnMut(&T) -> bool) {
414        match self {
415            Self::One(o) => {
416                if o.as_ref().is_some_and(|x| !f(x)) {
417                    *o = None;
418                }
419            }
420            Self::Many(v) => v.retain(f),
421        }
422    }
423
424    /// Retains only the elements specified by the predicate, passing a mutable reference to it.
425    ///
426    /// Removes all elements e such that `f(&mut e)` returns `false`.
427    /// This method operates in place, visiting each element exactly
428    /// once in the original order,
429    /// and preserves the order of the retained elements.
430    ///
431    /// # Examples
432    /// ```
433    /// use singlevec::SingleVec;
434    /// let mut v = SingleVec::from([1, 2, 3, 4]);
435    /// v.retain_mut(|x| if *x <= 3 {
436    ///     *x *= 10;
437    ///     true
438    /// } else {
439    ///     false
440    /// });
441    /// assert_eq!(v.as_slice(), [10, 20, 30]);
442    /// ```
443    ///
444    /// ```
445    /// use singlevec::SingleVec;
446    /// let mut v = SingleVec::from([1]);
447    /// v.retain_mut(|x| if *x <= 3 {
448    ///     *x *= 10;
449    ///     true
450    /// } else {
451    ///     false
452    /// });
453    /// assert_eq!(v.as_slice(), [10]);
454    /// ```
455    #[inline]
456    pub fn retain_mut(&mut self, mut f: impl FnMut(&mut T) -> bool) {
457        match self {
458            Self::One(o) => {
459                if o.as_mut().is_some_and(|x| !f(x)) {
460                    *o = None;
461                }
462            }
463            Self::Many(v) => v.retain_mut(f),
464        }
465    }
466}
467
468impl<T> SingleVec<Option<T>> {
469    /// Removes exactly one level of nesting from a `SingleVec`
470    ///
471    /// # Examples
472    /// ```
473    /// use singlevec::SingleVec;
474    /// let v = SingleVec::from([Some(1), Some(2), None]);
475    /// assert_eq!(v.flatten().as_slice(), &[1, 2]);
476    /// ```
477    ///
478    /// ```
479    /// use singlevec::SingleVec;
480    /// let v = SingleVec::from([Some(Some(1))]);
481    /// assert_eq!(v.flatten().as_slice(), &[Some(1)]);
482    /// ```
483    #[inline]
484    pub fn flatten(self) -> SingleVec<T> {
485        match self {
486            Self::One(None) => SingleVec::One(None),
487            Self::One(Some(inner)) => SingleVec::One(inner),
488            Self::Many(v) => v.into_iter().flatten().collect(),
489        }
490    }
491
492    /// Transposes a `SingleVec` of `Option` into a `Option` of `SingleVec`.
493    ///
494    /// # Examples
495    /// ```
496    /// use singlevec::SingleVec;
497    ///
498    /// let input: SingleVec<Option<i32>> = SingleVec::from([Some(1)]);
499    /// let output: Option<SingleVec<i32>> = Some(SingleVec::from([1]));
500    /// assert_eq!(input.transpose(), output);
501    /// ```
502    ///
503    /// ```
504    /// use singlevec::SingleVec;
505    ///
506    /// let input: SingleVec<Option<char>> = SingleVec::from([Some('a'), None]);
507    /// assert!(input.transpose().is_none());
508    /// ```
509    #[inline]
510    pub fn transpose(self) -> Option<SingleVec<T>> {
511        match self {
512            Self::One(None) => None,
513            Self::One(Some(inner)) => Some(SingleVec::One(inner)),
514            Self::Many(v) => v.into_iter().collect::<Option<_>>().map(SingleVec::Many),
515        }
516    }
517}
518
519impl<T> SingleVec<SingleVec<T>> {
520    /// Removes exactly one level of nesting from a `SingleVec`
521    ///
522    /// # Examples
523    /// ```
524    /// use singlevec::SingleVec;
525    /// let v: SingleVec<SingleVec<i32>> = [[1].into(), [2].into(), [].into()].into();
526    /// assert_eq!(v.flatten().as_slice(), &[1, 2]);
527    /// ```
528    ///
529    /// ```
530    /// use singlevec::SingleVec;
531    /// let v: SingleVec<SingleVec<i32>> = [[1].into()].into();
532    /// assert_eq!(v.flatten().as_slice(), &[1]);
533    /// ```
534    #[inline]
535    pub fn flatten(self) -> SingleVec<T> {
536        match self {
537            Self::One(None) => SingleVec::One(None),
538            Self::One(Some(inner)) => inner,
539            Self::Many(v) => v.into_iter().flatten().collect(),
540        }
541    }
542}
543
544impl<T> SingleVec<Vec<T>> {
545    /// Removes exactly one level of nesting from a `SingleVec`
546    ///
547    /// # Examples
548    /// ```
549    /// use singlevec::SingleVec;
550    /// let v: SingleVec<Vec<i32>> = [vec![1], vec![2], vec![]].into();
551    /// assert_eq!(v.flatten().as_slice(), &[1, 2]);
552    /// ```
553    ///
554    /// ```
555    /// use singlevec::SingleVec;
556    /// let v: SingleVec<Vec<i32>> = [vec![1, 2, 3]].into();
557    /// assert_eq!(v.flatten().as_slice(), &[1, 2, 3]);
558    /// ```
559    ///
560    /// ```
561    /// use singlevec::SingleVec;
562    /// let v: SingleVec<Vec<i32>> = [vec![1]].into();
563    /// assert_eq!(v.flatten().as_slice(), &[1]);
564    /// ```
565    #[inline]
566    pub fn flatten(self) -> SingleVec<T> {
567        match self {
568            Self::One(None) => SingleVec::One(None),
569            Self::One(Some(inner)) => SingleVec::Many(inner),
570            Self::Many(v) => v.into_iter().flatten().collect(),
571        }
572    }
573}
574
575impl<T, U> SingleVec<(T, U)> {
576    /// Unzips `SingleVec` containing a tuple into a tuple of two `SingleVec`s
577    ///
578    /// # Examples
579    /// ```
580    /// use singlevec::SingleVec;
581    /// let v = SingleVec::from([(1, 2)]);
582    /// assert_eq!(v.unzip(), ([1].into(), [2].into()));
583    /// ```
584    ///
585    /// ```
586    /// use singlevec::SingleVec;
587    /// let v = SingleVec::from([(1, 2), (3, 4)]);
588    /// assert_eq!(v.unzip(), ([1, 3].into(), [2, 4].into()));
589    /// ```
590    #[inline]
591    pub fn unzip(self) -> (SingleVec<T>, SingleVec<U>) {
592        match self {
593            Self::One(None) => (SingleVec::One(None), SingleVec::One(None)),
594            Self::One(Some((t, u))) => (SingleVec::One(Some(t)), SingleVec::One(Some(u))),
595            Self::Many(v) => v.into_iter().unzip(),
596        }
597    }
598}
599
600impl<T, E> SingleVec<Result<T, E>> {
601    /// Transposes a `SingleVec` of `Result` into a `Result` of `SingleVec`,
602    /// using the first error encoutered, if any.
603    ///
604    /// # Examples
605    /// ```
606    /// use singlevec::SingleVec;
607    ///
608    /// #[derive(Debug, Eq, PartialEq)]
609    /// struct SomeErr;
610    ///
611    /// let input: SingleVec<Result<i32, SomeErr>> = SingleVec::from([Ok(1)]);
612    /// let output: Result<SingleVec<i32>, SomeErr> = Ok(SingleVec::from([1]));
613    /// assert_eq!(input.transpose(), output);
614    /// ```
615    ///
616    /// ```
617    /// use singlevec::SingleVec;
618    ///
619    /// #[derive(Debug, Eq, PartialEq)]
620    /// struct SomeErr(i32);
621    ///
622    /// let input: SingleVec<Result<char, SomeErr>> = SingleVec::from([Ok('a'), Err(SomeErr(2)), Err(SomeErr(3))]);
623    /// let output: Result<SingleVec<char>, SomeErr> = Err(SomeErr(2));
624    /// assert_eq!(input.transpose(), output);
625    /// ```
626    #[inline]
627    pub fn transpose(self) -> Result<SingleVec<T>, E> {
628        match self {
629            Self::One(o) => o.transpose().map(SingleVec::One),
630            Self::Many(v) => v.into_iter().collect::<Result<_, _>>().map(SingleVec::Many),
631        }
632    }
633}
634
635impl<T> Default for SingleVec<T> {
636    #[inline]
637    fn default() -> Self {
638        Self::new()
639    }
640}
641
642// Although SingleVec::One and SingleVec::Many store data differently,
643// they should compare and hash the same if their contents are the same
644// without the end user having to know which "mode" the SingleVec
645// is in.
646
647impl<T: core::cmp::Eq> core::cmp::Eq for SingleVec<T> {}
648
649impl<T: core::cmp::PartialEq> core::cmp::PartialEq for SingleVec<T> {
650    #[inline]
651    fn eq(&self, other: &SingleVec<T>) -> bool {
652        self.as_slice().eq(other.as_slice())
653    }
654}
655
656impl<T: core::cmp::Ord> core::cmp::Ord for SingleVec<T> {
657    #[inline]
658    fn cmp(&self, other: &SingleVec<T>) -> core::cmp::Ordering {
659        self.as_slice().cmp(other.as_slice())
660    }
661}
662
663impl<T: core::cmp::PartialOrd> core::cmp::PartialOrd for SingleVec<T> {
664    #[inline]
665    fn partial_cmp(&self, other: &SingleVec<T>) -> Option<core::cmp::Ordering> {
666        self.as_slice().partial_cmp(other.as_slice())
667    }
668}
669
670impl<T: core::hash::Hash> core::hash::Hash for SingleVec<T> {
671    #[inline]
672    fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
673        self.as_slice().hash(h)
674    }
675}
676
677impl<T> core::ops::Deref for SingleVec<T> {
678    type Target = [T];
679
680    #[inline]
681    fn deref(&self) -> &[T] {
682        self.as_slice()
683    }
684}
685
686impl<T> core::ops::DerefMut for SingleVec<T> {
687    #[inline]
688    fn deref_mut(&mut self) -> &mut [T] {
689        self.as_mut_slice()
690    }
691}
692
693impl<T> Extend<T> for SingleVec<T> {
694    #[inline]
695    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
696        for v in iter {
697            self.push(v);
698        }
699    }
700}
701
702impl<T> FromIterator<T> for SingleVec<T> {
703    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
704        let mut s = Self::default();
705        s.extend(iter);
706        s
707    }
708}
709
710impl<T> IntoIterator for SingleVec<T> {
711    type Item = T;
712
713    type IntoIter =
714        EitherIterator<<Option<T> as IntoIterator>::IntoIter, <Vec<T> as IntoIterator>::IntoIter>;
715
716    #[inline]
717    fn into_iter(self) -> Self::IntoIter {
718        match self {
719            Self::One(o) => EitherIterator::I(o.into_iter()),
720            Self::Many(v) => EitherIterator::J(v.into_iter()),
721        }
722    }
723}
724
725impl<'t, T> IntoIterator for &'t SingleVec<T> {
726    type Item = &'t T;
727
728    type IntoIter = <&'t [T] as IntoIterator>::IntoIter;
729
730    #[inline]
731    fn into_iter(self) -> Self::IntoIter {
732        self.as_slice().iter()
733    }
734}
735
736impl<T> From<Option<T>> for SingleVec<T> {
737    #[inline]
738    fn from(o: Option<T>) -> Self {
739        Self::One(o)
740    }
741}
742
743impl<T> From<Vec<T>> for SingleVec<T> {
744    #[inline]
745    fn from(mut v: Vec<T>) -> Self {
746        match v.len() {
747            0 | 1 => Self::One(v.pop()),
748            _ => Self::Many(v),
749        }
750    }
751}
752
753impl<T> From<SingleVec<T>> for Vec<T> {
754    #[inline]
755    fn from(v: SingleVec<T>) -> Self {
756        match v {
757            SingleVec::One(None) => Vec::new(),
758            SingleVec::One(Some(x)) => vec![x],
759            SingleVec::Many(v) => v,
760        }
761    }
762}
763
764impl<T> TryFrom<SingleVec<T>> for Option<T> {
765    type Error = Vec<T>;
766
767    #[inline]
768    fn try_from(v: SingleVec<T>) -> Result<Self, Self::Error> {
769        match v {
770            SingleVec::One(o) => Ok(o),
771            SingleVec::Many(mut v) if v.len() < 2 => Ok(v.pop()),
772            SingleVec::Many(v) => Err(v),
773        }
774    }
775}
776
777impl<T, const N: usize> From<[T; N]> for SingleVec<T> {
778    #[inline]
779    fn from(v: [T; N]) -> Self {
780        v.into_iter().collect()
781    }
782}
783
784#[cfg(feature = "serde")]
785impl<T: Serialize> Serialize for SingleVec<T> {
786    #[must_use]
787    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
788    where
789        S: Serializer,
790    {
791        let mut seq = serializer.serialize_seq(Some(self.len()))?;
792        for element in self.iter() {
793            seq.serialize_element(element)?;
794        }
795        seq.end()
796    }
797}
798
799#[cfg(feature = "serde")]
800impl<'de, T: Deserialize<'de>> Deserialize<'de> for SingleVec<T> {
801    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
802    where
803        D: Deserializer<'de>,
804    {
805        deserializer.deserialize_seq(SingleVecVisitor(core::marker::PhantomData))
806    }
807}
808
809#[cfg(feature = "serde")]
810struct SingleVecVisitor<T>(core::marker::PhantomData<T>);
811
812#[cfg(feature = "serde")]
813impl<'de, T: Deserialize<'de>> Visitor<'de> for SingleVecVisitor<T> {
814    type Value = SingleVec<T>;
815
816    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
817        formatter.write_str("a sequence")
818    }
819
820    fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
821    where
822        S: SeqAccess<'de>,
823    {
824        let mut v = SingleVec::default();
825
826        while let Some(value) = seq.next_element()? {
827            v.push(value);
828        }
829
830        Ok(v)
831    }
832}
833
834#[cfg(test)]
835mod tests {
836    use super::SingleVec;
837
838    #[test]
839    fn iter_test() {
840        let v = SingleVec::from([1, 2, 3]);
841        assert_eq!(v.iter().copied().sum::<i32>(), 6);
842
843        let v = SingleVec::from([1, 2, 3]);
844        assert_eq!((&v).into_iter().copied().sum::<i32>(), 6);
845    }
846
847    #[test]
848    fn index_test() {
849        let mut v = SingleVec::from([1, 2, 3]);
850        assert_eq!(v[0], 1);
851        assert_eq!(v[1], 2);
852        assert_eq!(v[2], 3);
853
854        v[0] = 3;
855        v[1] = 2;
856        v[2] = 1;
857
858        assert_eq!(v[0], 3);
859        assert_eq!(v[1], 2);
860        assert_eq!(v[2], 1);
861    }
862
863    #[test]
864    fn eq_test() {
865        let v1: SingleVec<i32> = SingleVec::One(None);
866        let v2 = SingleVec::Many(vec![]);
867        assert_eq!(v1, v2);
868
869        let v1: SingleVec<i32> = SingleVec::One(Some(1));
870        let v2 = SingleVec::Many(vec![1]);
871        assert_eq!(v1, v2);
872    }
873
874    #[test]
875    fn ord_test() {
876        let v1: SingleVec<i32> = SingleVec::One(Some(1));
877        let v2 = SingleVec::Many(vec![2]);
878        assert!(v1 < v2);
879    }
880
881    #[test]
882    fn hash_test() {
883        let mut h = std::collections::HashSet::new();
884        h.insert(SingleVec::One(Some(1)));
885        assert!(h.contains(&SingleVec::Many(vec![1])));
886    }
887
888    #[test]
889    fn insert_test() {
890        let mut v = SingleVec::new();
891        v.insert(0, 2);
892        v.insert(0, 1);
893        v.insert(2, 3);
894
895        assert_eq!(v[0], 1);
896        assert_eq!(v[1], 2);
897        assert_eq!(v[2], 3);
898    }
899
900    #[test]
901    fn remove_test() {
902        let mut v = SingleVec::from([1, 2, 3]);
903        assert_eq!(v.remove(0), 1);
904        assert_eq!(v.remove(0), 2);
905        assert_eq!(v.remove(0), 3);
906    }
907}
908
909/// An iterator which can be one of two possible variants
910/// but iterate over the same type.
911///
912/// Checks the iterator variant on each iteration,
913/// but the expectation is that the iterator length
914/// will usually be very short.
915#[derive(Clone, Debug)]
916pub enum EitherIterator<I, J> {
917    /// The first iterator variant
918    I(I),
919    /// The second iterator variant
920    J(J),
921}
922
923impl<I: Iterator, J: Iterator<Item = I::Item>> Iterator for EitherIterator<I, J> {
924    type Item = I::Item;
925
926    #[inline]
927    fn next(&mut self) -> Option<Self::Item> {
928        match self {
929            Self::I(i) => i.next(),
930            Self::J(j) => j.next(),
931        }
932    }
933
934    #[inline]
935    fn size_hint(&self) -> (usize, Option<usize>) {
936        match self {
937            Self::I(i) => i.size_hint(),
938            Self::J(j) => j.size_hint(),
939        }
940    }
941
942    #[inline]
943    fn count(self) -> usize
944    where
945        Self: Sized,
946    {
947        match self {
948            Self::I(i) => i.count(),
949            Self::J(j) => j.count(),
950        }
951    }
952
953    #[inline]
954    fn last(self) -> Option<Self::Item>
955    where
956        Self: Sized,
957    {
958        match self {
959            Self::I(i) => i.last(),
960            Self::J(j) => j.last(),
961        }
962    }
963
964    #[inline]
965    fn for_each<F>(self, f: F)
966    where
967        Self: Sized,
968        F: FnMut(Self::Item),
969    {
970        match self {
971            Self::I(i) => i.for_each(f),
972            Self::J(j) => j.for_each(f),
973        }
974    }
975
976    #[inline]
977    fn collect<B>(self) -> B
978    where
979        B: FromIterator<Self::Item>,
980        Self: Sized,
981    {
982        match self {
983            Self::I(i) => i.collect(),
984            Self::J(j) => j.collect(),
985        }
986    }
987
988    #[inline]
989    fn partition<B, F>(self, f: F) -> (B, B)
990    where
991        Self: Sized,
992        B: Default + Extend<Self::Item>,
993        F: FnMut(&Self::Item) -> bool,
994    {
995        match self {
996            Self::I(i) => i.partition(f),
997            Self::J(j) => j.partition(f),
998        }
999    }
1000
1001    #[inline]
1002    fn fold<B, F>(self, init: B, f: F) -> B
1003    where
1004        Self: Sized,
1005        F: FnMut(B, Self::Item) -> B,
1006    {
1007        match self {
1008            Self::I(i) => i.fold(init, f),
1009            Self::J(j) => j.fold(init, f),
1010        }
1011    }
1012
1013    #[inline]
1014    fn reduce<F>(self, f: F) -> Option<Self::Item>
1015    where
1016        Self: Sized,
1017        F: FnMut(Self::Item, Self::Item) -> Self::Item,
1018    {
1019        match self {
1020            Self::I(i) => i.reduce(f),
1021            Self::J(j) => j.reduce(f),
1022        }
1023    }
1024
1025    #[inline]
1026    fn all<F>(&mut self, f: F) -> bool
1027    where
1028        Self: Sized,
1029        F: FnMut(Self::Item) -> bool,
1030    {
1031        match self {
1032            Self::I(i) => i.all(f),
1033            Self::J(j) => j.all(f),
1034        }
1035    }
1036
1037    #[inline]
1038    fn any<F>(&mut self, f: F) -> bool
1039    where
1040        Self: Sized,
1041        F: FnMut(Self::Item) -> bool,
1042    {
1043        match self {
1044            Self::I(i) => i.any(f),
1045            Self::J(j) => j.any(f),
1046        }
1047    }
1048
1049    #[inline]
1050    fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
1051    where
1052        Self: Sized,
1053        P: FnMut(&Self::Item) -> bool,
1054    {
1055        match self {
1056            Self::I(i) => i.find(predicate),
1057            Self::J(j) => j.find(predicate),
1058        }
1059    }
1060
1061    #[inline]
1062    fn find_map<B, F>(&mut self, f: F) -> Option<B>
1063    where
1064        Self: Sized,
1065        F: FnMut(Self::Item) -> Option<B>,
1066    {
1067        match self {
1068            Self::I(i) => i.find_map(f),
1069            Self::J(j) => j.find_map(f),
1070        }
1071    }
1072
1073    #[inline]
1074    fn position<P>(&mut self, predicate: P) -> Option<usize>
1075    where
1076        Self: Sized,
1077        P: FnMut(Self::Item) -> bool,
1078    {
1079        match self {
1080            Self::I(i) => i.position(predicate),
1081            Self::J(j) => j.position(predicate),
1082        }
1083    }
1084
1085    #[inline]
1086    fn max(self) -> Option<Self::Item>
1087    where
1088        Self: Sized,
1089        Self::Item: Ord,
1090    {
1091        match self {
1092            Self::I(i) => i.max(),
1093            Self::J(j) => j.max(),
1094        }
1095    }
1096
1097    #[inline]
1098    fn min(self) -> Option<Self::Item>
1099    where
1100        Self: Sized,
1101        Self::Item: Ord,
1102    {
1103        match self {
1104            Self::I(i) => i.min(),
1105            Self::J(j) => j.min(),
1106        }
1107    }
1108
1109    #[inline]
1110    fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>
1111    where
1112        B: Ord,
1113        Self: Sized,
1114        F: FnMut(&Self::Item) -> B,
1115    {
1116        match self {
1117            Self::I(i) => i.max_by_key(f),
1118            Self::J(j) => j.max_by_key(f),
1119        }
1120    }
1121
1122    #[inline]
1123    fn max_by<F>(self, compare: F) -> Option<Self::Item>
1124    where
1125        Self: Sized,
1126        F: FnMut(&Self::Item, &Self::Item) -> core::cmp::Ordering,
1127    {
1128        match self {
1129            Self::I(i) => i.max_by(compare),
1130            Self::J(j) => j.max_by(compare),
1131        }
1132    }
1133
1134    #[inline]
1135    fn min_by_key<B, F>(self, f: F) -> Option<Self::Item>
1136    where
1137        B: Ord,
1138        Self: Sized,
1139        F: FnMut(&Self::Item) -> B,
1140    {
1141        match self {
1142            Self::I(i) => i.min_by_key(f),
1143            Self::J(j) => j.min_by_key(f),
1144        }
1145    }
1146
1147    #[inline]
1148    fn min_by<F>(self, compare: F) -> Option<Self::Item>
1149    where
1150        Self: Sized,
1151        F: FnMut(&Self::Item, &Self::Item) -> core::cmp::Ordering,
1152    {
1153        match self {
1154            Self::I(i) => i.min_by(compare),
1155            Self::J(j) => j.min_by(compare),
1156        }
1157    }
1158
1159    #[inline]
1160    fn sum<S>(self) -> S
1161    where
1162        Self: Sized,
1163        S: core::iter::Sum<Self::Item>,
1164    {
1165        match self {
1166            Self::I(i) => i.sum(),
1167            Self::J(j) => j.sum(),
1168        }
1169    }
1170
1171    #[inline]
1172    fn product<P>(self) -> P
1173    where
1174        Self: Sized,
1175        P: core::iter::Product<Self::Item>,
1176    {
1177        match self {
1178            Self::I(i) => i.product(),
1179            Self::J(j) => j.product(),
1180        }
1181    }
1182
1183    #[inline]
1184    fn cmp<K>(self, other: K) -> core::cmp::Ordering
1185    where
1186        K: IntoIterator<Item = Self::Item>,
1187        Self::Item: core::cmp::Ord,
1188        Self: Sized,
1189    {
1190        match self {
1191            Self::I(i) => i.cmp(other),
1192            Self::J(j) => j.cmp(other),
1193        }
1194    }
1195
1196    #[inline]
1197    fn partial_cmp<K>(self, other: K) -> Option<core::cmp::Ordering>
1198    where
1199        K: IntoIterator,
1200        Self::Item: PartialOrd<<K as IntoIterator>::Item>,
1201        Self: Sized,
1202    {
1203        match self {
1204            Self::I(i) => i.partial_cmp(other),
1205            Self::J(j) => j.partial_cmp(other),
1206        }
1207    }
1208
1209    #[inline]
1210    fn eq<K>(self, other: K) -> bool
1211    where
1212        K: IntoIterator,
1213        Self::Item: PartialEq<<K as IntoIterator>::Item>,
1214        Self: Sized,
1215    {
1216        match self {
1217            Self::I(i) => i.eq(other),
1218            Self::J(j) => j.eq(other),
1219        }
1220    }
1221
1222    #[inline]
1223    fn ne<K>(self, other: K) -> bool
1224    where
1225        K: IntoIterator,
1226        Self::Item: PartialEq<<K as IntoIterator>::Item>,
1227        Self: Sized,
1228    {
1229        match self {
1230            Self::I(i) => i.ne(other),
1231            Self::J(j) => j.ne(other),
1232        }
1233    }
1234
1235    #[inline]
1236    fn lt<K>(self, other: K) -> bool
1237    where
1238        K: IntoIterator,
1239        Self::Item: PartialOrd<<K as IntoIterator>::Item>,
1240        Self: Sized,
1241    {
1242        match self {
1243            Self::I(i) => i.lt(other),
1244            Self::J(j) => j.lt(other),
1245        }
1246    }
1247
1248    #[inline]
1249    fn le<K>(self, other: K) -> bool
1250    where
1251        K: IntoIterator,
1252        Self::Item: PartialOrd<<K as IntoIterator>::Item>,
1253        Self: Sized,
1254    {
1255        match self {
1256            Self::I(i) => i.le(other),
1257            Self::J(j) => j.le(other),
1258        }
1259    }
1260
1261    #[inline]
1262    fn gt<K>(self, other: K) -> bool
1263    where
1264        K: IntoIterator,
1265        Self::Item: PartialOrd<<K as IntoIterator>::Item>,
1266        Self: Sized,
1267    {
1268        match self {
1269            Self::I(i) => i.gt(other),
1270            Self::J(j) => j.gt(other),
1271        }
1272    }
1273
1274    #[inline]
1275    fn ge<K>(self, other: K) -> bool
1276    where
1277        K: IntoIterator,
1278        Self::Item: PartialOrd<<K as IntoIterator>::Item>,
1279        Self: Sized,
1280    {
1281        match self {
1282            Self::I(i) => i.ge(other),
1283            Self::J(j) => j.ge(other),
1284        }
1285    }
1286}
1287
1288impl<I: DoubleEndedIterator, J: DoubleEndedIterator<Item = I::Item>> DoubleEndedIterator
1289    for EitherIterator<I, J>
1290{
1291    #[inline]
1292    fn next_back(&mut self) -> Option<Self::Item> {
1293        match self {
1294            Self::I(i) => i.next_back(),
1295            Self::J(j) => j.next_back(),
1296        }
1297    }
1298}
1299
1300impl<I: ExactSizeIterator, J: ExactSizeIterator<Item = I::Item>> ExactSizeIterator
1301    for EitherIterator<I, J>
1302{
1303}
1304
1305impl<I: core::iter::FusedIterator, J: core::iter::FusedIterator<Item = I::Item>>
1306    core::iter::FusedIterator for EitherIterator<I, J>
1307{
1308}