Skip to content

Commit

Permalink
std: Unsafe-wrap std::io
Browse files Browse the repository at this point in the history
  • Loading branch information
workingjubilee committed Jul 15, 2024
1 parent 91b7331 commit 8c3a9c1
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 9 deletions.
8 changes: 5 additions & 3 deletions std/src/io/buffered/bufwriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -433,9 +433,11 @@ impl<W: ?Sized + Write> BufWriter<W> {
let old_len = self.buf.len();
let buf_len = buf.len();
let src = buf.as_ptr();
let dst = self.buf.as_mut_ptr().add(old_len);
ptr::copy_nonoverlapping(src, dst, buf_len);
self.buf.set_len(old_len + buf_len);
unsafe {
let dst = self.buf.as_mut_ptr().add(old_len);
ptr::copy_nonoverlapping(src, dst, buf_len);
self.buf.set_len(old_len + buf_len);
}
}

#[inline]
Expand Down
2 changes: 1 addition & 1 deletion std/src/io/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ where
A: Allocator,
{
debug_assert!(vec.capacity() >= pos + buf.len());
vec.as_mut_ptr().add(pos).copy_from(buf.as_ptr(), buf.len());
unsafe { vec.as_mut_ptr().add(pos).copy_from(buf.as_ptr(), buf.len()) };
pos + buf.len()
}

Expand Down
7 changes: 5 additions & 2 deletions std/src/io/error/repr_bitpacked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,11 +267,14 @@ where
// Using this rather than unwrap meaningfully improves the code
// for callers which only care about one variant (usually
// `Custom`)
core::hint::unreachable_unchecked();
unsafe { core::hint::unreachable_unchecked() };
});
ErrorData::Simple(kind)
}
TAG_SIMPLE_MESSAGE => ErrorData::SimpleMessage(&*ptr.cast::<SimpleMessage>().as_ptr()),
TAG_SIMPLE_MESSAGE => {
// SAFETY: per tag
unsafe { ErrorData::SimpleMessage(&*ptr.cast::<SimpleMessage>().as_ptr()) }
}
TAG_CUSTOM => {
// It would be correct for us to use `ptr::byte_sub` here (see the
// comment above the `wrapping_add` call in `new_custom` for why),
Expand Down
5 changes: 2 additions & 3 deletions std/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,6 @@
//! [`Arc`]: crate::sync::Arc
#![stable(feature = "rust1", since = "1.0.0")]
#![allow(unsafe_op_in_unsafe_fn)]

#[cfg(test)]
mod tests;
Expand Down Expand Up @@ -383,11 +382,11 @@ pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize
where
F: FnOnce(&mut Vec<u8>) -> Result<usize>,
{
let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
let mut g = Guard { len: buf.len(), buf: unsafe { buf.as_mut_vec() } };
let ret = f(g.buf);

// SAFETY: the caller promises to only append data to `buf`
let appended = g.buf.get_unchecked(g.len..);
let appended = unsafe { g.buf.get_unchecked(g.len..) };
if str::from_utf8(appended).is_err() {
ret.and_then(|_| Err(Error::INVALID_UTF8))
} else {
Expand Down

0 comments on commit 8c3a9c1

Please sign in to comment.