Skip to content
79 changes: 79 additions & 0 deletions library/alloc/src/io/copy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
mod generic;
mod specialization;

use self::generic::generic_copy;
#[doc(hidden)]
#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
pub use self::specialization::SpecCopy;
use self::specialization::specialized_copy;
use crate::io::{Read, Result, Write};

#[derive(Debug)]
#[doc(hidden)]
#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
pub enum CopyState {
Ended(u64),
Fallback(u64),
}

/// Copies the entire contents of a reader into a writer.
///
/// This function will continuously read data from `reader` and then
/// write it into `writer` in a streaming fashion until `reader`
/// returns EOF.
///
/// On success, the total number of bytes that were copied from
/// `reader` to `writer` is returned.
///
/// If you want to copy the contents of one file to another and you’re
/// working with filesystem paths, see the [`fs::copy`] function.
///
// FIXME(#74481): Hard-links required to link from `alloc` to `std`
/// [`fs::copy`]: ../../std/fs/fn.copy.html
///
/// # Errors
///
/// This function will return an error immediately if any call to [`read`] or
/// [`write`] returns an error. All instances of [`ErrorKind::Interrupted`] are
/// handled by this function and the underlying operation is retried.
///
/// [`read`]: Read::read
/// [`write`]: Write::write
/// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
///
/// # Examples
///
/// ```
/// use std::io;
///
/// fn main() -> io::Result<()> {
/// let mut reader: &[u8] = b"hello";
/// let mut writer: Vec<u8> = vec![];
///
/// io::copy(&mut reader, &mut writer)?;
///
/// assert_eq!(&b"hello"[..], &writer[..]);
/// Ok(())
/// }
/// ```
///
/// # Platform-specific behavior
///
/// On Linux (including Android), this function uses `copy_file_range(2)`,
/// `sendfile(2)` or `splice(2)` syscalls to move data directly between file
/// descriptors if possible.
///
/// Note that platform-specific behavior may change in the future.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> Result<u64>
where
R: Read,
W: Write,
{
match specialized_copy(reader, writer)? {
CopyState::Ended(copied) => Ok(copied),
CopyState::Fallback(copied) => {
generic_copy(reader, writer).map(|additional| copied + additional)
}
}
}
86 changes: 13 additions & 73 deletions library/std/src/io/copy.rs → library/alloc/src/io/copy/generic.rs
Original file line number Diff line number Diff line change
@@ -1,80 +1,19 @@
use super::{BorrowedBuf, BufReader, BufWriter, DEFAULT_BUF_SIZE, Read, Result, Write};
use crate::alloc::Allocator;
use crate::cmp;
use core::cmp;
use core::mem::MaybeUninit;

#[cfg(not(no_global_oom_handling))]
use crate::collections::VecDeque;
use crate::io::IoSlice;
use crate::mem::MaybeUninit;
use crate::sys::io::{CopyState, kernel_copy};

#[cfg(test)]
mod tests;

/// Copies the entire contents of a reader into a writer.
///
/// This function will continuously read data from `reader` and then
/// write it into `writer` in a streaming fashion until `reader`
/// returns EOF.
///
/// On success, the total number of bytes that were copied from
/// `reader` to `writer` is returned.
///
/// If you want to copy the contents of one file to another and you’re
/// working with filesystem paths, see the [`fs::copy`] function.
///
/// [`fs::copy`]: crate::fs::copy
///
/// # Errors
///
/// This function will return an error immediately if any call to [`read`] or
/// [`write`] returns an error. All instances of [`ErrorKind::Interrupted`] are
/// handled by this function and the underlying operation is retried.
///
/// [`read`]: Read::read
/// [`write`]: Write::write
/// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
///
/// # Examples
///
/// ```
/// use std::io;
///
/// fn main() -> io::Result<()> {
/// let mut reader: &[u8] = b"hello";
/// let mut writer: Vec<u8> = vec![];
///
/// io::copy(&mut reader, &mut writer)?;
///
/// assert_eq!(&b"hello"[..], &writer[..]);
/// Ok(())
/// }
/// ```
///
/// # Platform-specific behavior
///
/// On Linux (including Android), this function uses `copy_file_range(2)`,
/// `sendfile(2)` or `splice(2)` syscalls to move data directly between file
/// descriptors if possible.
///
/// Note that platform-specific behavior [may change in the future][changes].
///
/// [changes]: crate::io#platform-specific-behavior
#[stable(feature = "rust1", since = "1.0.0")]
pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> Result<u64>
where
R: Read,
W: Write,
{
match kernel_copy(reader, writer)? {
CopyState::Ended(copied) => Ok(copied),
CopyState::Fallback(copied) => {
generic_copy(reader, writer).map(|additional| copied + additional)
}
}
}
use crate::io::{BorrowedBuf, BufReader, BufWriter, DEFAULT_BUF_SIZE, Read, Result, Write};
use crate::vec::Vec;
#[cfg_attr(
no_global_oom_handling,
expect(unused_imports, reason = "only required for VecDeque specialization")
)]
use crate::{alloc::Allocator, io::IoSlice};

/// The userspace read-write-loop implementation of `io::copy` that is used when
/// OS-specific specializations for copy offloading are not available or not applicable.
fn generic_copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> Result<u64>
pub(super) fn generic_copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> Result<u64>
where
R: Read,
W: Write,
Expand Down Expand Up @@ -128,6 +67,7 @@ impl BufferedReaderSpec for &[u8] {
}
}

#[cfg(not(no_global_oom_handling))]
impl<A: Allocator> BufferedReaderSpec for VecDeque<u8, A> {
fn buffer_size(&self) -> usize {
// prefer this specialization since the source "buffer" is all we'll ever need,
Expand Down
75 changes: 75 additions & 0 deletions library/alloc/src/io/copy/specialization.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//! Provides specialization for `io::copy`.

use super::CopyState;
use crate::io::{BufReader, Read, Result, Take, Write};

/// The implementation of `io::copy` that can rely on platform specific specialization
/// provided by `libstd`.
pub(super) fn specialized_copy<R: ?Sized, W: ?Sized>(
reader: &mut R,
writer: &mut W,
) -> Result<CopyState>
where
R: Read,
W: Write,
{
SpecCopyInner::copy((reader, writer))
}

trait SpecCopyInner {
fn copy(self) -> Result<CopyState>;
}

impl<R: Read + ?Sized, W: Write + ?Sized> SpecCopyInner for (&mut R, &mut W) {
default fn copy(self) -> Result<CopyState> {
Ok(CopyState::Fallback(0))
}
}

impl<R: SpecCopy, W: Write> SpecCopyInner for (&mut R, &mut W) {
fn copy(self) -> Result<CopyState> {
<R as SpecCopy>::copy(self.0, self.1)
}
}

#[doc(hidden)]
#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
#[rustc_specialization_trait]
pub trait SpecCopy: Read {
/// Attempt to copy from this reader to the provided writer using a specialized
/// process.
fn copy<R: Read + ?Sized, W: Write + ?Sized>(
_reader: &mut R,
_writer: &mut W,
) -> Result<CopyState>;
}

impl<T> SpecCopy for &mut T
where
T: SpecCopy,
{
fn copy<R: Read + ?Sized, W: Write + ?Sized>(
reader: &mut R,
writer: &mut W,
) -> Result<CopyState> {
<T as SpecCopy>::copy(reader, writer)
}
}

impl<T: SpecCopy> SpecCopy for Take<T> {
fn copy<R: Read + ?Sized, W: Write + ?Sized>(
reader: &mut R,
writer: &mut W,
) -> Result<CopyState> {
<T as SpecCopy>::copy(reader, writer)
}
}

impl<T: ?Sized + SpecCopy> SpecCopy for BufReader<T> {
fn copy<R: Read + ?Sized, W: Write + ?Sized>(
reader: &mut R,
writer: &mut W,
) -> Result<CopyState> {
<T as SpecCopy>::copy(reader, writer)
}
}
Loading
Loading