Skip to content

Commit

Permalink
Error when encoding fixed-length buffers of incorrect size (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
HDegroote authored Oct 18, 2024
1 parent bf30820 commit 9d2fd7e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ exports.bool = {
const fixed = exports.fixed = function fixed (n) {
return {
preencode (state, s) {
if (s.byteLength !== n) throw new Error('Incorrect buffer size')
state.end += n
},
encode (state, s) {
Expand Down
13 changes: 13 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,19 @@ test('fixed n', function (t) {
t.exception(() => fixed.decode(state))
})

test('error for incorrect buffer sizes when encoding fixed-length buffers', function (t) {
const smallbuf = b4a.from('aa', 'hex')
const bigBuf = b4a.from('aa'.repeat(500), 'hex')

t.exception(() => enc.encode(enc.fixed32, smallbuf), /Incorrect buffer size/)
t.exception(() => enc.encode(enc.fixed64, smallbuf), /Incorrect buffer size/)
t.exception(() => enc.encode(enc.fixed(100), smallbuf), /Incorrect buffer size/)

t.exception(() => enc.encode(enc.fixed32, bigBuf), /Incorrect buffer size/)
t.exception(() => enc.encode(enc.fixed64, bigBuf), /Incorrect buffer size/)
t.exception(() => enc.encode(enc.fixed(100), bigBuf), /Incorrect buffer size/)
})

test('array', function (t) {
const state = enc.state()
const arr = enc.array(enc.bool)
Expand Down

0 comments on commit 9d2fd7e

Please sign in to comment.