Skip to content

Commit ab8e3c0

Browse files
authored
Clarify BufMut allocation guarantees (#501)
1 parent f34dc5c commit ab8e3c0

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

src/buf/buf_mut.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ pub unsafe trait BufMut {
3333
/// This value is greater than or equal to the length of the slice returned
3434
/// by `chunk_mut()`.
3535
///
36+
/// Writing to a `BufMut` may involve allocating more memory on the fly.
37+
/// Implementations may fail before reaching the number of bytes indicated
38+
/// by this method if they encounter an allocation failure.
39+
///
3640
/// # Examples
3741
///
3842
/// ```
@@ -158,6 +162,9 @@ pub unsafe trait BufMut {
158162
/// `chunk_mut()` returning an empty slice implies that `remaining_mut()` will
159163
/// return 0 and `remaining_mut()` returning 0 implies that `chunk_mut()` will
160164
/// return an empty slice.
165+
///
166+
/// This function may trigger an out-of-memory abort if it tries to allocate
167+
/// memory and fails to do so.
161168
// The `chunk_mut` method was previously called `bytes_mut`. This alias makes the
162169
// rename more easily discoverable.
163170
#[cfg_attr(docsrs, doc(alias = "bytes_mut"))]
@@ -1025,7 +1032,8 @@ unsafe impl BufMut for &mut [u8] {
10251032
unsafe impl BufMut for Vec<u8> {
10261033
#[inline]
10271034
fn remaining_mut(&self) -> usize {
1028-
usize::MAX - self.len()
1035+
// A vector can never have more than isize::MAX bytes
1036+
core::isize::MAX as usize - self.len()
10291037
}
10301038

10311039
#[inline]

tests/test_buf_mut.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,15 @@ use core::usize;
99
fn test_vec_as_mut_buf() {
1010
let mut buf = Vec::with_capacity(64);
1111

12-
assert_eq!(buf.remaining_mut(), usize::MAX);
12+
assert_eq!(buf.remaining_mut(), isize::MAX as usize);
1313

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

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

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

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

2323
for _ in 0..16 {

0 commit comments

Comments
 (0)