Skip to content

Unify fs::copy and io::copy on Linux #134547

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

Merged
merged 3 commits into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 10 additions & 25 deletions library/std/src/sys/pal/unix/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1944,7 +1944,7 @@ fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)>
#[cfg(target_os = "espidf")]
fn open_to_and_set_permissions(
to: &Path,
_reader_metadata: crate::fs::Metadata,
_reader_metadata: &crate::fs::Metadata,
) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
use crate::fs::OpenOptions;
let writer = OpenOptions::new().open(to)?;
Expand All @@ -1955,7 +1955,7 @@ fn open_to_and_set_permissions(
#[cfg(not(target_os = "espidf"))]
fn open_to_and_set_permissions(
to: &Path,
reader_metadata: crate::fs::Metadata,
reader_metadata: &crate::fs::Metadata,
) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
use crate::fs::OpenOptions;
use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
Expand All @@ -1980,30 +1980,15 @@ fn open_to_and_set_permissions(
Ok((writer, writer_metadata))
}

#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
#[cfg(not(target_vendor = "apple"))]
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
let (mut reader, reader_metadata) = open_from(from)?;
let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;

io::copy(&mut reader, &mut writer)
}
let (reader, reader_metadata) = open_from(from)?;
let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;

#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
let (mut reader, reader_metadata) = open_from(from)?;
let max_len = u64::MAX;
let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;

use super::kernel_copy::{CopyResult, copy_regular_files};

match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) {
CopyResult::Ended(bytes) => Ok(bytes),
CopyResult::Error(e, _) => Err(e),
CopyResult::Fallback(written) => match io::copy::generic_copy(&mut reader, &mut writer) {
Ok(bytes) => Ok(bytes + written),
Err(e) => Err(e),
},
}
io::copy(
&mut crate::sys::kernel_copy::CachedFileMetadata(reader, reader_metadata),
&mut crate::sys::kernel_copy::CachedFileMetadata(writer, writer_metadata),
Copy link
Member

Choose a reason for hiding this comment

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

The kernel_copy module is only defined for linux/android. So this would fail on some other unixes.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good point, fixed. I'm surprised CI doesn't catch that.

)
}

#[cfg(target_vendor = "apple")]
Expand Down Expand Up @@ -2040,7 +2025,7 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
}

// Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;

// We ensure that `FreeOnDrop` never contains a null pointer so it is
// always safe to call `copyfile_state_free`
Expand Down
58 changes: 55 additions & 3 deletions library/std/src/sys/pal/unix/kernel_copy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ use crate::cmp::min;
use crate::fs::{File, Metadata};
use crate::io::copy::generic_copy;
use crate::io::{
BufRead, BufReader, BufWriter, Error, Read, Result, StderrLock, StdinLock, StdoutLock, Take,
Write,
BorrowedCursor, BufRead, BufReader, BufWriter, Error, IoSlice, IoSliceMut, Read, Result,
StderrLock, StdinLock, StdoutLock, Take, Write,
};
use crate::mem::ManuallyDrop;
use crate::net::TcpStream;
Expand Down Expand Up @@ -192,7 +192,7 @@ impl<R: CopyRead, W: CopyWrite> SpecCopy for Copier<'_, '_, R, W> {
let w_cfg = writer.properties();

// before direct operations on file descriptors ensure that all source and sink buffers are empty
let mut flush = || -> crate::io::Result<u64> {
let mut flush = || -> Result<u64> {
let bytes = reader.drain_to(writer, u64::MAX)?;
// BufWriter buffered bytes have already been accounted for in earlier write() calls
writer.flush()?;
Expand Down Expand Up @@ -537,6 +537,58 @@ impl<T: ?Sized + CopyWrite> CopyWrite for BufWriter<T> {
}
}

pub(crate) struct CachedFileMetadata(pub File, pub Metadata);

impl Read for CachedFileMetadata {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
self.0.read(buf)
}
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
self.0.read_vectored(bufs)
}
fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
self.0.read_buf(cursor)
}
#[inline]
fn is_read_vectored(&self) -> bool {
self.0.is_read_vectored()
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
self.0.read_to_end(buf)
}
fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
self.0.read_to_string(buf)
}
}
impl Write for CachedFileMetadata {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.0.write(buf)
}
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
self.0.write_vectored(bufs)
}
#[inline]
fn is_write_vectored(&self) -> bool {
self.0.is_write_vectored()
}
#[inline]
fn flush(&mut self) -> Result<()> {
self.0.flush()
}
}

impl CopyRead for CachedFileMetadata {
fn properties(&self) -> CopyParams {
CopyParams(FdMeta::Metadata(self.1.clone()), Some(self.0.as_raw_fd()))
}
}

impl CopyWrite for CachedFileMetadata {
fn properties(&self) -> CopyParams {
CopyParams(FdMeta::Metadata(self.1.clone()), Some(self.0.as_raw_fd()))
}
}

fn fd_to_meta<T: AsRawFd>(fd: &T) -> FdMeta {
let fd = fd.as_raw_fd();
let file: ManuallyDrop<File> = ManuallyDrop::new(unsafe { File::from_raw_fd(fd) });
Expand Down
Loading