diff --git a/src/lib.rs b/src/lib.rs index 9e6371f..3ff6a08 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1135,8 +1135,45 @@ impl BufferWriter { /// Prints the contents of the given buffer. /// /// It is safe to call this from multiple threads simultaneously. In - /// particular, all buffers are written atomically. No interleaving will + /// particular, all buffers are written automically. No interleaving will /// occur. + /// + /// Note that this method does not explicitly flush the underlying stream. The output + /// uses line buffering by default, which means content will only be flushed when a + /// newline character is encountered or when the internal buffer is full. To ensure + /// immediate output, especially for content without newlines, use the `flush` method + /// after calling `print`. + /// + /// # Example + /// + /// Content with newlines is automatically flushed: + /// ``` + /// use termcolor::{BufferWriter, ColorChoice}; + /// use std::io::Write; + /// + /// # fn main() -> std::io::Result<()> { + /// let bufwtr = BufferWriter::stdout(ColorChoice::Never); + /// let mut buffer = bufwtr.buffer(); + /// writeln!(buffer, "This will appear immediately\n")?; // Contains newline + /// bufwtr.print(&buffer)?; // No need for a manual flush + /// # Ok(()) + /// # } + /// ``` + /// + /// Contents without newlines need explicit flushing: + /// ``` + /// use termcolor::{BufferWriter, ColorChoice}; + /// use std::io::Write; + /// + /// # fn main() -> std::io::Result<()> { + /// let bufwtr = BufferWriter::stdout(ColorChoice::Never); + /// let mut buffer = bufwtr.buffer(); + /// write!(buffer, "This needs manual flush")?; // No newline + /// bufwtr.print(&buffer)?; + /// bufwtr.flush()?; // Ensure content appears immediately + /// # Ok(()) + /// # } + /// ``` pub fn print(&self, buf: &Buffer) -> io::Result<()> { if buf.is_empty() { return Ok(()); @@ -1166,6 +1203,31 @@ impl BufferWriter { self.printed.store(true, Ordering::Relaxed); Ok(()) } + + /// Flushes the underlying stream. + /// + /// This ensures any buffered content is written to the terminal immediately, + /// particularly useful for content without newlines that would otherwise + /// remain in the line buffer. + /// + /// # Examples + /// + /// ``` + /// use termcolor::{BufferWriter, ColorChoice}; + /// use std::io::Write; + /// + /// # fn main() -> std::io::Result<()> { + /// let bufwtr = BufferWriter::stdout(ColorChoice::Never); + /// let mut buffer = bufwtr.buffer(); + /// write!(buffer, "Will appear immediately")?; // No need for a newline + /// bufwtr.print(&buffer)?; + /// bufwtr.flush()?; // Force the content to appear + /// # Ok(()) + /// # } + /// ``` + pub fn flush(&self) -> io::Result<()> { + self.stream.get_ref().lock().flush() + } } /// Write colored text to memory.