netstring

Package Version Hex Docs

A Gleam library for encoding and decoding netstrings - a simple format for encoding byte strings with explicit lengths.

Installation

gleam add netstring

Usage

Encoding

import netstring

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

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

// Works with arbitrary binary data
netstring.encode(<<0, 255, 128>>)
// -> <<"3:", 0, 255, 128, ",">>

Decoding

The decoder returns both the decoded data and any remaining bytes, making it suitable for streaming protocols:

import netstring

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

// Multiple netstrings in a buffer
netstring.decode(<<"5:hello,5:world,">>)
// -> Ok(#(<<"hello">>, <<"5:world,">>))

Handling Incomplete Data

When data is incomplete, the decoder returns NeedMore - buffer more data and try again:

import netstring.{NeedMore}

netstring.decode(<<"5:hel">>)
// -> Error(NeedMore)

Documentation

Full API documentation is available at hexdocs.pm/netstring.

Search Document