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
use core::hash::Hash;
use core::mem::swap;
pub use alloc::{
alloc::AllocError,
collections::{TryReserveError, VecDeque},
string::String,
vec::Vec,
};
pub use hashbrown::HashMap;
pub fn r2a<T>(r: Result<T, TryReserveError>) -> Result<T, AllocError> {
r.map_err(|_| AllocError)
}
pub fn str_push<T>(s: &mut String, x: char) -> Result<(), AllocError> {
r2a(s.try_reserve(1))?;
s.push(x);
Ok(())
}
pub fn vec_push<T>(v: &mut Vec<T>, x: T) -> Result<(), AllocError> {
r2a(v.try_reserve(1))?;
v.push(x);
Ok(())
}
pub fn vec_shrink_to_fit<T>(v: &mut Vec<T>) -> Result<(), AllocError> {
let mut nv = Vec::new();
r2a(nv.try_reserve(v.len()))?;
while let Some(x) = v.pop() {
nv.push(x);
}
nv.reverse();
swap(v, &mut nv);
Ok(())
}
pub fn deque_push_front<T>(v: &mut VecDeque<T>, x: T) -> Result<(), AllocError> {
r2a(v.try_reserve(1))?;
v.push_front(x);
Ok(())
}
pub fn deque_push_back<T>(v: &mut VecDeque<T>, x: T) -> Result<(), AllocError> {
r2a(v.try_reserve(1))?;
v.push_back(x);
Ok(())
}
pub fn map_insert<K: Eq + Hash, V>(
m: &mut HashMap<K, V>,
k: K,
v: V,
) -> Result<Option<V>, AllocError> {
m.try_reserve(1).map_err(|_| AllocError)?;
Ok(m.insert(k, v))
}