From 9d2fd7e45e018defa1d65fb47a4e155ce617f413 Mon Sep 17 00:00:00 2001 From: HDegroote <75906619+HDegroote@users.noreply.github.com> Date: Fri, 18 Oct 2024 13:38:45 +0200 Subject: [PATCH] Error when encoding fixed-length buffers of incorrect size (#30) --- index.js | 1 + test.js | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/index.js b/index.js index 027f059..af95f3e 100644 --- a/index.js +++ b/index.js @@ -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) { diff --git a/test.js b/test.js index f21a4e5..371046d 100644 --- a/test.js +++ b/test.js @@ -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)