Compact encoding

A series of binary encoders/decoders for building small and fast parsers and serializers.

GitHub (Compact-Encoding)

Installation

Install with npm:

npm install compact-encoding

Encoder API

state()

An object with the keys{ start, end, buffer, cache }.

Users can also get a blank state object usingcenc.state().

const cenc = require('compact-encoding')
const state = cenc.state()

enc.preencode(state, val)

Performs a fast preencode dry-run that only sets state.end. Use this to figure out how big the buffer needs to be.

const cenc = require('compact-encoding')

const state = cenc.state()

// use preencode to figure out how big a buffer is needed
cenc.uint.preencode(state, 42)
cenc.string.preencode(state, 'hi')

console.log(state) // { start: 0, end: 4, buffer: null, cache: null }

enc.encode(state, val)

Encodes val into state.buffer at position state.start and updates state.start to point after the encoded value when done.

state.buffer = Buffer.allocUnsafe(state.end)

// then use encode to actually encode it to the buffer
cenc.uint.encode(state, 42)
cenc.string.encode(state, 'hi')

val = enc.decode(state)

Decodes a value from state.buffer as position state.startand updates state.start to point after the decoded value when done in the buffer.

// to decode it simply use decode instead

state.start = 0
cenc.uint.decode(state) // 42
cenc.string.decode(state) // 'hi'

Helpers

To encode to a buffer or decode from one, use the encode and decode helpers to reduce boilerplate.

const buf = cenc.encode(cenc.bool, true)
const bool = cenc.decode(cenc.bool, buf)

Bundled encodings

The following encodings are bundled as they are primitives that can be used to build others on top.

Feel free to make a PR to add more encodings that are missing.

Last updated