aboutsummaryrefslogtreecommitdiff
path: root/src/buf/limit.rs
diff options
context:
space:
mode:
authorGravatar Carl Lerche <me@carllerche.com> 2020-10-16 15:16:23 -0700
committerGravatar GitHub <noreply@github.com> 2020-10-16 15:16:23 -0700
commit94c543f74b111e894d16faa43e4ad361b97ee87d (patch)
tree8cad5f70cc986e8b1952dc52436933e9a5a34f05 /src/buf/limit.rs
parent447530b8a6f97fc6864b39d29b24efb4ac9202d3 (diff)
downloadbytes-94c543f74b111e894d16faa43e4ad361b97ee87d.tar.gz
bytes-94c543f74b111e894d16faa43e4ad361b97ee87d.tar.zst
bytes-94c543f74b111e894d16faa43e4ad361b97ee87d.zip
remove ext traits (#431)
Diffstat (limited to 'src/buf/limit.rs')
-rw-r--r--src/buf/limit.rs74
1 files changed, 74 insertions, 0 deletions
diff --git a/src/buf/limit.rs b/src/buf/limit.rs
new file mode 100644
index 0000000..a36ecee
--- /dev/null
+++ b/src/buf/limit.rs
@@ -0,0 +1,74 @@
+use crate::BufMut;
+
+use core::{cmp, mem::MaybeUninit};
+
+/// A `BufMut` adapter which limits the amount of bytes that can be written
+/// to an underlying buffer.
+#[derive(Debug)]
+pub struct Limit<T> {
+ inner: T,
+ limit: usize,
+}
+
+pub(super) fn new<T>(inner: T, limit: usize) -> Limit<T> {
+ Limit { inner, limit }
+}
+
+impl<T> Limit<T> {
+ /// Consumes this `Limit`, returning the underlying value.
+ pub fn into_inner(self) -> T {
+ self.inner
+ }
+
+ /// Gets a reference to the underlying `BufMut`.
+ ///
+ /// It is inadvisable to directly write to the underlying `BufMut`.
+ pub fn get_ref(&self) -> &T {
+ &self.inner
+ }
+
+ /// Gets a mutable reference to the underlying `BufMut`.
+ ///
+ /// It is inadvisable to directly write to the underlying `BufMut`.
+ pub fn get_mut(&mut self) -> &mut T {
+ &mut self.inner
+ }
+
+ /// Returns the maximum number of bytes that can be written
+ ///
+ /// # Note
+ ///
+ /// If the inner `BufMut` has fewer bytes than indicated by this method then
+ /// that is the actual number of available bytes.
+ pub fn limit(&self) -> usize {
+ self.limit
+ }
+
+ /// Sets the maximum number of bytes that can be written.
+ ///
+ /// # Note
+ ///
+ /// If the inner `BufMut` has fewer bytes than `lim` then that is the actual
+ /// number of available bytes.
+ pub fn set_limit(&mut self, lim: usize) {
+ self.limit = lim
+ }
+}
+
+impl<T: BufMut> BufMut for Limit<T> {
+ fn remaining_mut(&self) -> usize {
+ cmp::min(self.inner.remaining_mut(), self.limit)
+ }
+
+ fn bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
+ let bytes = self.inner.bytes_mut();
+ let end = cmp::min(bytes.len(), self.limit);
+ &mut bytes[..end]
+ }
+
+ unsafe fn advance_mut(&mut self, cnt: usize) {
+ assert!(cnt <= self.limit);
+ self.inner.advance_mut(cnt);
+ self.limit -= cnt;
+ }
+}