1use error::{ErrorKind, Result};
2
3/// A trait for stopping serialization and deserialization when a certain limit has been reached.
4pub trait SizeLimit {
5 /// Tells the SizeLimit that a certain number of bytes has been
6 /// read or written. Returns Err if the limit has been exceeded.
7 fn add(&mut self, n: u64) -> Result<()>;
8 /// Returns the hard limit (if one exists)
9 fn limit(&self) -> Option<u64>;
10}
11
12/// A SizeLimit that restricts serialized or deserialized messages from
13/// exceeding a certain byte length.
14#[derive(Copy, Clone)]
15pub struct Bounded(pub u64);
16
17/// A SizeLimit without a limit!
18/// Use this if you don't care about the size of encoded or decoded messages.
19#[derive(Copy, Clone)]
20pub struct Infinite;
21
22impl SizeLimit for Bounded {
23 #[inline(always)]
24 fn add(&mut self, n: u64) -> Result<()> {
25 if self.0 >= n {
26 self.0 -= n;
27 Ok(())
28 } else {
29 Err(Box::new(ErrorKind::SizeLimit))
30 }
31 }
32
33 #[inline(always)]
34 fn limit(&self) -> Option<u64> {
35 Some(self.0)
36 }
37}
38
39impl SizeLimit for Infinite {
40 #[inline(always)]
41 fn add(&mut self, _: u64) -> Result<()> {
42 Ok(())
43 }
44
45 #[inline(always)]
46 fn limit(&self) -> Option<u64> {
47 None
48 }
49}
50