Skip to content

Commit

Permalink
Clarify BufMut allocation guarantees (#501)
Browse files Browse the repository at this point in the history
  • Loading branch information
Darksonn authored Aug 7, 2021
1 parent f34dc5c commit ab8e3c0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
10 changes: 9 additions & 1 deletion src/buf/buf_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ pub unsafe trait BufMut {
/// This value is greater than or equal to the length of the slice returned
/// by `chunk_mut()`.
///
/// Writing to a `BufMut` may involve allocating more memory on the fly.
/// Implementations may fail before reaching the number of bytes indicated
/// by this method if they encounter an allocation failure.
///
/// # Examples
///
/// ```
Expand Down Expand Up @@ -158,6 +162,9 @@ pub unsafe trait BufMut {
/// `chunk_mut()` returning an empty slice implies that `remaining_mut()` will
/// return 0 and `remaining_mut()` returning 0 implies that `chunk_mut()` will
/// return an empty slice.
///
/// This function may trigger an out-of-memory abort if it tries to allocate
/// memory and fails to do so.
// The `chunk_mut` method was previously called `bytes_mut`. This alias makes the
// rename more easily discoverable.
#[cfg_attr(docsrs, doc(alias = "bytes_mut"))]
Expand Down Expand Up @@ -1025,7 +1032,8 @@ unsafe impl BufMut for &mut [u8] {
unsafe impl BufMut for Vec<u8> {
#[inline]
fn remaining_mut(&self) -> usize {
usize::MAX - self.len()
// A vector can never have more than isize::MAX bytes
core::isize::MAX as usize - self.len()
}

#[inline]
Expand Down
4 changes: 2 additions & 2 deletions tests/test_buf_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ use core::usize;
fn test_vec_as_mut_buf() {
let mut buf = Vec::with_capacity(64);

assert_eq!(buf.remaining_mut(), usize::MAX);
assert_eq!(buf.remaining_mut(), isize::MAX as usize);

assert!(buf.chunk_mut().len() >= 64);

buf.put(&b"zomg"[..]);

assert_eq!(&buf, b"zomg");

assert_eq!(buf.remaining_mut(), usize::MAX - 4);
assert_eq!(buf.remaining_mut(), isize::MAX as usize - 4);
assert_eq!(buf.capacity(), 64);

for _ in 0..16 {
Expand Down

0 comments on commit ab8e3c0

Please sign in to comment.