-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.js
More file actions
102 lines (94 loc) · 2.4 KB
/
binary.js
File metadata and controls
102 lines (94 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* binary.js - binary data helper routines.
*
* 2010, Michel Beloshitsky
*
* Licensed under the terms of MIT license. See COPYING file in the
* root of distribution.
*/
/**
* Basic idea of this format functions borrowed from "binary format"
* routine of tcl standart library. But abbreviations now did not match.
*
* This implementation of binary routines is not full; it's tuned for
* tokyo tyrant connector.
*
* Abbreviations:
*
* b - byte (octet).
* i - 32-bit big-endian integer
* S - string (sequence of chars).
*
* In read function "S" means pascal string. In mean that at first
* read length (N) from 32-integer. After that N bytes read into string.
*
* Example:
*
* > require('./binary').format('bbIIS', 1, 2, 4, 5, 'test')
*
* produces:
*
* > 0x01 0x02 0x00 0x00 0x00 0x04 0x00 0x00
* > 0x00 0x05 0x74 0x65 0x73 0x74
*
* > require('./binary').read(formatString, binaryStringToParse)
*
* acts vice versa.
*/
exports.format = function () {
var out = '', args = arguments, format = args[0].split(''), argi = 1
format.map(function (spec) {
switch (spec) {
case 'b': out += String.fromCharCode(args[argi])
break
case 'i':
var iv = args[argi], i=4, ov = []
while (i--) {
ov.push(String.fromCharCode(iv & 0xFF))
iv >>= 8
}
out+=ov.reverse().join('')
break
case 's': out += args[argi]
break
default:
throw 'Binary format syntax error'
}
argi++
})
return out
}
exports.read = function rd (fmtStr, reader, cb) {
var out = [], spec = fmtStr.split('')
function next(specCh) {
if (!specCh)
return cb(null, out)
switch (specCh) {
case 'b':
reader.read(1, function (err, str) {
out.push(str.charCodeAt(0));
next(spec.shift())
})
break
case 'i':
reader.read(4, function (err, str) {
var j = -1, v = 0
while (++j < 4) {
v += (str.charCodeAt(j) & 0xFF) << (8 * (3 - j))
}
out.push(v)
next(spec.shift())
})
break
case 'S':
rd('i', reader, function (err, len) {
reader.read(len[0], function (err, data) {
out.push(data)
next(spec.shift())
})
})
break
}
}
next(spec.shift())
}