1 use crate::BufMut;
2 
3 use core::{cmp, mem::MaybeUninit};
4 
5 /// A `BufMut` adapter which limits the amount of bytes that can be written
6 /// to an underlying buffer.
7 #[derive(Debug)]
8 pub struct Limit<T> {
9     inner: T,
10     limit: usize,
11 }
12 
new<T>(inner: T, limit: usize) -> Limit<T>13 pub(super) fn new<T>(inner: T, limit: usize) -> Limit<T> {
14     Limit { inner, limit }
15 }
16 
17 impl<T> Limit<T> {
18     /// Consumes this `Limit`, returning the underlying value.
into_inner(self) -> T19     pub fn into_inner(self) -> T {
20         self.inner
21     }
22 
23     /// Gets a reference to the underlying `BufMut`.
24     ///
25     /// It is inadvisable to directly write to the underlying `BufMut`.
get_ref(&self) -> &T26     pub fn get_ref(&self) -> &T {
27         &self.inner
28     }
29 
30     /// Gets a mutable reference to the underlying `BufMut`.
31     ///
32     /// It is inadvisable to directly write to the underlying `BufMut`.
get_mut(&mut self) -> &mut T33     pub fn get_mut(&mut self) -> &mut T {
34         &mut self.inner
35     }
36 
37     /// Returns the maximum number of bytes that can be written
38     ///
39     /// # Note
40     ///
41     /// If the inner `BufMut` has fewer bytes than indicated by this method then
42     /// that is the actual number of available bytes.
limit(&self) -> usize43     pub fn limit(&self) -> usize {
44         self.limit
45     }
46 
47     /// Sets the maximum number of bytes that can be written.
48     ///
49     /// # Note
50     ///
51     /// If the inner `BufMut` has fewer bytes than `lim` then that is the actual
52     /// number of available bytes.
set_limit(&mut self, lim: usize)53     pub fn set_limit(&mut self, lim: usize) {
54         self.limit = lim
55     }
56 }
57 
58 impl<T: BufMut> BufMut for Limit<T> {
remaining_mut(&self) -> usize59     fn remaining_mut(&self) -> usize {
60         cmp::min(self.inner.remaining_mut(), self.limit)
61     }
62 
bytes_mut(&mut self) -> &mut [MaybeUninit<u8>]63     fn bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
64         let bytes = self.inner.bytes_mut();
65         let end = cmp::min(bytes.len(), self.limit);
66         &mut bytes[..end]
67     }
68 
advance_mut(&mut self, cnt: usize)69     unsafe fn advance_mut(&mut self, cnt: usize) {
70         assert!(cnt <= self.limit);
71         self.inner.advance_mut(cnt);
72         self.limit -= cnt;
73     }
74 }
75