CRAM.Itf8 (cram v0.1.0)

Copy Markdown View Source

ITF-8 integer codec from CRAM v3 section 2.3.

An ITF-8 value is a signed 32-bit integer. The on-disk form stores the two's-complement bit pattern, so -1 is the unsigned value 0xFFFFFFFF and occupies five bytes. Encoding uses the shortest prefix that can hold that bit pattern, matching HTSlib.

Unused high bits in the five-byte tail are ignored on decode, which is what the specification describes ("only 4 lower bits used in the last byte").

Summary

Types

Why decode/1 rejected the bytes. :truncated means the prefix promised more bytes than binary contains.

Functions

Decode one ITF-8 integer from the front of binary.

Decode one ITF-8 integer or raise CRAM.Error.

Encode a signed 32-bit integer.

Encode a signed 32-bit integer or raise CRAM.Error.

Types

decode_error()

@type decode_error() :: :truncated

Why decode/1 rejected the bytes. :truncated means the prefix promised more bytes than binary contains.

Functions

decode(binary)

@spec decode(binary()) :: {:ok, integer(), binary()} | {:error, decode_error()}

Decode one ITF-8 integer from the front of binary.

Returns {:ok, value, rest}. value is a signed integer.

iex> CRAM.Itf8.decode(<<0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 1>>)
{:ok, -1, <<1>>}

iex> CRAM.Itf8.decode(<<>>)
{:error, :truncated}

decode!(binary)

@spec decode!(binary()) :: {integer(), binary()}

Decode one ITF-8 integer or raise CRAM.Error.

Returns {value, rest}. A short prefix raises CRAM.Error with reason: :truncated.

iex> CRAM.Itf8.decode!(<<0>>)
{0, <<>>}

iex> CRAM.Itf8.decode!(<<0x80>>)
** (CRAM.Error) cram: truncated: ITF-8 input ended early

encode(value)

@spec encode(integer()) :: {:ok, binary()} | {:error, :overflow}

Encode a signed 32-bit integer.

iex> CRAM.Itf8.encode(0)
{:ok, <<0>>}

iex> CRAM.Itf8.encode(-1)
{:ok, <<0xFF, 0xFF, 0xFF, 0xFF, 0x0F>>}

iex> CRAM.Itf8.encode(4_542_278)
{:ok, <<0xE0, 0x45, 0x4F, 0x46>>}

iex> CRAM.Itf8.encode(2_147_483_648)
{:error, :overflow}

encode!(value)

@spec encode!(integer()) :: binary()

Encode a signed 32-bit integer or raise CRAM.Error.

value must fit in a signed 32-bit integer. Success returns the binary. A value outside that range raises CRAM.Error with reason: :overflow.

iex> CRAM.Itf8.encode!(0)
<<0>>

iex> CRAM.Itf8.encode!(2_147_483_648)
** (CRAM.Error) cram: overflow: ITF-8 value is outside int32