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
use serde::{Deserialize, Serialize};
use std::{
error,
fmt::{self, Debug},
ops,
};
#[derive(Clone, PartialEq, Eq, Serialize, Hash, Deserialize, Default)]
pub struct Vec1<T>(Vec<T>)
where
T: Debug;
#[derive(Debug)]
pub struct EmptyVec;
impl error::Error for EmptyVec {}
impl fmt::Display for EmptyVec {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "Vec1 must as least contain one item, zero given")
}
}
impl<T> Vec1<T>
where
T: Debug,
{
pub fn new(items: Vec<T>) -> Result<Self, EmptyVec> {
if items.is_empty() {
Err(EmptyVec)
} else {
Ok(Self(items))
}
}
pub fn into_vec(self) -> Vec<T> {
self.0
}
}
impl<T> fmt::Debug for Vec1<T>
where
T: Debug,
{
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{:?}", self.0)
}
}
impl<T> ops::Deref for Vec1<T>
where
T: Debug,
{
type Target = Vec<T>;
fn deref(&self) -> &Self::Target {
&self.0
}
}