forked from mcollina/msgpack5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (63 loc) · 1.88 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
74
75
76
77
78
79
80
81
var assert = require('assert')
var bl = require('bl')
var streams = require('./lib/streams')
var buildDecode = require('./lib/decoder')
var buildEncode = require('./lib/encoder')
function msgpack (options) {
var encodingTypes = []
var decodingTypes = []
options = options || {
forceFloat64: false,
compatibilityMode: false
}
function registerEncoder (check, encode) {
assert(check, 'must have an encode function')
assert(encode, 'must have an encode function')
encodingTypes.push({
check: check, encode: encode
})
return this
}
function registerDecoder (type, decode) {
assert(type >= 0, 'must have a non-negative type')
assert(decode, 'must have a decode function')
decodingTypes.push({
type: type, decode: decode
})
return this
}
function register (type, constructor, encode, decode) {
assert(constructor, 'must have a constructor')
assert(encode, 'must have an encode function')
assert(type >= 0, 'must have a non-negative type')
assert(decode, 'must have a decode function')
function check (obj) {
return (obj instanceof constructor)
}
function reEncode (obj) {
var buf = bl()
var header = new Buffer(1)
header.writeInt8(type, 0)
buf.append(header)
buf.append(encode(obj))
return buf
}
this.registerEncoder(check, reEncode)
this.registerDecoder(type, decode)
return this
}
return {
encode: buildEncode(encodingTypes, options.forceFloat64, options.compatibilityMode),
decode: buildDecode(decodingTypes),
register: register,
registerEncoder: registerEncoder,
registerDecoder: registerDecoder,
encoder: streams.encoder,
decoder: streams.decoder,
// needed for levelup support
buffer: true,
type: 'msgpack5',
IncompleteBufferError: buildDecode.IncompleteBufferError
}
}
module.exports = msgpack