-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.js
71 lines (61 loc) · 1.6 KB
/
utils.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
const lexint = require('lexicographic-integer')
const Promise = require('any-promise')
const co = require('co').wrap
const promisify = require('pify')
const collect = promisify(require('stream-collector'))
const through = require('through2')
const extend = require('xtend/mutable')
const MAX_INT = 2147483647
const firstInStream = co(function* (stream) {
const results = yield collect(stream)
return results[0]
})
module.exports = {
Promise,
co,
promisify,
assert,
validateEncoding,
createPassThrough,
createKeyParserTransform,
hexint,
unhexint,
firstInStream,
MAX_INT
}
function assert (statement, err) {
if (!statement) throw new Error(err || 'assertion failed')
}
function validateEncoding ({ value, encoding }) {
if (encoding === 'binary') {
assert(Buffer.isBuffer(value), 'expected Buffer')
} else if (encoding === 'json') {
assert(value && typeof value === 'object', 'expected object')
} else if (encoding === 'utf8') {
assert(typeof value === 'string', 'expected string')
}
}
function createPassThrough () {
return through.obj(function (data, enc, cb) {
cb(null, data)
})
}
function createKeyParserTransform (parseKey) {
return function (opts) {
return through.obj(function (data, enc, cb) {
if (opts.keys !== false) {
if (opts.values === false) {
return cb(null, parseKey(data))
}
extend(data, parseKey(data.key))
}
cb(null, data)
})
}
}
function hexint (n) {
return lexint.pack(n, 'hex')
}
function unhexint (hex) {
return lexint.unpack(Array.prototype.slice.call(new Buffer(hex, 'hex')))
}