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
#![no_std]
#[cfg(feature = "alloc")]
extern crate alloc;
pub trait Collection<T>:
AsRef<[T]> + AsMut<[T]> + Default + Length + Truncate + TryExtend<T> + TryPush<T>
{
}
pub trait Length {
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub trait Truncate {
fn truncate(&mut self, len: usize);
}
pub trait TryExtend<A> {
type Error;
fn try_extend<T>(&mut self, iter: &mut T) -> Result<(), Self::Error>
where
T: Iterator<Item = A>;
fn try_extend_from_slice(&mut self, slice: &[A]) -> Result<(), Self::Error>
where
A: Clone,
{
self.try_extend(&mut slice.iter().cloned())
}
}
pub trait TryFromIterator<A>: Sized {
type Error;
fn try_from_iter<T>(iter: &mut T) -> Result<Self, Self::Error>
where
T: Iterator<Item = A>;
}
impl<A, C: Default + TryExtend<A>> TryFromIterator<A> for C {
type Error = <Self as TryExtend<A>>::Error;
fn try_from_iter<T>(iter: &mut T) -> Result<Self, Self::Error>
where
T: Iterator<Item = A>,
{
let mut collection = Self::default();
collection.try_extend(iter)?;
Ok(collection)
}
}
pub trait TryPush<T> {
fn try_push(&mut self, item: T) -> Result<(), T>;
}
pub trait TryCollect<A> {
fn try_collect<B>(&mut self) -> Result<B, B::Error>
where
B: TryFromIterator<A>;
}
impl<A, T> TryCollect<A> for T
where
T: Iterator<Item = A>,
{
fn try_collect<B>(&mut self) -> Result<B, B::Error>
where
B: TryFromIterator<A>,
{
B::try_from_iter(self)
}
}
#[cfg(feature = "alloc")]
mod vec_impls {
use super::{Length, Truncate, TryExtend};
use alloc::vec::Vec;
use core::convert::Infallible;
impl<T> Length for Vec<T> {
fn len(&self) -> usize {
Vec::len(self)
}
}
impl<T> Truncate for Vec<T> {
fn truncate(&mut self, len: usize) {
Vec::truncate(self, len);
}
}
impl<A> TryExtend<A> for Vec<A> {
type Error = Infallible;
fn try_extend<T: IntoIterator<Item = A>>(&mut self, iter: T) -> Result<(), Infallible> {
Vec::extend(self, iter);
Ok(())
}
}
}