bytewise-core
A binary serialization that allows efficient comparison of certain useful data structures in a way that respects the typewise sort order.
This library defines a total order for well-structured keyspaces in key value stores. The ordering is a superset of the sorting algorithm defined by IndexedDB and the one defined by CouchDB. This serialization makes it easy to take advantage of the benefits of structured indexing in systems with fast but naïve binary indexing (key/value databases).
Order of Supported Structures
This package is a barebones kernel of bytewise, containing only the structures most often used to create structured keyspaces.
This is the top level order of the various structures that may be encoded:
null
false
true
Number
(numeric)Date
(time-wise)Buffer
, Uint8Array
(bit-wise)String
(character-wise)Array
(element-wise)Object
(element-wise, key/value pairs)undefined
Structured types like Array
and Object
may contain any supported structures, including nested Array
or Object
values.
Usage
encode
serializes any supported type and returns a Buffer
, or throws if an
unsupported structure is provided.
var assert = require('assert')
var bytewise = require('./')
var encode = bytewise.encode
assert.equal(encode(12345).toString('hex'), '4240c81c8000000000')
assert.equal(encode(-12345).toString('hex'), '41bf37e37fffffffff')
assert.equal(encode(-12345) + '', '41bf37e37fffffffff')
assert.equal(encode(1.2345) + '', '423ff3c083126e978d')
assert.equal(encode(-1.2345) + '', '41c00c3f7ced916872')
assert.equal(encode(-0) + '', '420000000000000000')
assert.equal(encode(0) + '', '420000000000000000')
assert.equal(encode('foo').toString('utf8'), 'pfoo')
assert.equal(encode('föo').toString('utf8'), 'pföo')
assert.equal(encode([ 'foo', 'bar' ]) + '', 'a070666f6f00706261720000')
assert.equal(encode([ 'foo' ]).toString('binary'), '\xa0pfoo\x00\x00')
assert.equal(encode([ [ 'foo', 10 ], 'bar' ]) + '', 'a0a070666f6f0042402400000000000000706261720000')
decode
parses a buffer and returns the structured data.
var decode = bytewise.decode
var key = 'a0a070666f6f0042402400000000000000706261720000'
assert.deepEqual(decode(new Buffer(key, 'hex')), [ [ 'foo', 10 ], 'bar' ])
assert.deepEqual(decode(key), [ [ 'foo', 10 ], 'bar' ])
Use Cases
Take a look at the bytewise library for an idea of what kind of stuff this could be useful for.
License
MIT