Skip to content

Commit b540e18

Browse files
authored
Merge pull request #7519 from karlmcdowall/cat_perf
cat: Improve performance of formatting.
2 parents 09d7b2d + c84ee0a commit b540e18

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/uu/cat/src/cat.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
// spell-checker:ignore (ToDO) nonprint nonblank nonprinting ELOOP
77
use std::fs::{metadata, File};
8-
use std::io::{self, IsTerminal, Read, Write};
8+
use std::io::{self, BufWriter, IsTerminal, Read, Write};
99
/// Unix domain socket support
1010
#[cfg(unix)]
1111
use std::net::Shutdown;
@@ -511,7 +511,9 @@ fn write_lines<R: FdReadable>(
511511
) -> CatResult<()> {
512512
let mut in_buf = [0; 1024 * 31];
513513
let stdout = io::stdout();
514-
let mut writer = stdout.lock();
514+
let stdout = stdout.lock();
515+
// Add a 32K buffer for stdout - this greatly improves performance.
516+
let mut writer = BufWriter::with_capacity(32 * 1024, stdout);
515517

516518
while let Ok(n) = handle.reader.read(&mut in_buf) {
517519
if n == 0 {
@@ -560,6 +562,14 @@ fn write_lines<R: FdReadable>(
560562
}
561563
pos += offset + 1;
562564
}
565+
// We need to flush the buffer each time around the loop in order to pass GNU tests.
566+
// When we are reading the input from a pipe, the `handle.reader.read` call at the top
567+
// of this loop will block (indefinitely) whist waiting for more data. The expectation
568+
// however is that anything that's ready for output should show up in the meantime,
569+
// and not be buffered internally to the `cat` process.
570+
// Hence it's necessary to flush our buffer before every time we could potentially block
571+
// on a `std::io::Read::read` call.
572+
writer.flush()?;
563573
}
564574

565575
Ok(())

0 commit comments

Comments
 (0)