l@271: // t is a binpack typename l@271: var sizeOfType = function(t) { l@271: // unsigned are the same length as signed l@271: if(t[0] === 'U') { l@271: t = t.slice(1); l@271: } l@271: l@271: return { l@271: 'Float32' : 4, l@271: 'Float64' : 8, l@271: 'Int8' : 1, l@271: 'Int16' : 2, l@271: 'Int32' : 4, l@271: 'Int64' : 8 l@271: }[t]; l@271: }; l@271: l@271: var endianConv = function(e, t) { l@271: // node doesn't define 8 bit endianness l@271: if(t[t.length - 1] === '8') l@271: return ''; l@271: l@271: if(e === 'big') { l@271: return 'BE'; l@271: } l@271: return 'LE'; l@271: }; l@271: l@271: var addBindings = function(binpackTypename, nodeTypename){ l@271: if(!(typeof nodeTypename !== "undefined" && nodeTypename !== null)) { l@271: nodeTypename = binpackTypename; l@271: } l@271: module.exports['pack' + binpackTypename] = function(num, endian){ l@271: b = new Buffer(sizeOfType(binpackTypename)); l@271: b['write' + nodeTypename + endianConv(endian, binpackTypename)](num, 0, true); l@271: return b; l@271: } l@271: l@271: module.exports['unpack' + binpackTypename] = function(buff, endian){ l@271: return buff['read' + nodeTypename + endianConv(endian, binpackTypename)](0); l@271: } l@271: } l@271: l@271: var addIntBindings = function(n) { l@271: addBindings("Int" + n); l@271: addBindings("UInt" + n); l@271: } l@271: l@271: addIntBindings(8); l@271: addIntBindings(16); l@271: addIntBindings(32); l@271: l@271: twoToThe32 = Math.pow(2, 32); l@271: l@271: // 64 bit bindings require special care l@271: var read64 = function(unsigned){return function(buff, endian){ l@271: var e = endianConv(endian, ''); l@271: var u = unsigned ? 'U' : ''; l@271: var low, high; l@271: if(e === 'LE') { l@271: low = buff.readUInt32LE(0); l@271: high = buff['read' + u + 'Int32LE'](4); l@271: } else { l@271: low = buff.readUInt32BE(4); l@271: high = buff['read' + u + 'Int32BE'](0); l@271: } l@271: return high * twoToThe32 + low; l@271: };}; l@271: l@271: var write64 = function(unsigned){return function(num, endian){ l@271: var e = endianConv(endian, ''); l@271: var u = unsigned ? 'U' : ''; l@271: var b = new Buffer(8); l@271: var high = Math.floor(num / twoToThe32); l@271: var low = Math.floor(num - high * twoToThe32); l@271: if(e == 'LE') { l@271: b.writeUInt32LE(low, 0, true); l@271: b['write' + u + 'Int32LE'](high, 4, true); l@271: } else { l@271: b.writeUInt32BE(low, 4, true); l@271: b['write' + u + 'Int32BE'](high, 0, true); l@271: } l@271: return b; l@271: };}; l@271: l@271: module.exports.unpackInt64 = read64(false); l@271: module.exports.unpackUInt64 = read64(true); l@271: module.exports.packInt64 = write64(false); l@271: module.exports.packUInt64 = write64(true); l@271: l@271: addBindings("Float32", "Float"); l@271: addBindings("Float64", "Double");