Skip to content

Commit ddcffb3

Browse files
committed
Added comments on safety and Miri
1 parent 8e881a8 commit ddcffb3

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/bytes.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,21 @@ impl Bytes {
228228
where
229229
T: AsRef<[u8]> + Send + 'static,
230230
{
231+
/// Safety & Miri:
232+
/// The ownership of `owner` is first transferred to the `Owned` wrapper and `Bytes` object.
233+
/// This ensures that the owner is pinned in memory, allowing us to call `.as_ref()` safely
234+
/// since the lifetime of the owner is controlled by the lifetime of the new `Bytes` object,
235+
/// and the lifetime of the resulting borrowed `&[u8]` matches that of the owner.
236+
/// Note that this remains safe so long as we only call `.as_ref()` once.
237+
///
238+
/// There are some additional special considerations here:
239+
/// * We rely on Bytes's Drop impl to clean up memory should `.as_ref()` panic.
240+
/// * Setting the `ptr` and `len` on the bytes object last (after moving the owner to
241+
/// Bytes) allows Miri checks to pass since it avoids obtaining the `&[u8]` slice
242+
/// from a stack-owned Box.
243+
/// More details on this: https://github.com/tokio-rs/bytes/pull/742/#discussion_r1813375863
244+
/// and: https://github.com/tokio-rs/bytes/pull/742/#discussion_r1813316032
245+
231246
let owned = Box::into_raw(Box::new(Owned {
232247
lifetime: OwnedLifetime {
233248
ref_cnt: AtomicUsize::new(1),

0 commit comments

Comments
 (0)