Skip to content

Commit 095873b

Browse files
committed
Add more complex test case for readArray; minor code cleanup
1 parent 956fd1e commit 095873b

File tree

2 files changed

+51
-11
lines changed

2 files changed

+51
-11
lines changed

typescript/src/bufferfish.test.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,3 +459,40 @@ test("should return error for arrays exceeding maximum length", () => {
459459
Error("array length 65536 exceeds maximum size of 65535"),
460460
)
461461
})
462+
463+
test("should read an array of objects implementing read methods", () => {
464+
const arr = [
465+
{ id: 1, name: "Alice", key: { inner: 1 } },
466+
{ id: 2, name: "Bob", key: { inner: 2 } },
467+
{ id: 3, name: "Charlie", key: { inner: 3 } },
468+
]
469+
470+
const decodeKey = (bf: Bufferfish) => {
471+
const inner = bf.readUint8()
472+
if (inner instanceof Error) {
473+
throw inner
474+
}
475+
return { inner }
476+
}
477+
478+
const decodePerson = (bf: Bufferfish) => {
479+
const id = bf.readUint8()
480+
const name = bf.readString()
481+
const key = decodeKey(bf)
482+
if (id instanceof Error || name instanceof Error) {
483+
throw id instanceof Error ? id : name
484+
}
485+
return { id, name, key }
486+
}
487+
488+
const bf = new Bufferfish()
489+
490+
bf.writeArray(arr, (person) => {
491+
bf.writeUint8(person.id)
492+
bf.writeString(person.name)
493+
bf.writeUint8(person.key.inner)
494+
})
495+
496+
const people = bf.readArray(() => decodePerson(bf))
497+
expect(people).toEqual(arr)
498+
})

typescript/src/bufferfish.ts

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -583,23 +583,26 @@ export class Bufferfish {
583583
/**
584584
* Attempts to read a variable-length array of elements from the buffer.
585585
*/
586-
public readArray<T>(readFn: () => T): Array<T> | Error {
586+
public readArray<T>(readFn: () => T | Error): Array<T> | Error {
587587
const lengthOrError = this.readUint16()
588588
if (lengthOrError instanceof Error) {
589589
return lengthOrError
590590
}
591591

592-
const length = lengthOrError as number
593-
const values: Array<T> = []
594-
for (let i = 0; i < length; i++) {
595-
const valueOrError = readFn()
596-
if (valueOrError instanceof Error) {
597-
return valueOrError
598-
}
592+
const length = lengthOrError
593+
const values: Array<T> = new Array(length)
599594

600-
values.push(valueOrError as T)
595+
try {
596+
for (let i = 0; i < length; i++) {
597+
const valueOrError = readFn()
598+
if (valueOrError instanceof Error) {
599+
return valueOrError
600+
}
601+
values[i] = valueOrError as T
602+
}
603+
return values
604+
} catch (error) {
605+
return error instanceof Error ? error : new Error(String(error))
601606
}
602-
603-
return values
604607
}
605608
}

0 commit comments

Comments
 (0)