empty_collections/
vector.rs

1//! Empty vectors. An icy wind blows across the wintering fields of Manitoba.
2
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6use std::marker::PhantomData;
7
8use crate::Empty;
9
10/// A vector that is guaranteed to be empty.
11///
12/// Naturally, the following operations are impossible with [`EVec`]:
13///
14/// - `append`
15/// - `insert`
16/// - `push`
17/// - `remove`
18///
19/// And many others have been elided for being pointless (like `drain` and `sort`).
20#[cfg_attr(
21    feature = "serde",
22    derive(Deserialize, Serialize),
23    serde(bound(
24        serialize = "T: Serialize + Clone",
25        deserialize = "T: Deserialize<'de>"
26    )),
27    serde(into = "Vec<T>", try_from = "Vec<T>")
28)]
29#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
30pub struct EVec<T> {
31    // Spooky. Don't look behind you.
32    vector: PhantomData<T>,
33}
34
35impl<T> EVec<T> {
36    /// Go ahead, see if it's in there.
37    pub const fn contains(&self, _: &T) -> bool {
38        false
39    }
40
41    /// Attempt to convert a possibly non-empty `Vec` into one that is
42    /// guaranteed to be empty.
43    pub fn from_vec(vec: Vec<T>) -> Option<EVec<T>> {
44        vec.is_empty().then(|| EVec::new())
45    }
46
47    /// This may be the best function I've ever written. Go on, guess the return
48    /// value.
49    pub const fn is_empty(&self) -> bool {
50        true
51    }
52
53    /// Wow, it's even an [`Iterator`]?
54    pub fn iter(&self) -> Empty<&T> {
55        Empty::new()
56    }
57
58    /// No, sorry, _this_ is the best function I've ever written.
59    pub const fn len(&self) -> usize {
60        0
61    }
62
63    /// Think of the possibilities!
64    pub fn new() -> EVec<T> {
65        EVec {
66            vector: PhantomData,
67        }
68    }
69}
70
71impl<T> From<EVec<T>> for Vec<T> {
72    fn from(_: EVec<T>) -> Self {
73        Vec::new()
74    }
75}
76
77impl<T> std::fmt::Debug for EVec<T> {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        let v: [usize; 0] = [];
80        v.fmt(f)
81    }
82}
83
84impl<T> TryFrom<Vec<T>> for EVec<T> {
85    type Error = &'static str;
86
87    fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
88        if value.is_empty() {
89            Ok(EVec::new())
90        } else {
91            Err("Cannot convert a non-empty vector into an empty one")
92        }
93    }
94}
95
96impl<T> IntoIterator for EVec<T> {
97    type Item = T;
98
99    type IntoIter = Empty<T>;
100
101    fn into_iter(self) -> Self::IntoIter {
102        Empty::new()
103    }
104}
105
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[test]
112    fn eq() {
113        let a: EVec<usize> = EVec::new();
114        let b = EVec::new();
115        assert_eq!(a, b);
116    }
117
118    #[test]
119    fn ord() {
120        let a: EVec<usize> = EVec::new();
121        let b = EVec::new();
122        assert!(!(a < b));
123        assert!(!(a > b));
124    }
125
126    #[cfg(feature = "serde")]
127    mod serialize {
128        use crate::EVec;
129
130        #[test]
131        fn roundtrip() {
132            let v: EVec<usize> = EVec::new();
133            let j = serde_json::to_string(&v).unwrap();
134            let r = serde_json::from_str(&j).unwrap();
135            assert_eq!(v, r);
136        }
137    }
138}