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 = vstructname: 'x' type: vstructDoubleBEname: 'y' type: vstructDoubleBEname: 'z' type: vstructDoubleBE//encode a object to get a buffervar buffer = vectorencodex: 93.1 y: 87.3 z: 10.39var v = vectordecodebuffer
var vstruct = require'varstruct'var VarIntProtobuf = require'varint'//codec for a sha256 hashvar SHA256 = vstructBuffer32var message = vstruct// the hash of the previous messagename: 'previous' type: SHA256// the hash of the author's public keyname: 'author' type: SHA256// an arbitary length buffername: 'message' type: vstructVarBufferVarIntProtobuf// hashes of related documents.name: 'attachments' type: vstructVarArrayvstructByte SHA256
varstruct uses abstract-encoding as interface and provides next types:
Create a codec with a fixed number of fields. If any subcodec has a variable length, then the new codec will as well.
If you want Big Endian, append
BE, for examlpe
Int16BE or add
LE for Little Endian.
64 bit ints are actually only 53 bit ints, but they will still be written to 8 bytes. (based on int53)
Create codec that encodes an array with fixed length.
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.
Create codec that encodes an array with fixed length and various types.
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, but must encode an integer.
Create a fixed length (in bytes) string codec.
Create a variable length string codec. This codec uses
VarBuffer (buffer will be created from string with given
Return a codec that will check value before encode and after decode.
checkValue should throw error if value is wrong.