Skip to content

core: Add BorrowedCursor::with_unfilled_buf #142885

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions library/core/src/io/borrowed_buf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,23 @@ impl<'data> From<&'data mut [MaybeUninit<u8>]> for BorrowedBuf<'data> {
}
}

/// Creates a new `BorrowedBuf` from a cursor.
///
/// Use `BorrowedCursor::with_unfilled_buf` instead for a safer alternative.
impl<'data> From<BorrowedCursor<'data>> for BorrowedBuf<'data> {
#[inline]
fn from(mut buf: BorrowedCursor<'data>) -> BorrowedBuf<'data> {
let init = buf.init_mut().len();
BorrowedBuf {
// SAFETY: no initialized byte is ever uninitialized as per
// `BorrowedBuf`'s invariant
buf: unsafe { buf.buf.buf.get_unchecked_mut(buf.buf.filled..) },
filled: 0,
init,
}
}
}

impl<'data> BorrowedBuf<'data> {
/// Returns the total capacity of the buffer.
#[inline]
Expand Down Expand Up @@ -353,4 +370,38 @@ impl<'a> BorrowedCursor<'a> {
}
self.buf.filled += buf.len();
}

/// Runs the given closure with a `BorrowedBuf` containing the unfilled part
/// of the cursor.
///
/// This enables inspecting what was written to the cursor.
///
/// # Panics
///
/// Panics if the `BorrowedBuf` given to the closure is replaced by another
/// one.
pub fn with_unfilled_buf<T>(&mut self, f: impl FnOnce(&mut BorrowedBuf<'_>) -> T) -> T {
let mut buf = BorrowedBuf::from(self.reborrow());
let prev_ptr = buf.buf as *const _;
let res = f(&mut buf);

// Check that the caller didn't replace the `BorrowedBuf`.
// This is necessary for the safety of the code below: if the check wasn't
// there, one could mark some bytes as initialized even though there aren't.
assert!(core::ptr::addr_eq(prev_ptr, buf.buf));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a necessary condition for soundness? If so, we probably have to abort here, not just panic. Can you clarify in comments why it's necessary to check this as well?

(Also if it's a soundness condition it should probably be in a drop guard, so that the closure panicking after replacing the Buf doesn't cause us to unwind past this check).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a necessary condition for soundness? If so, we probably have to abort here, not just panic. Can you clarify in comments why it's necessary to check this as well?

Yes, for the update of filled and init fields. I will change the comments to make it clearer.

I disagree for the abort though. It is not something usually done in std unless necessary, which is not the case here.

(Also if it's a soundness condition it should probably be in a drop guard, so that the closure panicking after replacing the Buf doesn't cause us to unwind past this check).

That's fine if we do, because the code that rely on this invariant would be skipped.


let filled = buf.filled;
let init = buf.init;

// Update `init` and `filled` fields with what was written to the buffer.
// `self.buf.filled` was the starting length of the `BorrowedBuf`.
//
// SAFETY: These amounts of bytes were initialized/filled in the `BorrowedBuf`,
// and therefore they are initialized/filled in the cursor too, because the
// buffer wasn't replaced.
self.buf.init = self.buf.filled + init;
self.buf.filled += filled;

res
}
}
36 changes: 36 additions & 0 deletions library/coretests/tests/io/borrowed_buf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,39 @@ fn cursor_set_init() {
assert_eq!(rbuf.unfilled().uninit_mut().len(), 4);
assert_eq!(unsafe { rbuf.unfilled().as_mut().len() }, 12);
}

#[test]
fn cursor_with_unfilled_buf() {
let buf: &mut [_] = &mut [MaybeUninit::uninit(); 16];
let mut rbuf = BorrowedBuf::from(buf);
let mut cursor = rbuf.unfilled();

cursor.with_unfilled_buf(|buf| {
buf.unfilled().append(&[1, 2, 3]);
assert_eq!(buf.filled(), &[1, 2, 3]);
});

assert_eq!(cursor.init_mut().len(), 0);
assert_eq!(cursor.written(), 3);

cursor.with_unfilled_buf(|buf| {
assert_eq!(buf.capacity(), 13);
assert_eq!(buf.init_len(), 0);

buf.unfilled().ensure_init();
buf.unfilled().advance(4);
});

assert_eq!(cursor.init_mut().len(), 9);
assert_eq!(cursor.written(), 7);

cursor.with_unfilled_buf(|buf| {
assert_eq!(buf.capacity(), 9);
assert_eq!(buf.init_len(), 9);
});

assert_eq!(cursor.init_mut().len(), 9);
assert_eq!(cursor.written(), 7);

assert_eq!(rbuf.filled(), &[1, 2, 3, 0, 0, 0, 0]);
}
Loading