68 lines
1.2 KiB
JavaScript
68 lines
1.2 KiB
JavaScript
// codec-base.js
|
|
|
|
var IS_ARRAY = require("isarray");
|
|
|
|
exports.createCodec = createCodec;
|
|
exports.install = install;
|
|
exports.filter = filter;
|
|
|
|
var Bufferish = require("./bufferish");
|
|
|
|
function Codec(options) {
|
|
if (!(this instanceof Codec)) return new Codec(options);
|
|
this.options = options;
|
|
this.init();
|
|
}
|
|
|
|
Codec.prototype.init = function() {
|
|
var options = this.options;
|
|
|
|
if (options && options.uint8array) {
|
|
this.bufferish = Bufferish.Uint8Array;
|
|
}
|
|
|
|
return this;
|
|
};
|
|
|
|
function install(props) {
|
|
for (var key in props) {
|
|
Codec.prototype[key] = add(Codec.prototype[key], props[key]);
|
|
}
|
|
}
|
|
|
|
function add(a, b) {
|
|
return (a && b) ? ab : (a || b);
|
|
|
|
function ab() {
|
|
a.apply(this, arguments);
|
|
return b.apply(this, arguments);
|
|
}
|
|
}
|
|
|
|
function join(filters) {
|
|
filters = filters.slice();
|
|
|
|
return function(value) {
|
|
return filters.reduce(iterator, value);
|
|
};
|
|
|
|
function iterator(value, filter) {
|
|
return filter(value);
|
|
}
|
|
}
|
|
|
|
function filter(filter) {
|
|
return IS_ARRAY(filter) ? join(filter) : filter;
|
|
}
|
|
|
|
// @public
|
|
// msgpack.createCodec()
|
|
|
|
function createCodec(options) {
|
|
return new Codec(options);
|
|
}
|
|
|
|
// default shared codec
|
|
|
|
exports.preset = createCodec({preset: true});
|