From e536d7da6ba5bdc0972ab109a3bff3b6a7d871e7 Mon Sep 17 00:00:00 2001 From: Tommaso Allevi Date: Wed, 15 Nov 2023 11:36:06 +0100 Subject: [PATCH] Add bufferSize option --- README.md | 2 +- src/index.ts | 12 ++++++++++-- tests/index.test.ts | 22 ++++++++++++++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 63bc563..b241734 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ console.log(deserializedTodos) This library exports the following functions: -- `createSer()`: creates a new serializer. +- `createSer()`/`createSer({ bufferSize: number })`: creates a new serializer. - `createDes(buffer)`: creates a new deserializer. - `ser.serializeBoolean(b)`: serializes a boolean value. - `des.deserializeBoolean()`: deserializes a boolean value. diff --git a/src/index.ts b/src/index.ts index ab3fb26..2da979f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,8 +26,16 @@ export interface Des { deserializeIterable: (deserialize: (des: Des) => T) => Iterable } -export function createSer (): Ser { - const buffer = new ArrayBuffer(2 ** 24) +interface CreateSerOption { + bufferSize?: number +} +export function createSer ({ bufferSize }: CreateSerOption = {}): Ser { + const size = bufferSize || 2 ** 24 + if (size >= 2 ** 32) { + throw new Error('bufferSize option must be strictly less than 2 ** 32') + } + + const buffer = new ArrayBuffer(size) return { index: 0, buffer, diff --git a/tests/index.test.ts b/tests/index.test.ts index d101ebd..f0ec8a6 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -261,6 +261,28 @@ await t.test('iterable', async t => { }) }) +await t.test('with option', async t => { + await t.test('bufferSize', async t => { + { + const ser = createSer({ bufferSize: 4 }) + assert.equal(ser.buffer.byteLength, 4) + } + { + const ser = createSer({ bufferSize: 8 }) + assert.equal(ser.buffer.byteLength, 8) + } + { + const ser = createSer({ bufferSize: 2 ** 32 - 4 }) + assert.equal(ser.buffer.byteLength, 2 ** 32 - 4) + } + { + assert.throws(() => createSer({ bufferSize: 2 ** 32 }), err => { + return /bufferSize option must be strictly less than 2 \*\* 32/.test((err as Error).message) + }) + } + }) +}) + await t.test('random items', async t => { const elements: any[] = [ { item: 'foo', serializer: 'serializeString', deserializer: 'deserializeString' },