channels_io/buf/
take.rs

1use core::cmp::min;
2
3use crate::buf::Buf;
4
5/// The `take` adapter.
6///
7/// See: [`Buf::take`].
8#[derive(Debug, Clone, Copy)]
9pub struct Take<T> {
10	inner: T,
11	left: usize,
12}
13
14impl<T> Take<T> {
15	pub(super) fn new(inner: T, left: usize) -> Self {
16		Self { inner, left }
17	}
18
19	/// Get the number of bytes logically left in the buffer.
20	///
21	/// This method is not the same as [`Buf::remaining()`]. It returns the maximum number
22	/// of bytes the underlying buffer is allowed to have left. The returned value might be
23	/// greater than the actual amount of bytes the underlying buffer has left.
24	#[inline]
25	pub fn left(&self) -> usize {
26		self.left
27	}
28
29	/// Set the maximum amount of bytes the underlying buffer is allowed to have.
30	#[inline]
31	pub fn set_left(&mut self, left: usize) {
32		self.left = left;
33	}
34
35	/// Get a reference to the underlying buffer.
36	#[inline]
37	pub fn get(&self) -> &T {
38		&self.inner
39	}
40
41	/// Get a mutable reference to the underlying buffer.
42	#[inline]
43	pub fn get_mut(&mut self) -> &mut T {
44		&mut self.inner
45	}
46
47	/// Destruct the adapter and get back the underlying buffer.
48	#[inline]
49	pub fn into_inner(self) -> T {
50		self.inner
51	}
52}
53
54impl<T: Buf> Buf for Take<T> {
55	fn remaining(&self) -> usize {
56		min(self.inner.remaining(), self.left)
57	}
58
59	fn chunk(&self) -> &[u8] {
60		let s = self.inner.chunk();
61
62		if s.len() > self.left {
63			&s[..self.left]
64		} else {
65			s
66		}
67	}
68
69	fn advance(&mut self, n: usize) {
70		assert!(
71			n <= self.left,
72			"n must not be greater than the amount of bytes left"
73		);
74
75		self.left -= n;
76	}
77}