netstring

A library for encoding and decoding netstrings.

Netstrings are a simple format for encoding byte strings with explicit lengths, using the format <length>:<data>,. For example, <<"hello">> encodes as <<"5:hello,">>.

Types

Errors that can occur when decoding a netstring.

pub type NetstringError {
  NeedMore
  InvalidFormat(String)
}

Constructors

  • NeedMore

    The buffer doesn’t contain a complete netstring yet. Buffer more data and call decode again.

  • InvalidFormat(String)

    The input is malformed. The String describes what was wrong.

Values

pub fn decode(
  buffer: BitArray,
) -> Result(#(BitArray, BitArray), NetstringError)

Decodes a netstring from a BitArray buffer.

On success, returns both the decoded data and any remaining bytes in the buffer. This makes it suitable for streaming protocols where multiple netstrings may arrive in a single buffer, or where data arrives incrementally.

Examples

netstring.decode(<<"5:hello,">>)
// -> Ok(#(<<"hello">>, <<>>))

// Multiple netstrings - remaining bytes returned for next decode
netstring.decode(<<"5:hello,5:world,">>)
// -> Ok(#(<<"hello">>, <<"5:world,">>))

// Incomplete data - buffer more and try again
netstring.decode(<<"5:hel">>)
// -> Error(NeedMore)

// Malformed input
netstring.decode(<<"hello">>)
// -> Error(InvalidFormat("Invalid character in length"))
pub fn encode(data: BitArray) -> BitArray

Encodes a BitArray as a netstring.

Examples

netstring.encode(<<"hello">>)
// -> <<"5:hello,">>

netstring.encode(<<>>)
// -> <<"0:,">>
pub fn encode_tree(
  data: bytes_tree.BytesTree,
) -> bytes_tree.BytesTree

Encodes a BytesTree as a netstring, returning a BytesTree.

Examples

bytes_tree.from_string("hello")
|> netstring.encode_tree
|> bytes_tree.to_bit_array
// -> <<"5:hello,">>
Search Document