Binary-parser-encoder
Note: This is a fork of binary-parser library. It is currently being proposed as a Pull-Request in that project.
Until the encoding feature is merged in baseline of original project, this branch is published under the name: binary-parser-encoder in npm.
Binary-parser is a parser/encoder builder for JavaScript that enables you to write efficient binary parsers/encoders in a simple and declarative manner.
It supports all common data types required to analyze a structured binary data. Binary-parser dynamically generates and compiles the parser and encoder code on-the-fly, which runs as fast as a hand-written parser/encoder (which takes much more time and effort to write). Supported data types are:
- Integers (8, 16, 32 and 64 bit signed and unsigned integers)
- Floating point numbers (32 and 64 bit floating point values)
- Bit fields (bit fields with length from 1 to 32 bits)
- Strings (fixed-length, variable-length and zero terminated strings with various encodings)
- Arrays (fixed-length and variable-length arrays of builtin or user-defined element types)
- Choices (supports integer keys)
- Pointers
- User defined types (arbitrary combination of builtin types)
Binary-parser was inspired by BinData and binary.
Quick Start
- Create an empty Parser object with
new Parser()
orParser.start()
. - Chain methods to build your desired parser and/or encoder. (See API for detailed document of each method)
- Call
Parser.prototype.parse
with aBuffer
/Uint8Array
object passed as an argument. - The parsed result will be returned as an object.
- Or call
Parser.prototype.encode
with an object passed as argument. - Encoded result will be returned as a
Buffer
object.
// Module importvar Parser = Parser; // Build an IP packet header Parservar ipHeader = ; // Prepare buffer to parse.var buf = Buffer; // Parse buffer and show resultconsole; var anIpHeader = version: 4 headerLength: 5 tos: 0 packetLength: 709 id: 37785 offset: 0 fragOffset: 0 ttl: 44 protocol: 6 checksum: 61336 src: 173 194 79 108 dst: 133 1 134 209 ; // Encode an IP header object and show result as hex stringconsole;
API
new Parser([options])
Create an empty parser object that parses nothing.
options
is an optional object to pass options to this declarative
parser.
smartBufferSize
The chunk size of the encoding (smart)buffer (when encoding is used) (default is 256 bytes).
parse(buffer)
Parse a Buffer
/Uint8Array
object buffer
with this parser and return the
resulting object. When parse(buffer)
is called for the first time, the
associated parser code is compiled on-the-fly and internally cached.
encode(obj)
Encode an Object
object obj
with this parser and return the resulting
Buffer
. When encode(obj)
is called for the first time, encoder code is
compiled on-the-fly and internally cached.
create(constructorFunction)
Set the constructor function that should be called to create the object
returned from the parse
method.
[u]int{8, 16, 32, 64}{le, be}(name[, options])
Parse bytes as an integer and store it in a variable named name
. name
should consist only of alphanumeric characters and start with an alphabet.
Number of bits can be chosen from 8, 16, 32 and 64. Byte-ordering can be either
l
for little endian or b
for big endian. With no prefix, it parses as a
signed number, with u
prefixed as an unsigned number. The runtime type
returned by the 8, 16, 32 bit methods is number
while the type
returned by the 64 bit is bigint
.
Note: [u]int64{be,le} methods only work if your runtime is node v12.0.0 or greater. Lower version will throw a runtime error.
var parser = // Signed 32-bit integer (little endian) // Unsigned 8-bit integer // Signed 16-bit integer (big endian) ; // signed 64-bit integer (big endian)
bit[1-32](name[, options])
Parse bytes as a bit field and store it in variable name
. There are 32
methods from bit1
to bit32
each corresponding to 1-bit-length to
32-bits-length bit field.
{float, double}{le, be}(name[, options])
Parse bytes as a floating-point value and stores it to a variable named
name
.
var parser = // 32-bit floating value (big endian) // 64-bit floating value (little endian) ;
string(name[, options])
Parse bytes as a string. name
should consist only of alpha numeric
characters and start with an alphabet. options
is an object which can have
the following keys:
encoding
- (Optional, defaults toutf8
) Specify which encoding to use. Supported encodings include"hex"
and all encodings supported byTextDecoder
.length
- (Optional) Length of the string. Can be a number, string or a function. Use number for statically sized arrays, string to reference another variable and function to do some calculation. Note: When encoding the string is padded with apadd
charecter to fit the length requirement.zeroTerminated
- (Optional, defaults tofalse
) If true, then this parser reads until it reaches zero (or the specifiedlength
). When encoding, a null character is inserted at end of the string (if the optionallength
allows it).greedy
- (Optional, defaults tofalse
) If true, then this parser reads until it reaches the end of the buffer. Will consume zero-bytes. (Note: has no effect on encoding function)stripNull
- (Optional, must be used withlength
) If true, then strip null characters from end of the string. (Note: When encoding, this will also set the defaultpadd
character to null instead of space)trim
- (Optional, default tofalse
) If true, then trim() (remove leading and trailing spaces) the parsed string.padding
- (Optional, Only used for encoding, default toright
) Ifleft
then the string will be right aligned (padding left withpadd
char or space) depending of thelength
optionpadd
- (Optional, Only used for encoding withlength
specified) A string from which first character (1 Byte) is used as a padding char if necessary (provided string length is less thanlength
option). Note: Only 'ascii' or utf8 < 0x80 are alowed. Note: The default padd character is space (or null whenstripNull
is used).
buffer(name[, options])
Parse bytes as a buffer. Its type will be the same as the input to
parse(buffer)
. name
should consist only of alpha numeric characters and
start with an alphabet. options
is an object which can have the following
keys:
clone
- (Optional, defaults tofalse
) By default,buffer(name [,options])
returns a new buffer which references the same memory as the parser input, but offset and cropped by a certain range. If this option is true, input buffer will be cloned and a new buffer referencing a new memory region is returned.length
- (eitherlength
orreadUntil
is required) Length of the buffer. Can be a number, string or a function. Use number for statically sized buffers, string to reference another variable and function to do some calculation.readUntil
- (eitherlength
orreadUntil
is required) If"eof"
, then this parser will read till it reaches the end of theBuffer
/Uint8Array
object. (Note: has no effect on encoding.) If it is a function, this parser will read the buffer until the function returns true.
array(name, options)
Parse bytes as an array. options
is an object which can have the following
keys:
type
- (Required) Type of the array element. Can be a string or an user defined Parser object. If it's a string, you have to choose from [u]int{8, 16, 32}{le, be}.length
- (eitherlength
,lengthInBytes
, orreadUntil
is required) Length of the array. Can be a number, string or a function. Use number for statically sized arrays.lengthInBytes
- (eitherlength
,lengthInBytes
, orreadUntil
is required) Length of the array expressed in bytes. Can be a number, string or a function. Use number for statically sized arrays.readUntil
- (eitherlength
,lengthInBytes
, orreadUntil
is required) If"eof"
, then this parser reads until the end of theBuffer
/Uint8Array
object. If function it reads until the function returns true. Note: When encoding, thebuffer
second parameter ofreadUntil
function is the buffer already encoded before this array. So no read-ahead is possible.encodeUntil
- a function (item, object), only used when encoding, that replaces thereadUntil
function when present and allow limit the number of encoded items by returning true based on item values or other object properies.
var parser = // Statically sized array // Dynamically sized array (references another variable) // Dynamically sized array (with some calculation) // Statically sized array // Dynamically sized array (references another variable) // Dynamically sized array (with some calculation) // Dynamically sized array (with stop-check on parsed item) // Use user defined parser object ;
choice([name,] options)
Choose one parser from multiple parsers according to a field value and store
its parsed result to key name
. If name
is null or omitted, the result of
the chosen parser is directly embedded into the current object. options
is
an object which can have the following keys:
tag
- (Required) The value used to determine which parser to use from thechoices
Can be a string pointing to another field or a function.choices
- (Required) An object which key is an integer and value is the parser which is executed whentag
equals the key value.defaultChoice
- (Optional) In case if the tag value doesn't match any ofchoices
, this parser is used.
var parser1 = ...;var parser2 = ...;var parser3 = ...; var parser = ;
Combining choice
with array
is an idiom to parse
TLV-based binary formats.
nest([name,] options)
Execute an inner parser and store its result to key name
. If name
is null
or omitted, the result of the inner parser is directly embedded into the
current object. options
is an object which can have the following keys:
type
- (Required) AParser
object.
pointer(name [,options])
Jump to offset
, execute parser for type
and rewind to previous offset.
Useful for parsing binary formats such as ELF where the offset of a field is
pointed by another field.
type
- (Required) Can be a string[u]int{8, 16, 32, 64}{le, be}
or an user defined Parser object.offset
- (Required) Indicates absolute offset from the beginning of the input buffer. Can be a number, string or a function.
saveOffset(name [,options])
Save the current buffer offset as key name
. This function is only useful
when called after another function which would advance the internal buffer
offset.
var parser = // this call advances the buffer offset by // a variable (i.e. unknown to us) number of bytes // this variable points to an absolute position // in the buffer // now, save the "current" offset in the stream // as the variable "currentOffset" // finally, use the saved offset to figure out // how many bytes we need to skip ... // the parser would continue here
seek(relOffset)
Move the buffer offset for relOffset
bytes from the current position. Use a
negative relOffset
value to rewind the offset. This method was previously
named skip(length)
. (Note: when encoding, the skipped bytes will be filled with zeros)
endianess(endianess)
Define what endianess to use in this parser. endianess
can be either
"little"
or "big"
. The default endianess of Parser
is set to big-endian.
var parser = // You can specify endianess explicitly // Or you can omit endianess (in this case, little-endian is used) ;
encoderSetOptions(opts)
Set specific options for encoding.
Current supported opts
object may contain:
- bitEndianess: true|false (default false) When true, tell the encoder to respect endianess BITs order, so that encoding is exactly the reverse of the parsing process for bits fields.
var parser = // Use BITs endianess for bits fields ;
namely(alias)
Set an alias to this parser, so there will be an opportunity to refer to it by
name in methods like .array
, .nest
and .choice
, instead of requirement
to have an instance of it.
Especially, the parser may reference itself:
var stop = ; var parser = // use 'self' to refer to the parser itself ; // 2// / \// 3 1// / | \ \// 1 0 2 0// / / \// 0 1 0// /// 0 var buffer = Buffer; parser;
For most of the cases there is almost no difference to the instance-way of referencing, but this method provides the way to parse recursive trees, where each node could reference the node of the same type from the inside.
Also, when you reference a parser using its instance twice, the generated code will contain two similar parts of the code included, while with the named approach, it will include a function with a name, and will just call this function for every case of usage.
Note: This style could lead to circular references and infinite recursion, to avoid this, ensure that every possible path has its end. Also, this recursion is not tail-optimized, so could lead to memory leaks when it goes too deep.
An example of referencing other patches:
// the line below registers the name 'self', so we will be able to use it in// `twoCells` as a referencevar parser = Parserstart; var stop = Parserstart; var twoCells = Parserstart ; parser; var buffer = Buffer; parser;
compile() and compileEncode()
Compile this parser/encoder on-the-fly and cache its result. Usually, there is no need
to call this method directly, since it's called when parse(buffer)
or encode(obj)
is
executed for the first time.
getCode() and getCodeEncode()
Dynamically generates the code for this parser/encoder and returns it as a string. Useful for debugging the generated code.
Common options
These options can be used in all parsers.
-
formatter
- Function that transforms the parsed value into a more desired form. formatter(value, obj, buffer, offset) → new value
wherevalue
is the value to be formatted,obj
is the current object being generated,buffer
is the buffer currently beeing parsed andoffset
is the current offset in that buffer.var parser =; -
encoder
- Function that transforms an object property into a more desired form for encoding. This is the opposite of the aboveformatter
function.
encoder(value) → new value
wherevalue
is the value to be encoded (de-formatted) andobj
is the object currently being encoded.var parser =; -
assert
- Do assertion on the parsed result (useful for checking magic numbers and so on). Ifassert
is astring
ornumber
, the actual parsed result will be compared with it with===
(strict equality check), and an exception is thrown if they mismatch. On the other hand, ifassert
is a function, that function is executed with one argument (parsed result) and if it returns false, an exception is thrown.// simple maginc number validationvar ClassFile = Parserstart;// Doing more complex assertion with a predicate functionvar parser =;
Examples
See example/
for real-world examples.
Support
Please report issues to the issue tracker if you have any difficulties using this module, found a bug, or request a new feature. Pull requests are welcomed.