Skip to content

Commit

Permalink
Rollup merge of rust-lang#136967 - DaniPopes:io-repeat-fill, r=joboet
Browse files Browse the repository at this point in the history
Use `slice::fill` in `io::Repeat` implementation

Use the existing `fill` methods on slices instead of manually writing the fill loop.
  • Loading branch information
workingjubilee authored Feb 14, 2025
2 parents c4effdb + 1a3efd2 commit 2013078
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 18 deletions.
28 changes: 10 additions & 18 deletions library/std/src/io/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::fmt;
use crate::io::{
self, BorrowedCursor, BufRead, IoSlice, IoSliceMut, Read, Seek, SeekFrom, SizeHint, Write,
};
use crate::mem::MaybeUninit;

/// `Empty` ignores any data written via [`Write`], and will always be empty
/// (returning zero bytes) when read via [`Read`].
Expand Down Expand Up @@ -182,35 +183,26 @@ pub const fn repeat(byte: u8) -> Repeat {
impl Read for Repeat {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
for slot in &mut *buf {
*slot = self.byte;
}
buf.fill(self.byte);
Ok(buf.len())
}

#[inline]
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
for slot in &mut *buf {
*slot = self.byte;
}
buf.fill(self.byte);
Ok(())
}

#[inline]
fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> io::Result<()> {
// SAFETY: No uninit bytes are being written
for slot in unsafe { buf.as_mut() } {
slot.write(self.byte);
}

let remaining = buf.capacity();

// SAFETY: the entire unfilled portion of buf has been initialized
unsafe {
buf.advance_unchecked(remaining);
}

// SAFETY: No uninit bytes are being written.
MaybeUninit::fill(unsafe { buf.as_mut() }, self.byte);
// SAFETY: the entire unfilled portion of buf has been initialized.
unsafe { buf.advance_unchecked(buf.capacity()) };
Ok(())
}

#[inline]
fn read_buf_exact(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
self.read_buf(buf)
}
Expand Down
1 change: 1 addition & 0 deletions library/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@
#![feature(link_cfg)]
#![feature(linkage)]
#![feature(macro_metavar_expr_concat)]
#![feature(maybe_uninit_fill)]
#![feature(min_specialization)]
#![feature(must_not_suspend)]
#![feature(needs_panic_runtime)]
Expand Down

0 comments on commit 2013078

Please sign in to comment.