msgpuck
TypeScript icon, indicating that this package has built-in type declarations

0.7.6 • Public • Published

msgpuck

npm GitHub license Build Status Coverage Status

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 <alex.masterow@gmail.com>

msgpuck is licensed under MIT and can be used for any personal or commercial project.

Package Sidebar

Install

npm i msgpuck

Weekly Downloads

1

Version

0.7.6

License

MIT

Unpacked Size

57.6 kB

Total Files

35

Last publish

Collaborators

  • asm