msgpuck
v0.7.6
Published
A fast and memory-efficient MessagePack serialization library
Downloads
3
Maintainers
Readme
msgpuck
A fast and memory-efficient MessagePack serialization library.
Features
- Fully compliant with the latest MessagePack specification
- Supports low-level methods
- Supports safe/big 64-bit integers handling
- Supports custom Extension Types (Serialization Codecs)
- Fully tested, including V8 JIT optimizations
Future works (not implemented yet)
- Decoder low-level methods
- Zero-copy stream handler
- Web browsers, WebAssembly, Bundler plugins
Installation
# npm
npm install msgpuck
# yarn
yarn add msgpuck
Usage
Encoding
To encode values you can either use an instance of Encoder
:
const { Encoder } = require('msgpuck');
const encoder = new Encoder();
...
encoder.encode(value); // string(encoded values)
A list of all low-level encoder methods:
encoder.encodeNil(); // MP nil
encoder.encodeBool(true); // MP bool
encoder.encodeInt(42); // MP int
encoder.encodeBigInt(42n); // MP int64
encoder.encodeFloat(Math.PI); // MP float
encoder.encodeStr('foo'); // MP str
encoder.encodeBin(Buffer.from([0x2a])); // MP bin
encoder.encodeArray([1, 2]); // MP array
encoder.encodeObject({ key: 'value' }); // MP map
encoder.encodeMap(new Map([[1, 2]]); // MP map
encoder.encodeExt(1, '\x2a'); // MP ext
Encoding options
The Encoder
object supports options for fine-tuning the encoding process (defaults are in bold):
| Name | Description | | -------------------- | ---------------------------------------------------------- | | float: '64' | Forces floats to be encoded as 64-bits MessagePack floats | | float: '32' | Forces floats to be encoded as 32-bits MessagePack floats | | float: 'auto' | Detects MessagePack floats type automatically | | bufferMinLen: 15 | The minimum length of the string to use the Buffer | | codecs: false | An array of codecs |
Decoding
To decode data (buffer) you can either use an instance of Decoder
:
const { Decoder } = require('msgpuck');
const decoder = new Decoder();
...
decoder.decode(buffer);
Extensions
To define application-specific types use the Ext
class:
const { Encoder, Decoder, Ext } = require('msgpuck');
const encoded = new Encoder().encode(Ext.make(42, '\x2a'));
const buffer = Buffer.from(encoded, 'binary');
const ext = new Decoder().decode(buffer);
console.log(ext.type === 42); // bool(true)
console.log(ext.data === '\x2a'); // bool(true)
Tests
Run tests as follows:
npm run test
License
Copyright © 2018-present Alex Masterov <[email protected]>
msgpuck is licensed under MIT and can be used for any personal or commercial project.