/** * Copyright 2017-2022, Voxel51, Inc. */ import pako from "./pako.js"; export { deserialize }; export const ARRAY_TYPES = { Uint8Array, Int8Array, Uint16Array, Int16Array, Uint32Array, Int32Array, Float32Array, Float64Array, }; export type TypedArray = | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array; export interface NumpyResult { buffer: ArrayBuffer; shape: [number, number]; arrayType: keyof typeof ARRAY_TYPES; } const DATA_TYPES = { // < = little-endian, > = big-endian, | = host architecture // we assume hosts are little-endian (like x86) so big-endian types are only // supported for 8-bit integers, where endianness doesn't matter "|b1": Uint8Array, "b1": Uint8Array, "|u1": Uint8Array, "u1": Uint8Array, "|i1": Int8Array, "i1": Int8Array, "|u2": Uint16Array, " String.fromCharCode(c)) .join(""); } /** * Parses a saved numpy array */ function parse(array: Uint8Array): NumpyResult { const version = readUint16At(array, 6); if (version !== 1) { throw new Error(`Unsupported version: ${version}`); } const headerLength = readUint16At(array, 8); const bodyIndex = 10 + headerLength; const header = JSON.parse( readStringAt(array, 10, bodyIndex) .replace(/'/g, '"') .replace(/\(/g, "[") .replace(/\)/g, "]") .replace(/True|False/g, (s) => s.toLowerCase()) .replace(/\s+/g, "") .replace(/,}/, "}") .replace(/,\]/, "]") ); if (header.fortran_order) { throw new Error(`Fortran order arrays are not supported"`); } const ArrayType = DATA_TYPES[header.descr]; if (!ArrayType) { throw new Error(`Unsupported data type: "${header.descr}"`); } const rawData = array.slice(bodyIndex); const typedData = ArrayType === Uint8Array ? rawData : new ArrayType( rawData.buffer, rawData.byteOffset, rawData.byteLength / ArrayType.BYTES_PER_ELEMENT ); return { shape: header.shape, buffer: typedData.buffer, arrayType: typedData.constructor.name, }; } /** * Deserializes and parses a saved numpy array */ function deserialize(str: string): NumpyResult { return parse(pako.inflate(atob(str))); }