encode/decode variable binary structures
encode/decode variable binary structures.
This module makes creating binary formats easy. It supports both fixed length structures (like classic c structs), and variable (usually length delemited) structures.
var vstruct = require'varstruct'//create a vector codec.var vector = vstructx: vstructDoubleBEy: vstructDoubleBEz: vstructDoubleBE//encode a object to get a buffervar buffer = vectorencodex: 93.1 y: 87.3 z: 10.39var v = vectordecodebuffer
var vstruct = require'varstruct'//codec for a sha256 hashvar sha256 = vstructbuffer32var message = vstruct//the hash of the previous messageprevious: sha256//the hash of the author's public keyauthor: sha256//an arbitary length buffermessage: vstructvarbuffervstructvarint//hashes of related documents.attachments:vstructvararrayvstructbyte sha256
every thing in varstruct implements a
value as binary. If
buffer is not provided,
return a new buffer. If
buffer is provided, write the encoding
buffer starting at
value is the wrong type to be encoded, or there is not enough room
offset then throw an error.
encode is called, a codec must set
encode.bytes to be
the number of bytes used to encode that value.
value encoded in
buffer starting at
offset defaults to
0 if not provided.
Return the new decoded value.
decode must throw an error if
buffer is not long enough
to contain a valid value after
decode is called, a codec must set
decode.bytes to be
the number of bytes consumed.
if this codec always encodes the same length,
set an integer property
length is not provided,
codec.dynamicLength must be.
return the number of bytes it would take to encode
encodingLength is not provided,
codec.length must be.
number codecs, by default Big Endian.
If you want Little Endian, append
LE, for examlpe
Use of Big Endian is encouraged. You can also append
BE to be
more explicitly Big Endian.
64 bit ints are actually only 53 bit ints, but they will still be written to 8 bytes. taken from int53
return a codec that errors if the value is not within a range.
variable sized integers, this is just reexporting chrisdickinson/varint
create a codec with a fixed number of fields. If any subcodec has a variable length, then the new codec will as well.
create a fixed length buffer codec.
create a variable length buffer codec. This will first write out the length of the
value buffer and then the value buffer itself. The
lengthCodec may be
variable length itself (i.e. a varint), but must encode an integer.
create a variable length codec that encodes an array of items.
itemCodec may be any varstruct compatible codec, including a vararray.
As long as it can encode very element in the array.
lengthCodec must encode an integer.