Bounded reader over a local file or an in-memory binary.
Reads that ask for more than max_bytes fail with
reason: :allocation_limit before any bytes are copied into a new binary
of that size. Reads past the end fail with reason: :truncated.
File sources hold an open file descriptor. Call close/1 when finished.
The struct does not print file bytes.
Summary
Functions
Close a file source and return the closed struct.
Open a local file or an in-memory binary.
Read length bytes at offset.
Byte length of the source.
Types
@type t() :: %CRAM.Source{ closed: boolean(), data: binary() | nil, fd: :file.fd() | nil, kind: :file | :binary, path: Path.t() | nil, size: non_neg_integer() }
An open byte source.
:kind—:fileor:binary:path— filesystem path for a file, otherwisenil:data— the bytes of a binary source, otherwisenil:fd— file descriptor, ornilafter close and for a binary:size— byte length:closed— true afterclose/1iex> {:ok, source} = CRAM.Source.open({:binary, "CRAM"}) iex> source.kind :binary
Functions
Close a file source and return the closed struct.
Returns {:ok, source}. Closing a binary source marks it closed and does
not free a descriptor. Closing again returns the same shape and does not
raise. Later read/4 calls on the returned struct fail with reason: :closed.
iex> {:ok, source} = CRAM.Source.open({:binary, "CRAM"})
iex> {:ok, closed} = CRAM.Source.close(source)
iex> closed.closed
true
@spec open(Path.t() | {:file, Path.t()} | {:binary, iodata()}) :: {:ok, t()} | {:error, CRAM.Error.t()}
Open a local file or an in-memory binary.
source is a path, {:file, path}, or {:binary, iodata}. Returns
{:ok, source}. A missing file is {:error, %CRAM.Error{reason: :io}}.
This function does not raise.
iex> {:ok, source} = CRAM.Source.open({:binary, "CRAM"})
iex> CRAM.Source.size(source)
4
@spec read(t(), non_neg_integer(), non_neg_integer(), non_neg_integer()) :: {:ok, binary()} | {:error, CRAM.Error.t()}
Read length bytes at offset.
max_bytes defaults to 16 MiB and is optional. All three numbers must be
non-negative integers. Returns {:ok, binary} or {:error, %CRAM.Error{}}.
reason: :allocation_limit—lengthis abovemax_bytes. Nothing of that size is allocatedreason: :truncated— the span passes the end of the sourcereason: :invalid_range— an argument is negative or not an integerreason: :closed—close/1was already calledreason: :io— the file read failed
iex> {:ok, source} = CRAM.Source.open({:binary, "CRAM"})
iex> CRAM.Source.read(source, 0, 4)
{:ok, "CRAM"}
iex> {:error, error} = CRAM.Source.read(source, 0, 3, 2)
iex> error.reason
:allocation_limit
iex> {:ok, closed} = CRAM.Source.close(source)
iex> {:error, closed_error} = CRAM.Source.read(closed, 0, 1)
iex> closed_error.reason
:closed
@spec size(t()) :: non_neg_integer()
Byte length of the source.
This does not read the bytes and does not change when the source is closed.
iex> {:ok, source} = CRAM.Source.open({:binary, "CRAM"})
iex> CRAM.Source.size(source)
4