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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use super::DEF_CAPACITY;
use std::fmt;
use tokio::io;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SizeLimitReached(usize);
impl SizeLimitReached {
pub fn is_reached(e: &io::Error) -> bool {
let dyn_err = match e.get_ref() {
Some(e) => e,
None => return false
};
dyn_err.is::<Self>()
}
pub fn downcast(e: &io::Error) -> Option<Self> {
e.get_ref()?
.downcast_ref()
.map(Clone::clone)
}
}
impl fmt::Display for SizeLimitReached {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl std::error::Error for SizeLimitReached {}
#[derive(Debug, PartialEq, Eq)]
pub struct SizeLimit {
read: usize,
max: usize
}
impl SizeLimit {
#[inline]
pub fn new(max: usize) -> Self {
assert!(max > 0, "max needs to bigger than zero");
Self { read: 0, max }
}
pub fn empty() -> Self {
Self { read: 0, max: 0 }
}
pub fn new_capacity(&self) -> usize {
if self.max == 0 {
DEF_CAPACITY
} else if self.max <= self.read {
0
} else {
(self.max - self.read).min(DEF_CAPACITY)
}
}
#[cfg(any(feature = "hyper_body", test))]
pub fn surpassed(&self) -> bool {
self.max > 0 && self.read > self.max
}
pub fn add_read_res(&mut self, read: usize) -> io::Result<()> {
self.read += read;
if self.max > 0 && self.read > self.max {
Err(io::Error::new(
io::ErrorKind::Other,
SizeLimitReached(self.max)
))
} else {
Ok(())
}
}
#[cfg(any(feature = "hyper_body", test))]
pub fn set(&mut self, max: usize) {
assert!(max > 0, "max needs to bigger than 0");
assert!(self.read <= max, "max needs to smaller than already read size");
self.max = max;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn some_tests() {
let mut limit = SizeLimit::empty();
assert_eq!(limit.new_capacity(), DEF_CAPACITY);
limit.set(2);
assert_eq!(SizeLimit::new(2), limit);
assert_eq!(limit.new_capacity(), 2);
assert!(limit.add_read_res(2).is_ok());
assert!(!limit.surpassed());
assert!(limit.add_read_res(1).is_err());
assert!(limit.surpassed());
assert_eq!(limit.new_capacity(), 0);
}
}