Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This type is the counterpart to BufExt::take. It limits how many bytes some `BufMut` can actually be filled with.
- Loading branch information
1 parent
b3f86d8
commit 44fb206
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
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: 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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters