-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (61 loc) · 1.92 KB
/
index.js
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
import determineLength from './util/determineLength';
import types from './type';
import pattern from './pattern';
/**
* Pack a set of values, starting at offset, based on format
*
* @param fmt
* @param values
* @param offset
* @returns {Buffer|void}
*/
export const pack = (fmt, values, offset = 0) => {
const buffer = Buffer.alloc(determineLength(fmt));
const re = new RegExp(pattern, 'g');
let match;
let i = 0;
while ((match = re.exec(fmt))) { // eslint-disable-line no-cond-assign
const [, typeName, typeCount] = match;
const type = types[typeName];
if (!type) {
throw new Error(`Unknown type: ${typeName}`);
}
const length = type.length();
const count = typeCount ? parseInt(typeCount, 10) : 1;
if (offset + count * length > buffer.length) {
return buffer;
}
type.pack(buffer, values.slice(i, i + 1), offset, count);
offset += count * length; // eslint-disable-line no-param-reassign
i += 1;
}
return buffer;
};
/**
* Unpack an array buffer, starting at offset, based on format
*
* @param fmt
* @param buffer
* @param offset
* @returns {[]|void}
*/
export const unpack = (fmt, buffer, offset = 0) => {
let results = [];
let match;
const re = new RegExp(pattern, 'g');
while ((match = re.exec(fmt))) { // eslint-disable-line no-cond-assign
const [, typeName, typeCount] = match;
const type = types[typeName];
if (!type) {
throw new Error(`Unknown type: ${typeName}`);
}
const length = type.length();
const count = typeCount ? parseInt(typeCount, 10) : 1;
if (offset + count * length > buffer.length) {
return results;
}
results = [...results, ...type.unpack(buffer, offset, count)];
offset += count * length; // eslint-disable-line no-param-reassign
}
return results;
};