Skip to content

Commit 4522ab3

Browse files
Darksonnlelongg
authored andcommitted
Clarify BufMut allocation guarantees (tokio-rs#501)
1 parent 4fd879b commit 4522ab3

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
@@ -34,6 +34,10 @@ pub unsafe trait BufMut {
3434
/// This value is greater than or equal to the length of the slice returned
3535
/// by `chunk_mut()`.
3636
///
37+
/// Writing to a `BufMut` may involve allocating more memory on the fly.
38+
/// Implementations may fail before reaching the number of bytes indicated
39+
/// by this method if they encounter an allocation failure.
40+
///
3741
/// # Examples
3842
///
3943
/// ```
@@ -159,6 +163,9 @@ pub unsafe trait BufMut {
159163
/// `chunk_mut()` returning an empty slice implies that `remaining_mut()` will
160164
/// return 0 and `remaining_mut()` returning 0 implies that `chunk_mut()` will
161165
/// return an empty slice.
166+
///
167+
/// This function may trigger an out-of-memory abort if it tries to allocate
168+
/// memory and fails to do so.
162169
// The `chunk_mut` method was previously called `bytes_mut`. This alias makes the
163170
// rename more easily discoverable.
164171
#[cfg_attr(docsrs, doc(alias = "bytes_mut"))]
@@ -1028,7 +1035,8 @@ unsafe impl BufMut for &mut [u8] {
10281035
unsafe impl BufMut for Vec<u8> {
10291036
#[inline]
10301037
fn remaining_mut(&self) -> usize {
1031-
usize::MAX - self.len()
1038+
// A vector can never have more than isize::MAX bytes
1039+
core::isize::MAX as usize - self.len()
10321040
}
10331041

10341042
#[inline]

tests/test_buf_mut.rs

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

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

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

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

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

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

2424
for _ in 0..16 {

0 commit comments

Comments
 (0)