1use error::{ErrorKind, Result};
23/// 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.
7fn add(&mut self, n: u64) -> Result<()>;
8/// Returns the hard limit (if one exists)
9fn limit(&self) -> Option<u64>;
10}
1112/// A SizeLimit that restricts serialized or deserialized messages from
13/// exceeding a certain byte length.
14#[derive(Copy, Clone)]
15pub struct Bounded(pub u64);
1617/// 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;
2122impl SizeLimit for Bounded {
23#[inline(always)]
24fn add(&mut self, n: u64) -> Result<()> {
25if self.0 >= n {
26self.0 -= n;
27Ok(())
28 } else {
29Err(Box::new(ErrorKind::SizeLimit))
30 }
31 }
3233#[inline(always)]
34fn limit(&self) -> Option<u64> {
35Some(self.0)
36 }
37}
3839impl SizeLimit for Infinite {
40#[inline(always)]
41fn add(&mut self, _: u64) -> Result<()> {
42Ok(())
43 }
4445#[inline(always)]
46fn limit(&self) -> Option<u64> {
47None
48}
49}