Skip to content

Commit 46bfc79

Browse files
committed
cat: avoid unnecessary alloc on Linux
1 parent 4704cae commit 46bfc79

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

src/uu/cat/src/cat.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -488,14 +488,18 @@ fn write_fast<R: FdReadable>(handle: &mut InputHandle<R>) -> CatResult<()> {
488488
return Ok(());
489489
}
490490
}
491+
491492
// If we're not on Linux or Android, or the splice() call failed,
492493
// fall back on slower writing.
494+
write_slow(handle, stdout)
495+
}
496+
497+
#[cfg_attr(any(target_os = "linux", target_os = "android"), inline(never))] // splice fast-path does not require this allocation
498+
#[cfg_attr(not(any(target_os = "linux", target_os = "android")), inline)]
499+
fn write_slow<R: FdReadable>(handle: &mut InputHandle<R>, mut stdout: io::Stdout) -> CatResult<()> {
493500
let mut stdout_lock = stdout.lock();
494-
// stack allocation is overhead when splice succeed
495-
#[cfg(any(target_os = "linux", target_os = "android"))]
496-
let mut buf = vec![0; 1024 * 64];
497-
#[cfg(not(any(target_os = "linux", target_os = "android")))]
498501
let mut buf = [0; 1024 * 64];
502+
499503
loop {
500504
match handle.reader.read(&mut buf) {
501505
Ok(n) => {
@@ -515,8 +519,8 @@ fn write_fast<R: FdReadable>(handle: &mut InputHandle<R>) -> CatResult<()> {
515519
// stdout via while loop above AND there will be second splice() call
516520
// that will succeed, data pushed through splice will be output before
517521
// the data buffered in stdout.lock. Therefore additional explicit flush
518-
// is required here.
519-
stdout_lock.flush().inspect_err(handle_broken_pipe)?;
522+
// is required here
523+
stdout.flush().inspect_err(handle_broken_pipe)?;
520524
Ok(())
521525
}
522526

0 commit comments

Comments
 (0)