-
-
Notifications
You must be signed in to change notification settings - Fork 239
/
Copy pathwrite-hex.js
59 lines (47 loc) · 1.41 KB
/
write-hex.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
'use strict'
const Buffer = require('../').Buffer
const test = require('tape')
test('buffer.write("hex") should stop on invalid characters', function (t) {
// Test the entire 16-bit space.
for (let ch = 0; ch <= 0xffff; ch++) {
// 0-9
if (ch >= 0x30 && ch <= 0x39) {
continue
}
// A-F
if (ch >= 0x41 && ch <= 0x46) {
continue
}
// a-f
if (ch >= 0x61 && ch <= 0x66) {
continue
}
for (const str of [
'abcd' + String.fromCharCode(ch) + 'ef0',
'abcde' + String.fromCharCode(ch) + 'f0',
'abcd' + String.fromCharCode(ch + 0) + String.fromCharCode(ch + 1) + 'f0',
'abcde' + String.fromCharCode(ch + 0) + String.fromCharCode(ch + 1) + '0'
]) {
const buf = Buffer.alloc(4)
t.equal(str.length, 8)
t.equal(buf.write(str, 'hex'), 2)
t.equal(buf.toString('hex'), 'abcd0000')
t.equal(Buffer.from(str, 'hex').toString('hex'), 'abcd')
}
}
t.end()
})
test('buffer.write("hex") should truncate odd string lengths', function (t) {
const buf = Buffer.alloc(32)
const charset = '0123456789abcdef'
let str = ''
for (let i = 0; i < 63; i++) {
str += charset[Math.random() * charset.length | 0]
}
t.equal(buf.write('abcde', 'hex'), 2)
t.equal(buf.toString('hex', 0, 3), 'abcd00')
buf.fill(0)
t.equal(buf.write(str, 'hex'), 31)
t.equal(buf.toString('hex', 0, 32), str.slice(0, -1) + '00')
t.end()
})