chiark / gitweb /
utils: Provide io_copy_interactive
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Tue, 1 Jun 2021 12:54:07 +0000 (13:54 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Tue, 1 Jun 2021 14:42:14 +0000 (15:42 +0100)
stdlib io::copy insists on buffering.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
src/utils.rs

index 9c73675a6f5dac3ec2f883c5a5c0920a211324e2..4b7c070420347522424cd2f321fab522bd63247a 100644 (file)
@@ -676,6 +676,24 @@ impl anyhow::Error {
   }
 }
 
+#[throws(Either<io::Error, io::Error>)]
+pub fn io_copy_interactive<R,W>(read: &mut BufReader<R>, write: &mut W)
+where R: Read, W: Write {
+  loop {
+    let buf = read.fill_buf().map_err(Either::Left)?;
+    if buf.len() == 0 { break }
+
+    let did = (||{
+      let did = write.write(buf)?;
+      if did == 0 { throw!(ErrorKind::WriteZero) }
+      Ok::<_,io::Error>(did)
+    })().map_err(Either::Right)?;
+        
+    read.consume(did);
+    write.flush().map_err(Either::Right)?;
+  }
+}
+
 #[throws(fmt::Error)]
 pub fn fmt_hex(f: &mut Formatter, buf: &[u8]) {
   for v in buf { write!(f, "{:02x}", v)?; }