From 3c4efd2e775fe60854dc08ab25c0396544fcdc51 Mon Sep 17 00:00:00 2001 From: Yulong Wang <7679871+fs-eire@users.noreply.github.com> Date: Wed, 8 Mar 2023 15:29:04 -0800 Subject: [PATCH] [js/common] allows polyfill for bigint (#14921) ### Description This change delays the execution of checking whether bigint is available in the context. This allows polyfill for `BigInt64Array`/`BigUint64Array` (if there is any) --- js/common/lib/tensor-impl.ts | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/js/common/lib/tensor-impl.ts b/js/common/lib/tensor-impl.ts index 80fc150af0..81c3c0674e 100644 --- a/js/common/lib/tensor-impl.ts +++ b/js/common/lib/tensor-impl.ts @@ -11,9 +11,6 @@ type SupportedTypedArrayConstructors = Float32ArrayConstructor|Uint8ArrayConstru Float64ArrayConstructor|Uint32ArrayConstructor|BigUint64ArrayConstructor; type SupportedTypedArray = InstanceType; -const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && typeof BigInt64Array.from === 'function'; -const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && typeof BigUint64Array.from === 'function'; - // a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap. const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([ ['float32', Float32Array], @@ -39,14 +36,27 @@ const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map { + if (!isBigIntChecked) { + isBigIntChecked = true; + const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && typeof BigInt64Array.from === 'function'; + const isBigUint64ArrayAvailable = + typeof BigUint64Array !== 'undefined' && typeof BigUint64Array.from === 'function'; + + if (isBigInt64ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64'); + } + if (isBigUint64ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64'); + } + } +}; /** * calculate size from dims. @@ -75,6 +85,8 @@ export class Tensor implements TensorInterface { constructor( arg0: TensorType|TensorDataType|readonly boolean[], arg1?: TensorDataType|readonly number[]|readonly boolean[], arg2?: readonly number[]) { + checkBigInt(); + let type: TensorType; let data: TensorDataType; let dims: typeof arg1|typeof arg2;