Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 63 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(());
Expand Down Expand Up @@ -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.
Expand Down