use std::fs::File;
use std::os::fd::AsFd;
use std::os::unix::fs::FileExt;
const FALLBACK_BUF_SIZE: usize = 1024 * 1024;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum ReflinkMode {
#[default]
Auto,
Never,
}
pub fn copy_file_data(
src: &File,
dst: &File,
len: u64,
reflink: ReflinkMode,
) -> std::io::Result<u64> {
match reflink {
ReflinkMode::Auto => copy_file_range_all(src, dst, len),
ReflinkMode::Never => copy_sparse_fallback(src, dst, 0, len),
}
}
fn copy_file_range_all(src: &File, dst: &File, len: u64) -> std::io::Result<u64> {
copy_file_range_all_with(src, dst, len, |src_offset, dst_offset, remaining| {
#[cfg(test)]
crate::testutils::record_copy_file_range_call();
nix::fcntl::copy_file_range(
src.as_fd(),
Some(src_offset),
dst.as_fd(),
Some(dst_offset),
remaining,
)
})
}
fn copy_file_range_all_with(
src: &File,
dst: &File,
len: u64,
mut copy_range: impl FnMut(&mut i64, &mut i64, usize) -> nix::Result<usize>,
) -> std::io::Result<u64> {
let mut copied: u64 = 0;
while copied < len {
let remaining = usize::try_from(len - copied).unwrap_or(usize::MAX);
let mut src_offset = i64::try_from(copied).map_err(|_| nix::errno::Errno::EOVERFLOW)?;
let mut dst_offset = src_offset;
match copy_range(&mut src_offset, &mut dst_offset, remaining) {
Ok(0)
| Err(
nix::errno::Errno::ENOSYS
| nix::errno::Errno::EXDEV
| nix::errno::Errno::EINVAL
| nix::errno::Errno::EOPNOTSUPP,
) => {
return copy_sparse_fallback(src, dst, copied, len);
}
Err(nix::errno::Errno::EPERM) if copied == 0 => {
return copy_sparse_fallback(src, dst, 0, len);
}
Ok(n) if n > remaining => return Err(nix::errno::Errno::EIO.into()),
Ok(n) => copied += n as u64,
Err(nix::errno::Errno::EINTR) => continue,
Err(errno) => return Err(std::io::Error::from(errno)),
}
}
Ok(copied)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SparseProbe {
Data(u64),
TrailingHole,
Unsupported,
}
fn classify_seek_data(result: nix::Result<libc::off_t>) -> std::io::Result<SparseProbe> {
match result {
Ok(off) => Ok(SparseProbe::Data(off as u64)),
Err(nix::errno::Errno::ENXIO) => Ok(SparseProbe::TrailingHole),
Err(nix::errno::Errno::EINVAL | nix::errno::Errno::EOPNOTSUPP) => {
Ok(SparseProbe::Unsupported)
}
Err(errno) => Err(std::io::Error::from(errno)),
}
}
fn copy_sparse_fallback(src: &File, dst: &File, start: u64, len: u64) -> std::io::Result<u64> {
copy_sparse_fallback_with_seek(src, dst, start, len, |offset, whence| {
nix::unistd::lseek(src.as_fd(), offset, whence)
})
}
fn copy_sparse_fallback_with_seek(
src: &File,
dst: &File,
start: u64,
len: u64,
mut seek: impl FnMut(libc::off_t, nix::unistd::Whence) -> nix::Result<libc::off_t>,
) -> std::io::Result<u64> {
debug_assert!(start <= len);
if start == len {
return Ok(len);
}
let mut off = start;
let mut written_end = start;
let mut read_eof = None;
let mut buf = Vec::new();
while off < len {
let extent = match next_copy_extent(&mut seek, off, len)? {
CopyExtent::Sparse(extent) => extent,
CopyExtent::Dense => off..len,
CopyExtent::End => break,
};
let capacity = (extent.end - extent.start).min(FALLBACK_BUF_SIZE as u64) as usize;
if buf.len() < capacity {
buf.resize(capacity, 0);
}
let end = copy_data_extent(src, dst, extent.start, extent.end, &mut buf[..capacity])?;
if end > extent.start {
written_end = end;
}
if end < extent.end {
read_eof = Some(end);
break;
}
off = extent.end;
}
let actual_eof = seek(0, nix::unistd::Whence::SeekEnd).map_err(std::io::Error::from)? as u64;
let final_size = len.min(actual_eof).min(read_eof.unwrap_or(len));
if written_end != final_size {
nix::unistd::ftruncate(dst.as_fd(), to_off_t(final_size)?).map_err(std::io::Error::from)?;
}
Ok(final_size)
}
enum CopyExtent {
Sparse(std::ops::Range<u64>),
Dense,
End,
}
fn next_copy_extent(
seek: &mut impl FnMut(libc::off_t, nix::unistd::Whence) -> nix::Result<libc::off_t>,
off: u64,
len: u64,
) -> std::io::Result<CopyExtent> {
let data = match classify_seek_data(seek(to_off_t(off)?, nix::unistd::Whence::SeekData))? {
SparseProbe::Data(data) => data,
SparseProbe::TrailingHole => return Ok(CopyExtent::End),
SparseProbe::Unsupported => return Ok(CopyExtent::Dense),
};
if data < off {
return Ok(CopyExtent::Dense);
}
if data >= len {
return Ok(CopyExtent::End);
}
let hole = match seek(to_off_t(data)?, nix::unistd::Whence::SeekHole) {
Ok(hole) => (hole as u64).min(len),
Err(nix::errno::Errno::ENXIO) => len,
Err(nix::errno::Errno::EINVAL | nix::errno::Errno::EOPNOTSUPP) => {
return Ok(CopyExtent::Dense);
}
Err(errno) => return Err(std::io::Error::from(errno)),
};
if hole <= data {
return Ok(CopyExtent::Dense);
}
Ok(CopyExtent::Sparse(data..hole))
}
fn copy_data_extent(
src: &impl FileExt,
dst: &impl FileExt,
from: u64,
to: u64,
buf: &mut [u8],
) -> std::io::Result<u64> {
let mut pos = from;
while pos < to {
let want = (to - pos).min(buf.len() as u64) as usize;
let n = match src.read_at(&mut buf[..want], pos) {
Ok(0) => break,
Ok(n) => n,
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
};
let mut written = 0;
while written < n {
match dst.write_at(&buf[written..n], pos + written as u64) {
Ok(0) => return Err(std::io::ErrorKind::WriteZero.into()),
Ok(w) => written += w,
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
Err(err) => return Err(err),
}
}
pos += n as u64;
}
Ok(pos)
}
fn to_off_t(value: u64) -> std::io::Result<libc::off_t> {
libc::off_t::try_from(value).map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"file offset exceeds off_t range",
)
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write as _;
use std::os::unix::fs::MetadataExt;
fn dense_copy(src: &File, dst: &File, start: u64, len: u64) -> std::io::Result<u64> {
copy_sparse_fallback_with_seek(src, dst, start, len, |offset, whence| match whence {
nix::unistd::Whence::SeekData | nix::unistd::Whence::SeekHole => {
Err(nix::errno::Errno::EOPNOTSUPP)
}
_ => nix::unistd::lseek(src.as_fd(), offset, whence),
})
}
fn make_file(dir: &std::path::Path, name: &str) -> File {
std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(dir.join(name))
.expect("open temp file")
}
fn copies_with_seek_results(
start: u64,
probes: &[(nix::unistd::Whence, libc::off_t, nix::Result<libc::off_t>)],
) {
let tmp = tempfile::tempdir().unwrap();
let contents = b"0123456789abcdef";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let mut dst = make_file(tmp.path(), "dst");
dst.write_all(&contents[..start as usize]).unwrap();
let mut probes = probes.iter();
let copied = copy_sparse_fallback_with_seek(
&src,
&dst,
start,
contents.len() as u64,
|offset, whence| {
if matches!(whence, nix::unistd::Whence::SeekEnd) {
return nix::unistd::lseek(src.as_fd(), offset, whence);
}
let &(expected_whence, expected_offset, result) = probes.next().unwrap();
assert_eq!(
(whence as i32, offset),
(expected_whence as i32, expected_offset)
);
result
},
)
.unwrap();
assert!(probes.next().is_none());
assert_eq!(copied, contents.len() as u64);
assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
}
fn copies_with_kernel_results(
src: &File,
dst: &File,
len: u64,
steps: &[(i64, usize, nix::Result<usize>)],
mut before_step: impl FnMut(usize),
) -> std::io::Result<u64> {
let mut steps = steps.iter().enumerate();
let copied =
copy_file_range_all_with(src, dst, len, |src_offset, dst_offset, remaining| {
let (step, &(offset, expected_remaining, result)) = steps.next().unwrap();
assert_eq!(
(*src_offset, *dst_offset, remaining),
(offset, offset, expected_remaining)
);
before_step(step);
match result {
Ok(n) if n <= remaining => {
let mut bytes = vec![0; n];
src.read_exact_at(&mut bytes, *src_offset as u64).unwrap();
dst.write_all_at(&bytes, *dst_offset as u64).unwrap();
*src_offset += n as i64;
*dst_offset += n as i64;
}
_ => {}
}
result
});
assert!(steps.next().is_none());
copied
}
#[test]
fn falls_back_when_kernel_copy_is_denied_before_progress() {
for interrupted in [false, true] {
for len in [7, 16, 20] {
let tmp = tempfile::tempdir().unwrap();
let contents = b"0123456789abcdef";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let dst = make_file(tmp.path(), "dst");
nix::unistd::lseek(src.as_fd(), 3, nix::unistd::Whence::SeekSet).unwrap();
nix::unistd::lseek(dst.as_fd(), 11, nix::unistd::Whence::SeekSet).unwrap();
let mut steps = Vec::new();
if interrupted {
steps.push((0, len as usize, Err(nix::errno::Errno::EINTR)));
}
steps.push((0, len as usize, Err(nix::errno::Errno::EPERM)));
let copied = copies_with_kernel_results(&src, &dst, len, &steps, |_| {}).unwrap();
let expected_len = len.min(contents.len() as u64);
assert_eq!(copied, expected_len);
assert_eq!(
std::fs::read(tmp.path().join("dst")).unwrap(),
&contents[..expected_len as usize]
);
}
}
}
#[test]
fn propagates_permission_errors_after_partial_kernel_copy() {
for interrupted in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let contents = b"0123456789abcdef";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let dst = make_file(tmp.path(), "dst");
let mut steps = vec![(0, 16, Ok(8))];
if interrupted {
steps.push((8, 8, Err(nix::errno::Errno::EINTR)));
}
steps.push((8, 8, Err(nix::errno::Errno::EPERM)));
let error = copies_with_kernel_results(&src, &dst, 16, &steps, |_| {}).unwrap_err();
assert_eq!(error.raw_os_error(), Some(libc::EPERM));
assert_eq!(
std::fs::read(tmp.path().join("dst")).unwrap(),
&contents[..8]
);
}
}
#[test]
fn propagates_fallback_errors_after_initial_kernel_permission_denial() {
let tmp = tempfile::tempdir().unwrap();
let mut src = make_file(tmp.path(), "src");
src.write_all(b"0123456789abcdef").unwrap();
drop(make_file(tmp.path(), "dst"));
let dst = File::open(tmp.path().join("dst")).unwrap();
let error = copies_with_kernel_results(
&src,
&dst,
16,
&[(0, 16, Err(nix::errno::Errno::EPERM))],
|_| {},
)
.unwrap_err();
assert_eq!(error.raw_os_error(), Some(libc::EBADF));
assert_eq!(dst.metadata().unwrap().len(), 0);
}
#[test]
fn rejects_kernel_copy_counts_larger_than_remaining() {
for prefix in [0, 8] {
let remaining = 16 - prefix;
for reported in [remaining + 1, usize::MAX] {
let tmp = tempfile::tempdir().unwrap();
let contents = b"0123456789abcdef";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let dst = make_file(tmp.path(), "dst");
let mut steps = Vec::new();
if prefix != 0 {
steps.push((0, 16, Ok(prefix)));
}
steps.push((prefix as i64, remaining, Ok(reported)));
let error = copies_with_kernel_results(&src, &dst, 16, &steps, |_| {}).unwrap_err();
assert_eq!(error.raw_os_error(), Some(libc::EIO));
assert_eq!(
std::fs::read(tmp.path().join("dst")).unwrap(),
&contents[..prefix]
);
}
}
}
#[test]
fn falls_back_from_the_confirmed_prefix_for_each_outcome() {
for outcome in [
Ok(0),
Err(nix::errno::Errno::ENOSYS),
Err(nix::errno::Errno::EXDEV),
Err(nix::errno::Errno::EINVAL),
Err(nix::errno::Errno::EOPNOTSUPP),
] {
let tmp = tempfile::tempdir().unwrap();
let contents = b"0123456789abcdef";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copies_with_kernel_results(
&src,
&dst,
16,
&[(0, 16, Ok(8)), (8, 8, outcome)],
|_| {},
)
.unwrap();
assert_eq!(copied, contents.len() as u64);
assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
}
}
#[test]
fn reports_final_size_when_source_shrinks_after_partial_kernel_copy() {
for final_len in [0, 3, 8, 12] {
let tmp = tempfile::tempdir().unwrap();
let contents = b"0123456789abcdef";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copies_with_kernel_results(
&src,
&dst,
16,
&[(0, 16, Ok(8)), (8, 8, Err(nix::errno::Errno::EXDEV))],
|step| {
if step == 1 {
src.set_len(final_len).unwrap();
}
},
)
.unwrap();
assert_eq!(copied, final_len);
assert_eq!(dst.metadata().unwrap().len(), final_len);
assert_eq!(
std::fs::read(tmp.path().join("dst")).unwrap(),
&contents[..final_len as usize]
);
}
}
#[test]
fn retries_interrupted_kernel_copies_without_restarting_the_prefix() {
let tmp = tempfile::tempdir().unwrap();
let contents = b"0123456789abcdef";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copies_with_kernel_results(
&src,
&dst,
16,
&[
(0, 16, Ok(8)),
(8, 8, Err(nix::errno::Errno::EINTR)),
(8, 8, Ok(8)),
],
|_| {},
)
.unwrap();
assert_eq!(copied, contents.len() as u64);
assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
}
#[test]
fn counts_the_sparse_prefix_when_later_probes_are_unsupported() {
use nix::unistd::Whence::{SeekData, SeekHole};
for errno in [nix::errno::Errno::EINVAL, nix::errno::Errno::EOPNOTSUPP] {
copies_with_seek_results(
4,
&[
(SeekData, 4, Ok(4)),
(SeekHole, 4, Ok(8)),
(SeekData, 8, Err(errno)),
],
);
}
}
#[test]
fn copies_densely_when_hole_probes_are_unsupported() {
use nix::unistd::Whence::{SeekData, SeekHole};
for errno in [nix::errno::Errno::EINVAL, nix::errno::Errno::EOPNOTSUPP] {
copies_with_seek_results(4, &[(SeekData, 4, Ok(4)), (SeekHole, 4, Err(errno))]);
}
}
#[test]
fn copies_densely_when_sparse_probes_do_not_advance() {
use nix::unistd::Whence::{SeekData, SeekHole};
copies_with_seek_results(4, &[(SeekData, 4, Ok(0))]);
for hole in [0, 4] {
copies_with_seek_results(4, &[(SeekData, 4, Ok(4)), (SeekHole, 4, Ok(hole))]);
}
}
#[test]
fn propagates_io_errors_from_hole_probes() {
let tmp = tempfile::tempdir().unwrap();
let mut src = make_file(tmp.path(), "src");
src.write_all(b"data").unwrap();
let dst = make_file(tmp.path(), "dst");
let error = copy_sparse_fallback_with_seek(&src, &dst, 0, 4, |_, whence| match whence {
nix::unistd::Whence::SeekData => Ok(0),
nix::unistd::Whence::SeekHole => Err(nix::errno::Errno::EIO),
_ => unreachable!(),
})
.unwrap_err();
assert_eq!(error.raw_os_error(), Some(libc::EIO));
}
#[test]
fn retries_interrupted_extent_io_and_completes_short_writes() {
let tmp = tempfile::tempdir().unwrap();
let contents = b"interrupted reads and short writes";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let dst = make_file(tmp.path(), "dst");
let src = crate::testutils::InterruptedFile::new(src);
let dst = crate::testutils::InterruptedFile::new(dst);
copy_data_extent(&src, &dst, 0, contents.len() as u64, &mut [0; 8]).unwrap();
assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
}
#[test]
fn does_not_pad_past_read_eof_when_seek_reports_a_larger_size() {
for start in [0, 3] {
for sparse in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let contents = b"short";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let mut dst = make_file(tmp.path(), "dst");
dst.write_all(&contents[..start as usize]).unwrap();
let copied =
copy_sparse_fallback_with_seek(
&src,
&dst,
start,
16,
|_, whence| match whence {
nix::unistd::Whence::SeekData if sparse => Ok(start as libc::off_t),
nix::unistd::Whence::SeekData => Err(nix::errno::Errno::EOPNOTSUPP),
nix::unistd::Whence::SeekHole | nix::unistd::Whence::SeekEnd => Ok(16),
_ => unreachable!(),
},
)
.unwrap();
assert_eq!(copied, contents.len() as u64);
assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
}
}
}
#[test]
fn reconciles_a_source_shrunk_after_the_last_extent() {
for start in [0, 4] {
let tmp = tempfile::tempdir().unwrap();
let contents = b"0123456789abcdef";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
let mut dst = make_file(tmp.path(), "dst");
dst.write_all(&contents[..start as usize]).unwrap();
let copied = copy_sparse_fallback_with_seek(
&src,
&dst,
start,
contents.len() as u64,
|offset, whence| match whence {
nix::unistd::Whence::SeekData => Ok(start as libc::off_t),
nix::unistd::Whence::SeekHole => Ok(contents.len() as libc::off_t),
nix::unistd::Whence::SeekEnd => {
src.set_len(3).unwrap();
nix::unistd::lseek(src.as_fd(), offset, whence)
}
_ => unreachable!(),
},
)
.unwrap();
assert_eq!(copied, 3);
assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), b"012");
}
}
#[test]
fn copies_bytes_identically() {
let tmp = tempfile::tempdir().unwrap();
let contents = b"the quick brown fox jumps over the lazy dog";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copy_file_range_all(&src, &dst, contents.len() as u64).unwrap();
assert_eq!(copied, contents.len() as u64);
let got = std::fs::read(tmp.path().join("dst")).unwrap();
assert_eq!(got, contents);
}
#[test]
fn copies_without_copy_file_range_when_reflink_is_disabled() {
let tmp = tempfile::tempdir().unwrap();
let contents = b"a non-empty source with an unaligned size";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
for len in [0, 7, contents.len() as u64, contents.len() as u64 + 100] {
let dst = make_file(tmp.path(), "never");
let calls_before = crate::testutils::copy_file_range_calls();
let copied = copy_file_data(&src, &dst, len, ReflinkMode::Never).unwrap();
let expected_len = len.min(contents.len() as u64);
assert_eq!(copied, expected_len);
assert_eq!(
std::fs::read(tmp.path().join("never")).unwrap(),
&contents[..expected_len as usize]
);
assert_eq!(crate::testutils::copy_file_range_calls(), calls_before);
}
let dst = make_file(tmp.path(), "auto");
let calls_before = crate::testutils::copy_file_range_calls();
copy_file_data(&src, &dst, contents.len() as u64, ReflinkMode::Auto).unwrap();
assert!(crate::testutils::copy_file_range_calls() > calls_before);
assert_eq!(std::fs::read(tmp.path().join("auto")).unwrap(), contents);
}
#[test]
fn copies_from_zero_with_nonzero_source_and_destination_cursors() {
let tmp = tempfile::tempdir().unwrap();
let contents = b"independent source and destination cursors";
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
for (policy, len) in [
(ReflinkMode::Auto, 7),
(ReflinkMode::Auto, contents.len() as u64 + 10),
(ReflinkMode::Never, contents.len() as u64),
] {
let dst = make_file(tmp.path(), "dst");
nix::unistd::lseek(src.as_fd(), 3, nix::unistd::Whence::SeekSet).unwrap();
nix::unistd::lseek(dst.as_fd(), 11, nix::unistd::Whence::SeekSet).unwrap();
let copied = copy_file_data(&src, &dst, len, policy).unwrap();
let expected_len = len.min(contents.len() as u64);
assert_eq!(copied, expected_len);
assert_eq!(
std::fs::read(tmp.path().join("dst")).unwrap(),
&contents[..expected_len as usize]
);
}
}
#[test]
fn preserves_sparse_suffix_after_partial_kernel_copy() {
let tmp = tempfile::tempdir().unwrap();
let logical = 8 * 1024 * 1024;
let src = make_file(tmp.path(), "src");
src.set_len(logical).unwrap();
src.write_all_at(b"head", 0).unwrap();
src.write_all_at(b"tail", 4 * 1024 * 1024).unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copies_with_kernel_results(
&src,
&dst,
logical,
&[
(0, logical as usize, Ok(4096)),
(4096, logical as usize - 4096, Err(nix::errno::Errno::EXDEV)),
],
|_| {},
)
.unwrap();
assert_eq!(copied, logical);
assert_eq!(dst.metadata().unwrap().len(), logical);
assert_eq!(
std::fs::read(tmp.path().join("dst")).unwrap(),
std::fs::read(tmp.path().join("src")).unwrap()
);
let src_allocated = src.metadata().unwrap().blocks() * 512;
let dst_allocated = dst.metadata().unwrap().blocks() * 512;
assert!(
src_allocated < logical,
"source fixture is not sparse: allocated {src_allocated} >= logical {logical}"
);
assert!(
dst_allocated < logical,
"destination is not sparse: dst={dst_allocated}, src={src_allocated}, logical={logical}"
);
}
#[test]
fn copies_sparse_contents_and_trailing_hole_with_auto() {
let tmp = tempfile::tempdir().unwrap();
let logical = 64 * 1024;
let src = make_file(tmp.path(), "src");
src.set_len(logical).unwrap();
src.write_all_at(b"head", 0).unwrap();
src.write_all_at(b"middle", logical / 2).unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copy_file_data(&src, &dst, logical, ReflinkMode::Auto).unwrap();
assert_eq!(copied, logical);
assert_eq!(dst.metadata().unwrap().len(), logical);
assert_eq!(
std::fs::read(tmp.path().join("dst")).unwrap(),
std::fs::read(tmp.path().join("src")).unwrap()
);
}
#[test]
fn copies_large_file_fully() {
let tmp = tempfile::tempdir().unwrap();
let len: usize = 8 * 1024 * 1024;
let data: Vec<u8> = (0..len)
.map(|i| (i.wrapping_mul(31) ^ (i >> 7)) as u8)
.collect();
let mut src = make_file(tmp.path(), "src");
src.write_all(&data).unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copy_file_range_all(&src, &dst, len as u64).unwrap();
assert_eq!(copied, len as u64);
let got = std::fs::read(tmp.path().join("dst")).unwrap();
assert_eq!(got.len(), len);
assert!(got == data, "destination bytes differ from source");
}
#[test]
fn preserves_holes_when_reflink_is_disabled() {
let tmp = tempfile::tempdir().unwrap();
let logical: u64 = 8 * 1024 * 1024;
let head = b"HEAD-region-bytes";
let tail = b"TAIL-region-bytes";
let tail_off = logical - tail.len() as u64;
let src = make_file(tmp.path(), "src");
nix::unistd::ftruncate(src.as_fd(), to_off_t(logical).unwrap()).unwrap();
src.write_at(head, 0).unwrap();
src.write_at(tail, tail_off).unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copy_file_data(&src, &dst, logical, ReflinkMode::Never).unwrap();
assert_eq!(copied, logical);
let got = std::fs::read(tmp.path().join("dst")).unwrap();
let expected = std::fs::read(tmp.path().join("src")).unwrap();
assert_eq!(got.len() as u64, logical);
assert_eq!(got, expected, "destination content differs from source");
assert_eq!(&got[..head.len()], head);
assert_eq!(&got[tail_off as usize..], tail);
let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
assert_eq!(dst_meta.len(), logical);
let src_meta = std::fs::metadata(tmp.path().join("src")).unwrap();
let dst_allocated = dst_meta.blocks() * 512;
let src_allocated = src_meta.blocks() * 512;
eprintln!(
"sparse blocks: src={} blocks ({} bytes), dst={} blocks ({} bytes), logical={} bytes",
src_meta.blocks(),
src_allocated,
dst_meta.blocks(),
dst_allocated,
logical
);
assert!(
dst_allocated < logical,
"destination is not sparse: allocated {dst_allocated} >= logical {logical}"
);
assert!(
dst_allocated <= src_allocated * 4 + 4096,
"destination far less sparse than source: dst={dst_allocated} src={src_allocated}"
);
}
#[test]
fn terminates_on_short_source() {
let tmp = tempfile::tempdir().unwrap();
let contents = b"short source contents";
let real_len = contents.len() as u64;
let mut src = make_file(tmp.path(), "src");
src.write_all(contents).unwrap();
src.sync_all().unwrap();
let _dst = make_file(tmp.path(), "dst");
let claimed = real_len + 4096;
let (tx, rx) = std::sync::mpsc::channel();
let src_path = tmp.path().join("src");
let dst_path = tmp.path().join("dst");
std::thread::spawn(move || {
let src = std::fs::File::open(&src_path).unwrap();
let dst = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&dst_path)
.unwrap();
let copied = copy_file_range_all(&src, &dst, claimed).unwrap();
tx.send(copied).unwrap();
});
let copied = rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("copy_file_range_all hung on a short source");
assert_eq!(copied, real_len);
let got = std::fs::read(tmp.path().join("dst")).unwrap();
assert_eq!(got, contents);
}
#[test]
fn copies_partial_len_on_both_paths() {
let tmp = tempfile::tempdir().unwrap();
let full: Vec<u8> = (0u32..4096).map(|i| (i % 251) as u8).collect();
let len: u64 = 1000;
let mut src = make_file(tmp.path(), "src");
src.write_all(&full).unwrap();
src.sync_all().unwrap();
let dst_cfr = make_file(tmp.path(), "dst_cfr");
let copied_cfr = copy_file_range_all(&src, &dst_cfr, len).unwrap();
assert_eq!(copied_cfr, len);
let got_cfr = std::fs::read(tmp.path().join("dst_cfr")).unwrap();
assert_eq!(got_cfr.len() as u64, len);
assert_eq!(got_cfr, &full[..len as usize]);
let dst_fb = make_file(tmp.path(), "dst_fb");
let copied_fb = copy_sparse_fallback(&src, &dst_fb, 0, len).unwrap();
assert_eq!(copied_fb, len);
let got_fb = std::fs::read(tmp.path().join("dst_fb")).unwrap();
assert_eq!(got_fb.len() as u64, len);
assert_eq!(got_fb, &full[..len as usize]);
}
#[test]
fn fallback_shrunk_source_not_padded() {
let tmp = tempfile::tempdir().unwrap();
let contents: Vec<u8> = (0u32..3000).map(|i| (i % 240) as u8).collect();
let s = contents.len() as u64;
let mut src = make_file(tmp.path(), "src");
src.write_all(&contents).unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copy_sparse_fallback(&src, &dst, 0, s + 8192).unwrap();
assert_eq!(
copied, s,
"must return actual source bytes, not the claimed len"
);
let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
assert_eq!(
dst_meta.len(),
s,
"dst must be sized to the source, not padded"
);
let got = std::fs::read(tmp.path().join("dst")).unwrap();
assert_eq!(got, contents);
}
#[test]
fn copies_zero_length() {
let tmp = tempfile::tempdir().unwrap();
let mut src = make_file(tmp.path(), "src");
src.write_all(b"non-empty source contents").unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let calls_before = crate::testutils::copy_file_range_calls();
let copied = copy_file_range_all(&src, &dst, 0).unwrap();
assert_eq!(copied, 0);
assert_eq!(crate::testutils::copy_file_range_calls(), calls_before);
let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
assert_eq!(dst_meta.len(), 0, "zero-length copy must leave dst empty");
}
#[test]
fn copies_all_hole_source_when_reflink_is_disabled() {
let tmp = tempfile::tempdir().unwrap();
let logical: u64 = 4 * 1024 * 1024;
let src = make_file(tmp.path(), "src");
nix::unistd::ftruncate(src.as_fd(), to_off_t(logical).unwrap()).unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = copy_file_data(&src, &dst, logical, ReflinkMode::Never).unwrap();
assert_eq!(copied, logical);
let got = std::fs::read(tmp.path().join("dst")).unwrap();
assert_eq!(got.len() as u64, logical);
assert!(
got.iter().all(|&b| b == 0),
"all-hole copy must be all zeros"
);
let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
assert_eq!(dst_meta.len(), logical);
let dst_allocated = dst_meta.blocks() * 512;
eprintln!(
"all-hole: dst={} blocks ({dst_allocated} bytes), logical={logical}",
dst_meta.blocks()
);
assert!(
dst_allocated < logical,
"all-hole destination is not sparse: allocated {dst_allocated} >= logical {logical}"
);
}
#[test]
fn classify_seek_data_routes_by_errno() {
assert_eq!(
classify_seek_data(Ok(4096)).unwrap(),
SparseProbe::Data(4096)
);
assert_eq!(
classify_seek_data(Err(nix::errno::Errno::ENXIO)).unwrap(),
SparseProbe::TrailingHole
);
assert_eq!(
classify_seek_data(Err(nix::errno::Errno::EINVAL)).unwrap(),
SparseProbe::Unsupported
);
assert_eq!(
classify_seek_data(Err(nix::errno::Errno::EOPNOTSUPP)).unwrap(),
SparseProbe::Unsupported
);
assert_eq!(
classify_seek_data(Err(nix::errno::Errno::ENOTSUP)).unwrap(),
SparseProbe::Unsupported
);
let err = classify_seek_data(Err(nix::errno::Errno::EIO)).unwrap_err();
assert_eq!(err.raw_os_error(), Some(libc::EIO));
}
#[test]
fn dense_copy_is_byte_exact_with_embedded_zeros() {
let tmp = tempfile::tempdir().unwrap();
let len: usize = 3 * FALLBACK_BUF_SIZE + 777; let mut data: Vec<u8> = (0..len)
.map(|i| (i.wrapping_mul(37) ^ (i >> 5)) as u8)
.collect();
for b in data.iter_mut().take(FALLBACK_BUF_SIZE + 4096).skip(100) {
*b = 0;
}
for b in data
.iter_mut()
.take(2 * FALLBACK_BUF_SIZE)
.skip(2 * FALLBACK_BUF_SIZE - 500)
{
*b = 0;
}
let mut src = make_file(tmp.path(), "src");
src.write_all(&data).unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = dense_copy(&src, &dst, 0, len as u64).unwrap();
assert_eq!(copied, len as u64);
let got = std::fs::read(tmp.path().join("dst")).unwrap();
assert_eq!(got.len(), len, "dense copy must size dst to the source");
assert!(got == data, "dense copy bytes differ from source");
}
#[test]
fn dense_copy_partial_len_sizes_dst_exactly() {
let tmp = tempfile::tempdir().unwrap();
let full: Vec<u8> = (0u32..8192).map(|i| (i % 251) as u8).collect();
let len: u64 = 5000;
let mut src = make_file(tmp.path(), "src");
src.write_all(&full).unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = dense_copy(&src, &dst, 0, len).unwrap();
assert_eq!(copied, len);
let got = std::fs::read(tmp.path().join("dst")).unwrap();
assert_eq!(got.len() as u64, len);
assert_eq!(got, &full[..len as usize]);
}
#[test]
fn dense_copy_shrunk_source_not_padded() {
let tmp = tempfile::tempdir().unwrap();
let contents: Vec<u8> = (0u32..3000).map(|i| (i % 240) as u8).collect();
let s = contents.len() as u64;
let mut src = make_file(tmp.path(), "src");
src.write_all(&contents).unwrap();
src.sync_all().unwrap();
let dst = make_file(tmp.path(), "dst");
let copied = dense_copy(&src, &dst, 0, s + 8192).unwrap();
assert_eq!(
copied, s,
"dense copy must return actual source bytes, not the claimed len"
);
let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
assert_eq!(dst_meta.len(), s, "dst must be sized to the source");
let got = std::fs::read(tmp.path().join("dst")).unwrap();
assert_eq!(got, contents);
}
#[test]
fn copies_densely_when_the_initial_probe_is_unsupported() {
for errno in [nix::errno::Errno::EINVAL, nix::errno::Errno::EOPNOTSUPP] {
copies_with_seek_results(4, &[(nix::unistd::Whence::SeekData, 4, Err(errno))]);
}
}
}