1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use core::fmt::Debug;
use core::fmt::Formatter;
use core::hash::Hash;
use core::mem::replace;
use core::ops::Deref;
use core::slice::from_ref;
use serde;
use serde::Deserialize;
use serde::Serialize;
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(untagged)]
pub enum OneOrMany<T> {
One(T),
Many(Vec<T>),
}
impl<T> OneOrMany<T> {
pub fn len(&self) -> usize {
match self {
Self::One(_) => 1,
Self::Many(inner) => inner.len(),
}
}
pub fn is_empty(&self) -> bool {
match self {
Self::One(_) => false,
Self::Many(inner) => inner.is_empty(),
}
}
pub fn get(&self, index: usize) -> Option<&T> {
match self {
Self::One(inner) if index == 0 => Some(inner),
Self::One(_) => None,
Self::Many(inner) => inner.get(index),
}
}
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
match self {
Self::One(ref mut inner) if index == 0 => Some(inner),
Self::One(_) => None,
Self::Many(inner) => inner.get_mut(index),
}
}
pub fn contains(&self, value: &T) -> bool
where
T: PartialEq<T>,
{
match self {
Self::One(inner) => inner == value,
Self::Many(inner) => inner.contains(value),
}
}
pub fn push(&mut self, value: T) {
match self {
Self::One(_) => match replace(self, Self::Many(Vec::new())) {
Self::One(inner) => *self = Self::Many(vec![inner, value]),
Self::Many(_) => unreachable!(),
},
Self::Many(ref mut inner) => {
if inner.is_empty() {
*self = Self::One(value);
} else {
inner.push(value);
}
}
}
}
pub fn iter(&self) -> impl Iterator<Item = &T> + '_ {
OneOrManyIter::new(self)
}
pub fn as_slice(&self) -> &[T] {
&*self
}
pub fn into_vec(self) -> Vec<T> {
match self {
Self::One(inner) => vec![inner],
Self::Many(inner) => inner,
}
}
}
impl<T> Debug for OneOrMany<T>
where
T: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
Self::One(inner) => Debug::fmt(inner, f),
Self::Many(inner) => Debug::fmt(inner, f),
}
}
}
impl<T> Deref for OneOrMany<T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
match self {
Self::One(inner) => from_ref(inner),
Self::Many(inner) => &*inner,
}
}
}
impl<T> AsRef<[T]> for OneOrMany<T> {
fn as_ref(&self) -> &[T] {
&*self
}
}
impl<T> Default for OneOrMany<T> {
fn default() -> Self {
Self::Many(Vec::new())
}
}
impl<T> From<T> for OneOrMany<T> {
fn from(other: T) -> Self {
Self::One(other)
}
}
impl<T> From<Vec<T>> for OneOrMany<T> {
fn from(mut other: Vec<T>) -> Self {
if other.len() == 1 {
Self::One(other.pop().expect("infallible"))
} else {
Self::Many(other)
}
}
}
impl<T> From<OneOrMany<T>> for Vec<T> {
fn from(other: OneOrMany<T>) -> Self {
other.into_vec()
}
}
impl<T> FromIterator<T> for OneOrMany<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut iter = iter.into_iter();
let size_hint = iter.size_hint();
if size_hint.1.is_some() && (1, Some(1)) >= size_hint {
let mut this = iter.next().map(Self::One).unwrap_or_else(|| Self::Many(Vec::new()));
for next in iter.by_ref() {
this.push(next);
}
this
} else {
iter.into_iter().collect::<Vec<T>>().into()
}
}
}
struct OneOrManyIter<'a, T> {
inner: &'a OneOrMany<T>,
index: usize,
}
impl<'a, T> OneOrManyIter<'a, T> {
fn new(inner: &'a OneOrMany<T>) -> Self {
Self { inner, index: 0 }
}
}
impl<'a, T> Iterator for OneOrManyIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.index += 1;
self.inner.get(self.index - 1)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_iterator_empty() {
let empty_vec = Vec::<u32>::new();
assert_eq!(OneOrMany::from_iter(empty_vec.clone()), OneOrMany::Many(empty_vec));
}
#[test]
fn from_iterator_single() {
let single_item = [1];
assert_eq!(OneOrMany::from_iter(single_item), OneOrMany::One(1));
}
#[test]
fn from_iterator_many() {
let letters = ["a", "b", "c", "d"];
assert_eq!(OneOrMany::from_iter(letters), OneOrMany::Many(vec!["a", "b", "c", "d"]));
}
#[test]
fn from_iterator_iter() {
let none = OneOrMany::Many(Vec::<u32>::new());
assert_eq!(OneOrMany::from_iter(none.iter()), OneOrMany::Many(Vec::<&u32>::new()));
let one = OneOrMany::One(42);
assert_eq!(OneOrMany::from_iter(one.iter()), OneOrMany::One(&42));
let two = OneOrMany::Many(vec![0, 1]);
assert_eq!(OneOrMany::from_iter(two.iter()), OneOrMany::Many(vec![&0, &1]));
}
#[test]
fn push_from_zero_elements() {
let mut collection = OneOrMany::Many(Vec::<u32>::new());
collection.push(42);
assert_eq!(collection, OneOrMany::One(42));
}
#[test]
fn push_one_element() {
let mut collection = OneOrMany::One(42);
collection.push(42);
assert_eq!(collection, OneOrMany::Many(vec![42, 42]));
}
#[test]
fn push_many_elements() {
let v: Vec<i32> = (0..42).collect();
let mut collection = OneOrMany::Many(v);
collection.push(42);
assert_eq!(collection, OneOrMany::Many((0..=42).collect()));
}
}