diff --git a/src/_assert.ts b/src/_assert.ts index cd802fd..d9340f8 100644 --- a/src/_assert.ts +++ b/src/_assert.ts @@ -6,8 +6,16 @@ function bool(b: boolean) { if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`); } +function isBytes(a: unknown): a is Uint8Array { + return ( + a != null && + typeof a === 'object' && + (a instanceof Uint8Array || a.constructor.name === 'Uint8Array') + ); +} + function bytes(b: Uint8Array | undefined, ...lengths: number[]) { - if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array'); + if (!isBytes(b)) throw new Error('Expected Uint8Array'); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); } diff --git a/src/utils.ts b/src/utils.ts index 82f5b5e..692a24e 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -11,8 +11,12 @@ export const u16 = (arr: TypedArray) => export const u32 = (arr: TypedArray) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -function isBytes(a: any): a is Uint8Array { - return a instanceof Uint8Array || a.constructor.name === 'Uint8Array'; +function isBytes(a: unknown): a is Uint8Array { + return ( + a != null && + typeof a === 'object' && + (a instanceof Uint8Array || a.constructor.name === 'Uint8Array') + ); } // Cast array to view @@ -169,7 +173,7 @@ export function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>( } export function ensureBytes(b: any, len?: number) { - if (!(b instanceof Uint8Array)) throw new Error('Uint8Array expected'); + if (!isBytes(b)) throw new Error('Uint8Array expected'); if (typeof len === 'number') if (b.length !== len) throw new Error(`Uint8Array length ${len} expected`); }