io
BufferedReader

BufferedReader

Mojo struct 🡭

BufferedReader

@memory_only
struct BufferedReader

BufferedReader for readying lines and bytes from a file in a buffered way.

Example

from extramojo.io.buffered import BufferedReader

fn read_bytes(read file: String) raises -> List[UInt8]:
    var fh = open(file, "r")
    var reader = BufferedReader(fh^, buffer_capacity=50)
    var buffer = List[UInt8](capacity=125)
    for _ in range(0, 125):
        buffer.append(0)
    var found_file = List[UInt8]()

    # Read bytes from the buf reader, copy to found
    var bytes_read = 0
    while True:
        bytes_read = reader.read_bytes(buffer)
        if bytes_read == 0:
            break
        found_file.extend(buffer[0:bytes_read])
    return found_file

Fields

  • fh (FileHandle): The internal filehandle to read from.
  • buffer (UnsafePointer[SIMD[uint8, 1]]): The internal buffer.
  • file_offset (Int): Current offset into the file.
  • buffer_offset (Int): Current offset into the buffer.
  • buffer_capacity (Int): Total capacity of the buffer.
  • buffer_len (Int): Total filled capacity of the buffer.

Implemented traits

AnyType, Movable, UnknownDestructibility

Methods

 

__init__

fn __init__(out self, var fh: FileHandle, buffer_capacity: Int = 131072)

Create a BufferedReader. Args:

  • fh (FileHandle): The filehandle to read from.
  • buffer_capacity (Int): The size of the buffer to use.
  • self (Self)

Returns:

Self

Raises:

__moveinit__

@staticmethod
fn __moveinit__(out self, var existing: Self)

Details Args:

  • existing (Self)
  • self (Self)

Returns:

Self

__del__

fn __del__(var self)

Details Args:

  • self (Self)

__enter__

fn __enter__(var self) -> Self

Details Args:

  • self (Self)

Returns:

Self

read_bytes

fn read_bytes(mut self, mut buffer: List[SIMD[uint8, 1]]) -> Int

Read up to len(buffer) bytes. Args:

  • self (Self)
  • buffer (List): The buffer to read into. The len of the buffer determines how many bytes will be read.

Returns:

Int: This returns the number of bytes read. If the number of bytes read is less then len(buffer) then EOF has been reached.

Raises:

read_until

fn read_until(mut self, mut buffer: List[SIMD[uint8, 1]], char: UInt = UInt(10)) -> Int

Fill the given line_buffer until the given char is hit, or EOF. Note: the callee is responsible for clearing (or not) the buffer between calls to read_until.

Args:

  • self (Self)
  • buffer (List): The buffer to filled with any bytes found before char is hit.
  • char (UInt): The character to use as the terminator.

Returns:

Int: The number of bytes read.

Raises: