Skip to content

BufferedWriter

Mojo struct 🡭

@memory_only
struct BufferedWriter[W: WriterBackend]

Buffered writer for efficient byte writing.

Works with any WriterBackend (FileWriter, MemoryWriter, GZWriter). Maintains an internal buffer and flushes automatically when full or on explicit flush() call.

  • W (WriterBackend)
  • writer (W)

AnyType, ImplicitlyDestructible, Movable, Writer

def __init__(out self, var writer: W, capacity: Int = 262144)

Initialize BufferedWriter with a Writer backend.

Args:

  • writer (W): Writer backend (FileWriter, MemoryWriter, or GZWriter).
  • capacity (Int): Size of the write buffer in bytes.
  • self (Self)

Returns:

Self

Raises:

Error: If capacity is invalid.

def __del__(deinit self)

Destructor: flush buffer.

Args:

  • self (Self)
def capacity(self) -> Int

Return the buffer capacity.

Args:

  • self (Self)

Returns:

Int

def available_space(self) -> Int

Return available space in buffer.

Args:

  • self (Self)

Returns:

Int

def bytes_written(self) -> Int

Return total bytes written to file.

Args:

  • self (Self)

Returns:

Int

def write_bytes(mut self, data: Span[Byte, data.origin])

Write bytes from a Span to the buffer, flushing if needed.

This is the primary entry point; it supports views like List slices and other contiguous byte buffers without copying.

Args:

  • self (Self)
  • data (Span)

Raises:

def write_bytes(mut self, data: List[Byte])

Write bytes from a List to the buffer, flushing if needed.

Kept for backward compatibility; forwards to the Span overload.

Args:

  • self (Self)
  • data (List)

Raises:

Error: If writing fails.

def write_string(mut self, string: StringSlice[string.origin])

Write a StringSlice to this Writer. Required by the builtin Writer trait.

Args:

  • self (Self)
  • string (StringSlice)
def write[*Ts: Writable](mut self, *args: *Ts)

Write a sequence of Writable arguments. Required by the builtin Writer trait.

Parameters:

  • *Ts (Writable)

Args:

  • self (Self)
  • *args (*Ts)
def flush(mut self)

Flush the buffer to disk.

Ensures all buffered data is written to the file.

Args:

  • self (Self)

Raises: