1
|
var Buffer = require('buffer').Buffer
|
2
|
var test = require('tape')
|
3
|
|
4
|
var toArrayBuffer = require('.')
|
5
|
|
6
|
function elementsEqual (ab, buffer) {
|
7
|
var view = new Uint8Array(ab)
|
8
|
for (var i = 0; i < view.length; i++) {
|
9
|
if (view[i] !== buffer[i]) {
|
10
|
return false
|
11
|
}
|
12
|
}
|
13
|
return true
|
14
|
}
|
15
|
|
16
|
test('Basic behavior', function (t) {
|
17
|
var buf = new Buffer(10)
|
18
|
for (var i = 0; i < 10; i++) {
|
19
|
buf[i] = i
|
20
|
}
|
21
|
|
22
|
var ab = toArrayBuffer(buf)
|
23
|
|
24
|
t.equals(ab.byteLength, 10, 'correct length')
|
25
|
t.ok(elementsEqual(ab, buf), 'elements equal')
|
26
|
t.end()
|
27
|
})
|
28
|
|
29
|
test('Behavior when input is a subarray 1', function (t) {
|
30
|
var origBuf = new Buffer(10)
|
31
|
for (var i = 0; i < 10; i++) {
|
32
|
origBuf[i] = i
|
33
|
}
|
34
|
var buf = origBuf.slice(1)
|
35
|
|
36
|
var ab = toArrayBuffer(buf)
|
37
|
|
38
|
t.equals(ab.byteLength, 9, 'correct length')
|
39
|
t.ok(elementsEqual(ab, buf), 'elements equal')
|
40
|
t.notOk(ab === buf.buffer, 'the underlying ArrayBuffer is not returned when incorrect')
|
41
|
t.end()
|
42
|
})
|
43
|
|
44
|
test('Behavior when input is a subarray 2', function (t) {
|
45
|
var origBuf = new Buffer(10)
|
46
|
for (var i = 0; i < 10; i++) {
|
47
|
origBuf[i] = i
|
48
|
}
|
49
|
var buf = origBuf.slice(0, 9)
|
50
|
|
51
|
var ab = toArrayBuffer(buf)
|
52
|
|
53
|
t.equals(ab.byteLength, 9, 'correct length')
|
54
|
t.ok(elementsEqual(ab, buf), 'elements equal')
|
55
|
t.notOk(ab === buf.buffer, 'the underlying ArrayBuffer is not returned when incorrect')
|
56
|
t.end()
|
57
|
})
|