From d8203c5f3998b9b3586e881b2d16fc52b07770a8 Mon Sep 17 00:00:00 2001 From: Jean Mertz Date: Sat, 31 Jan 2026 21:32:54 +0100 Subject: [PATCH] enhance(printer): Implement `flush` for `PrinterWriter` The `PrinterWriter` now implements the `flush` method by sending a `Flush` command to the printer and waiting for it to be processed. This ensures that all messages written to the printer are fully handled before the call returns. Additionally, added a `Printable` implementation for `&String` to allow more flexible usage when printing string references. Signed-off-by: Jean Mertz --- crates/jp_printer/src/printer.rs | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/crates/jp_printer/src/printer.rs b/crates/jp_printer/src/printer.rs index 350e09e7..70d3496a 100644 --- a/crates/jp_printer/src/printer.rs +++ b/crates/jp_printer/src/printer.rs @@ -82,6 +82,15 @@ impl Printable for String { } } +impl Printable for &String { + fn into_task(self) -> PrintTask { + PrintTask { + content: self.to_owned(), + ..Default::default() + } + } +} + impl Printable for &str { fn into_task(self) -> PrintTask { PrintTask { @@ -301,17 +310,24 @@ impl std::fmt::Write for PrinterWriter<'_> { } } -impl std::io::Write for PrinterWriter<'_> { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - let s = std::str::from_utf8(buf).map_err(std::io::Error::other)?; +impl io::Write for PrinterWriter<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { + let s = std::str::from_utf8(buf).map_err(io::Error::other)?; self.write_str(s) - .map_err(std::io::Error::other) - .map(|()| buf.len()) + .map_err(io::Error::other) + .map(|()| s.len()) } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) + fn flush(&mut self) -> io::Result<()> { + let (tx, rx) = mpsc::channel(); + self.printer + .tx + .send(Command::Flush(tx)) + .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "printer shutdown"))?; + + rx.recv() + .map_err(|_| io::Error::other("failed to receive flush signal")) } }