69 lines
1.9 KiB
JavaScript
69 lines
1.9 KiB
JavaScript
|
'use strict';
|
|||
|
|
|||
|
String.prototype.removeEndNullBytes = function() {
|
|||
|
return this.replace(/\0+$/g, '');
|
|||
|
}
|
|||
|
String.prototype.removeStartNullBytes = function() {
|
|||
|
return this.replace(/^\0+/g, '');
|
|||
|
}
|
|||
|
|
|||
|
var pluie =
|
|||
|
{
|
|||
|
bin :
|
|||
|
{
|
|||
|
enc : new TextEncoder("utf-8"),
|
|||
|
|
|||
|
dec : new TextDecoder("utf-8", {fatal: true}),
|
|||
|
|
|||
|
intFromBytes : function(bytes)
|
|||
|
{
|
|||
|
// Big Endian
|
|||
|
for (var i = value = 0, lim = bytes.length; i < lim; i++) {
|
|||
|
value = value * 256 + bytes[i];
|
|||
|
}
|
|||
|
return value;
|
|||
|
},
|
|||
|
|
|||
|
bytesFromInt : function(value, size)
|
|||
|
{
|
|||
|
var bytes = new Uint8Array(size);
|
|||
|
while (value) {
|
|||
|
bytes.set([value & 255], --size);
|
|||
|
value >>= 8;;
|
|||
|
}
|
|||
|
return bytes;
|
|||
|
},
|
|||
|
|
|||
|
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;
|
|||
|
},
|
|||
|
|
|||
|
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;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
module.exports = pluie.bin;
|