Skip to content

Commit

Permalink
Add bufferSize option
Browse files Browse the repository at this point in the history
  • Loading branch information
allevo committed Nov 15, 2023
1 parent b89be67 commit e536d7d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 10 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,16 @@ export interface Des {
deserializeIterable: <T>(deserialize: (des: Des) => T) => Iterable<T>
}

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,
Expand Down
22 changes: 22 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down

0 comments on commit e536d7d

Please sign in to comment.