pluie-bin/lib/bin.js
2016-12-19 00:39:08 +01:00

97 lines
3.1 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

module.exports = function (ns) {
require('./encoder')(ns);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String.prototype.removeEndNullBytes = function() {
return this.replace(/\0+$/g, '');
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String.prototype.removeStartNullBytes = function() {
return this.replace(/^\0+/g, '');
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ns.enc = new ns.TextEncoder("utf-8");
ns.dec = new ns.TextDecoder("utf-8", {fatal: true});
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ns.intFromBytes = function(bytes)
{
var value = null;
if (bytes!=null && bytes.length > 0) {
// Big Endian
for (var i = value = 0, lim = bytes.length; i < lim; i++) {
value = value * 256 + bytes[i];
}
}
return value;
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ns.bytesFromInt = function(value, size)
{
var bytes = new Uint8Array(size);
while (value) {
bytes.set([value & 255], --size);
value >>= 8;
}
return bytes;
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ns.pack = function(size, type, value)
{
var packed = null
if (type == 'n' || type == 'N') {
// js int max on 32 signed bits
if (value >= 0 && value <= 2147483647) {
packed = this.bytesFromInt(value, type == 'n' ? 2 : 4);
}
}
else if (type == 'a') {
packed = new Uint8Array(size);
packed.set(this.enc.encode(value), 0);
}
return packed;
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ns.unpack = function(size, type, bytes)
{
var unpacked = null
if (type == 'n' || type == 'N') {
var selByte = bytes.slice(0, size*(type == 'n' ? 2 : 4));
unpacked = this.intFromBytes(selByte);
}
else if (type == 'a') {
unpacked = this.dec.decode(bytes.slice(0, size)).removeEndNullBytes();
}
return unpacked;
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ns.mergeBuffers = function(bufferArray)
{
var maxLength = 0;
for(var i=0, lim=bufferArray.length; i < lim; i++) {
if (bufferArray[i] != null) {
maxLength += bufferArray[i].byteLength;
}
}
var tmp = new Uint8Array(maxLength);
for(var i=0, pos = 0, lim=bufferArray.length; i < lim; i++) {
if (bufferArray[i] != null) {
tmp.set(new Uint8Array(bufferArray[i]), pos);
pos += bufferArray[i].byteLength;
}
}
return tmp;
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ns.getBuffer = function(array, size)
{
var buffer = new Uint8Array(!size ? array.length : size);
buffer.set(new Uint8Array(array), 0);
return buffer;
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
require('./file')(ns);
return ns;
}