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
#[derive(Clone, Debug)]
pub struct NonEmpty<T>(T, Vec<T>);
impl<T> NonEmpty<T> {
pub fn new(e: T) -> Self {
Self::singleton(e)
}
pub fn singleton(e: T) -> Self {
NonEmpty(e, Vec::new())
}
pub const fn is_empty(&self) -> bool {
false
}
pub const fn first(&self) -> &T {
&self.0
}
pub fn push(&mut self, e: T) {
self.1.push(e)
}
pub fn pop(&mut self) -> Option<T> {
self.1.pop()
}
pub fn len(&self) -> usize {
self.1.len() + 1
}
pub fn last(&self) -> &T {
match self.1.last() {
None => &self.0,
Some(e) => e,
}
}
pub fn last_mut(&mut self) -> &mut T {
match self.1.last_mut() {
None => &mut self.0,
Some(e) => e,
}
}
pub fn get(&self, index: usize) -> Option<&T> {
if index == 0 {
Some(&self.0)
} else {
self.1.get(index - 1)
}
}
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
if index == 0 {
Some(&mut self.0)
} else {
self.1.get_mut(index - 1)
}
}
pub fn truncate(&mut self, len: usize) {
assert!(len >= 1);
self.1.truncate(len - 1);
}
pub fn iter<'a>(&'a self) -> impl Iterator + 'a {
std::iter::once(&self.0).chain(self.1.iter())
}
}
impl<T> Into<Vec<T>> for NonEmpty<T> {
fn into(self) -> Vec<T> {
std::iter::once(self.0).chain(self.1).collect()
}
}