comparison resources/osc/node_modules/binpack/index.js @ 271:fb9c28a4676b prerelease

Added osc example project and node script for testing
author Liam Donovan <l.b.donovan@qmul.ac.uk>
date Tue, 17 May 2016 16:01:06 +0100
parents
children
comparison
equal deleted inserted replaced
270:de37582ce6f3 271:fb9c28a4676b
1 // t is a binpack typename
2 var sizeOfType = function(t) {
3 // unsigned are the same length as signed
4 if(t[0] === 'U') {
5 t = t.slice(1);
6 }
7
8 return {
9 'Float32' : 4,
10 'Float64' : 8,
11 'Int8' : 1,
12 'Int16' : 2,
13 'Int32' : 4,
14 'Int64' : 8
15 }[t];
16 };
17
18 var endianConv = function(e, t) {
19 // node doesn't define 8 bit endianness
20 if(t[t.length - 1] === '8')
21 return '';
22
23 if(e === 'big') {
24 return 'BE';
25 }
26 return 'LE';
27 };
28
29 var addBindings = function(binpackTypename, nodeTypename){
30 if(!(typeof nodeTypename !== "undefined" && nodeTypename !== null)) {
31 nodeTypename = binpackTypename;
32 }
33 module.exports['pack' + binpackTypename] = function(num, endian){
34 b = new Buffer(sizeOfType(binpackTypename));
35 b['write' + nodeTypename + endianConv(endian, binpackTypename)](num, 0, true);
36 return b;
37 }
38
39 module.exports['unpack' + binpackTypename] = function(buff, endian){
40 return buff['read' + nodeTypename + endianConv(endian, binpackTypename)](0);
41 }
42 }
43
44 var addIntBindings = function(n) {
45 addBindings("Int" + n);
46 addBindings("UInt" + n);
47 }
48
49 addIntBindings(8);
50 addIntBindings(16);
51 addIntBindings(32);
52
53 twoToThe32 = Math.pow(2, 32);
54
55 // 64 bit bindings require special care
56 var read64 = function(unsigned){return function(buff, endian){
57 var e = endianConv(endian, '');
58 var u = unsigned ? 'U' : '';
59 var low, high;
60 if(e === 'LE') {
61 low = buff.readUInt32LE(0);
62 high = buff['read' + u + 'Int32LE'](4);
63 } else {
64 low = buff.readUInt32BE(4);
65 high = buff['read' + u + 'Int32BE'](0);
66 }
67 return high * twoToThe32 + low;
68 };};
69
70 var write64 = function(unsigned){return function(num, endian){
71 var e = endianConv(endian, '');
72 var u = unsigned ? 'U' : '';
73 var b = new Buffer(8);
74 var high = Math.floor(num / twoToThe32);
75 var low = Math.floor(num - high * twoToThe32);
76 if(e == 'LE') {
77 b.writeUInt32LE(low, 0, true);
78 b['write' + u + 'Int32LE'](high, 4, true);
79 } else {
80 b.writeUInt32BE(low, 4, true);
81 b['write' + u + 'Int32BE'](high, 0, true);
82 }
83 return b;
84 };};
85
86 module.exports.unpackInt64 = read64(false);
87 module.exports.unpackUInt64 = read64(true);
88 module.exports.packInt64 = write64(false);
89 module.exports.packUInt64 = write64(true);
90
91 addBindings("Float32", "Float");
92 addBindings("Float64", "Double");