Meshcore.Util (Meshcore v0.1.0)

Copy Markdown View Source

Small binary/encoding helpers shared across the library.

Destinations

The Python library distinguishes bytes and str destinations. Elixir binaries are both, so to_key/2 applies this rule: a binary made only of hex digits and at least 2 * prefix_length characters long is treated as a hex string, anything else as raw bytes. A contact map (anything with a :public_key hex string) is accepted as well.

Summary

Functions

Like utf8/1 but also removes every NUL character.

Lower-case hex encoding.

Returns true if bin is a non-empty, even-length string of hex digits.

Current Unix time in seconds.

Reads a random unsigned 32 bit integer in 1..0xFFFFFFFF.

Little-endian signed integer encoding.

SHA-256 digest.

Splits an encoded path-length byte into {hash_mode, hop_count}.

Removes leading and trailing NUL bytes.

Normalises raw bytes: accepts a binary (taken verbatim) or {:hex, string}.

Resolves a destination (raw key, hex key or contact map) into prefix_length raw key bytes.

Little-endian unsigned integer encoding.

Decodes UTF-8, silently dropping invalid bytes (Python's decode("utf-8", "ignore")).

Types

destination()

@type destination() ::
  binary() | %{:public_key => String.t(), optional(any()) => any()}

Functions

cstr(bin)

@spec cstr(binary()) :: String.t()

Like utf8/1 but also removes every NUL character.

hex(bin)

@spec hex(binary()) :: String.t()

Lower-case hex encoding.

hex?(bin)

@spec hex?(binary()) :: boolean()

Returns true if bin is a non-empty, even-length string of hex digits.

now()

@spec now() :: non_neg_integer()

Current Unix time in seconds.

random_u32()

@spec random_u32() :: pos_integer()

Reads a random unsigned 32 bit integer in 1..0xFFFFFFFF.

s(value, bytes)

@spec s(integer(), pos_integer()) :: binary()

Little-endian signed integer encoding.

sha256(data)

@spec sha256(iodata()) :: binary()

SHA-256 digest.

split_path_len(plen)

@spec split_path_len(0..255) :: {integer(), integer()}

Splits an encoded path-length byte into {hash_mode, hop_count}.

255 means "flood" and yields {-1, -1}.

strip_nul(bin)

@spec strip_nul(binary()) :: binary()

Removes leading and trailing NUL bytes.

to_bytes(bin)

@spec to_bytes(binary() | {:hex, String.t()}) :: binary()

Normalises raw bytes: accepts a binary (taken verbatim) or {:hex, string}.

to_key(dst, prefix_length \\ 6)

@spec to_key(destination(), pos_integer()) :: binary()

Resolves a destination (raw key, hex key or contact map) into prefix_length raw key bytes.

Raises ArgumentError for malformed input (the equivalent of Python's ValueError).

u(value, bytes)

@spec u(integer(), pos_integer()) :: binary()

Little-endian unsigned integer encoding.

utf8(bin)

@spec utf8(binary()) :: String.t()

Decodes UTF-8, silently dropping invalid bytes (Python's decode("utf-8", "ignore")).