Blazing fast two-way serialization between JSON and binary. Creates a payload smaller than JSON by using a shared schema, and performs faster than JSON.parse and JSON.stringify.
Currently these data types are supported: [utf8, ascii, int8, uint8, int16, uint16, int32, uint32, float, double]
Planned to support: [array, object, boolean, number]
Values can be denoted as nullable by appending a question mark: { title: 'ascii?' }
import BinarySchema from 'binary-schema';
const characterSchema = new BinarySchema({
name: 'ascii',
title: 'ascii?',
race: 'uint8',
class: 'uint8',
maxHp: 'uint32'
});
const binary = characterSchema.pack({
name: 'osom',
race: 3,
class: 7,
maxHp: 3500
});
// binary === <Buffer 07 00 00 0d ac 00 04 6f 73 6f 6d 03 00>
// binary.length === 13
const json = characterSchema.unpack(binary);
// json === { class: 7, maxHp: 3500, name: 'osom', race: 3 }
// JSON.stringify(json).length === 47
If you're interpreting packets, it may be useful to start reading from an offset. For instance, the first byte may contain a UInt8 representing the type of packet you're receiving.
const schemas = {
0x01: new BinarySchema({ direction: 'uint8' }), // Move
0x02: new BinarySchema({ enemyId: 'ascii' }) // Attack
};
socket.on('data', (message) => {
const commandId = message.readUInt8(0);
const body = schemas[commandId](message, 1);
})
class BinarySchema {
constructor(template) {
// Compiles pack and unpack methods from the template.
}
pack(json, offset) {
// Returns a new buffer containing the packed json.
// If offset is specified, [offset] number of undesignated bytes will
// precede the packed json (extending the length of the buffer).
}
unpack(buffer, offset) {
// Returns the json unpacked from the passed buffer.
// If offset is specified, unpack will begin reading from that offset.
}
}