forked from mcollina/msgpack5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.js
43 lines (34 loc) · 986 Bytes
/
example.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
var msgpack = require('./')() // namespace our extensions
, a = new MyType(2, 'a')
, encode = msgpack.encode
, decode = msgpack.decode
msgpack.register(0x42, MyType, mytipeEncode, mytipeDecode)
console.log(encode({ 'hello': 'world' }).toString('hex'))
// 81a568656c6c6fa5776f726c64
console.log(decode(encode({ 'hello': 'world' })))
// { hello: 'world' }
console.log(encode(a).toString('hex'))
// d5426161
console.log(decode(encode(a)) instanceof MyType)
// true
console.log(decode(encode(a)))
// { value: 'a', size: 2 }
function MyType(size, value) {
this.value = value
this.size = size
}
function mytipeEncode(obj) {
var buf = new Buffer(obj.size)
buf.fill(obj.value)
return buf
}
function mytipeDecode(data) {
var result = new MyType(data.length, data.toString('utf8', 0, 1))
, i
for (i = 0; i < data.length; i++) {
if (data.readUInt8(0) != data.readUInt8(i)) {
throw new Error('should all be the same')
}
}
return result
}