Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add hexWrite test for invalid characters/lengths
Browse files Browse the repository at this point in the history
chjj committed Jan 31, 2024

Verified

This commit was signed with the committer’s verified signature.
chjj Christopher Jeffrey (JJ)
1 parent e320c87 commit 02c5846
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions test/write-hex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use strict'

const Buffer = require('../').Buffer
const test = require('tape')

test('buffer.write("hex") should stop on invalid characters', function (t) {
const buf = Buffer.alloc(4)

// 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
}

const str = 'abcd' + String.fromCharCode(ch) + 'ef0'

buf.fill(0)

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()
})

0 comments on commit 02c5846

Please sign in to comment.