in modules/serialize/src/read_element.ts [32:80]
export function readElements(
elementCount: number,
fieldsPerElement: number,
buffer: Uint8Array,
readPos = 0
) {
/* Uint8Array is a view on top of the underlying ArrayBuffer.
* This means that raw underlying memory stored in the ArrayBuffer
* may be larger than the Uint8Array. This is especially true of
* the Node.js Buffer object. The offset and length *must* be
* passed to the DataView otherwise I will get unexpected results.
*/
const dataView = new DataView(
buffer.buffer,
buffer.byteOffset,
buffer.byteLength
)
const elements = []
/* Precondition: readPos must be non-negative and within the byte length of the buffer given. */
needs(
readPos >= 0 && dataView.byteLength >= readPos,
'readPos out of bounds.'
)
/* Precondition: elementCount and fieldsPerElement must be non-negative. */
needs(
elementCount >= 0 && fieldsPerElement >= 0,
'elementCount and fieldsPerElement must be positive.'
)
while (elementCount--) {
const element = []
let fieldCount = fieldsPerElement
while (fieldCount--) {
/* Check for early return (Postcondition): Enough data must exist to read the Uint16 length value. */
if (readPos + 2 > dataView.byteLength) return false
const length = dataView.getUint16(readPos, false) // big endian
readPos += 2
/* Check for early return (Postcondition): Enough data must exist length of the value. */
if (readPos + length > dataView.byteLength) return false
const fieldBinary = buffer.slice(readPos, readPos + length)
element.push(fieldBinary)
readPos += length
}
elements.push(element)
}
return { elements, readPos }
}