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
#![feature(try_reserve)]
use std::fmt::{Debug, Display, Formatter};
use std::collections::TryReserveError;
use std::error::Error;
#[cfg(test)]
mod testing;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum WcsErrorType{
CapacityOverflow,
AllocError
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct WcsError{
error_type : WcsErrorType,
source: TryReserveError,
}
impl WcsError{
pub fn error_type(&self) -> &WcsErrorType{ &self.error_type }
pub fn source(&self) -> &TryReserveError{ &self.source }
}
impl Error for WcsError{
}
impl Display for WcsError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.error_type, f)
}
}
pub fn vec_with_capacity_safe<T>(capacity : usize) -> Result<Vec<T>, WcsError>{
let mut vec = Vec::new();
match vec.try_reserve_exact(capacity){
Ok(_) => Ok(vec),
Err(e) =>
match e{
TryReserveError::AllocError{ .. } =>{
Err(WcsError{ error_type : WcsErrorType::AllocError, source : e })
},
TryReserveError::CapacityOverflow =>{
Err(WcsError{ error_type : WcsErrorType::CapacityOverflow, source : e })
}
}
}
}