4-bytes-length-strings.js
2.35 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
'use strict'
var test = require('tape').test
var msgpack = require('../')
var bl = require('bl')
test('encode/decode 2^16 <-> (2^32 - 1) bytes strings', function (t) {
var encoder = msgpack()
var all = []
var str
str = new Buffer(Math.pow(2, 16))
str.fill('a')
all.push(str.toString())
str = new Buffer(Math.pow(2, 16) + 1)
str.fill('a')
all.push(str.toString())
str = new Buffer(Math.pow(2, 20))
str.fill('a')
all.push(str.toString())
all.forEach(function (str) {
t.test('encoding a string of length ' + str.length, function (t) {
var buf = encoder.encode(str)
t.equal(buf.length, 5 + Buffer.byteLength(str), 'must be the proper length')
t.equal(buf[0], 0xdb, 'must have the proper header')
t.equal(buf.readUInt32BE(1), Buffer.byteLength(str), 'must include the str length')
t.equal(buf.toString('utf8', 5, Buffer.byteLength(str) + 5), str, 'must decode correctly')
t.end()
})
t.test('decoding a string of length ' + str.length, function (t) {
var buf = new Buffer(5 + Buffer.byteLength(str))
buf[0] = 0xdb
buf.writeUInt32BE(Buffer.byteLength(str), 1)
buf.write(str, 5)
t.equal(encoder.decode(buf), str, 'must decode correctly')
t.end()
})
t.test('mirror test a string of length ' + str.length, function (t) {
t.equal(encoder.decode(encoder.encode(str)), str, 'must stay the same')
t.end()
})
})
t.end()
})
test('decoding a chopped string', function (t) {
var encoder = msgpack()
var str
for (str = 'a'; str.length < 0xffff + 100; str += 'a') {
}
var buf = new Buffer(5 + Buffer.byteLength(str))
buf[0] = 0xdb
buf.writeUInt32BE(Buffer.byteLength(str) + 10, 1) // set bigger size
buf.write(str, 5)
buf = bl().append(buf)
var origLength = buf.length
t.throws(function () {
encoder.decode(buf)
}, encoder.IncompleteBufferError, 'must throw IncompleteBufferError')
t.equals(buf.length, origLength, 'must not consume any byte')
t.end()
})
test('decoding an incomplete header of a string', function (t) {
var encoder = msgpack()
var buf = new Buffer(4)
buf[0] = 0xdb
buf = bl().append(buf)
var origLength = buf.length
t.throws(function () {
encoder.decode(buf)
}, encoder.IncompleteBufferError, 'must throw IncompleteBufferError')
t.equals(buf.length, origLength, 'must not consume any byte')
t.end()
})