Skip to main content

float_pigment_consistent_bincode/config/
limit.rs

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