11const objectToString = Object . prototype . toString ;
22const uint8ArrayStringified = '[object Uint8Array]' ;
3+ const arrayBufferStringified = '[object ArrayBuffer]' ;
34
4- export function isUint8Array ( value ) {
5+ function isType ( value , typeConstructor , typeStringified ) {
56 if ( ! value ) {
67 return false ;
78 }
89
9- if ( value . constructor === Uint8Array ) {
10+ if ( value . constructor === typeConstructor ) {
1011 return true ;
1112 }
1213
13- return objectToString . call ( value ) === uint8ArrayStringified ;
14+ return objectToString . call ( value ) === typeStringified ;
15+ }
16+
17+ export function isUint8Array ( value ) {
18+ return isType ( value , Uint8Array , uint8ArrayStringified ) ;
19+ }
20+
21+ function isArrayBuffer ( value ) {
22+ return isType ( value , ArrayBuffer , arrayBufferStringified ) ;
23+ }
24+
25+ function isUint8ArrayOrArrayBuffer ( value ) {
26+ return isUint8Array ( value ) || isArrayBuffer ( value ) ;
1427}
1528
1629export function assertUint8Array ( value ) {
@@ -19,6 +32,12 @@ export function assertUint8Array(value) {
1932 }
2033}
2134
35+ export function assertUint8ArrayOrArrayBuffer ( value ) {
36+ if ( ! isUint8ArrayOrArrayBuffer ( value ) ) {
37+ throw new TypeError ( `Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${ typeof value } \`` ) ;
38+ }
39+ }
40+
2241export function toUint8Array ( value ) {
2342 if ( value instanceof ArrayBuffer ) {
2443 return new Uint8Array ( value ) ;
@@ -95,7 +114,7 @@ const cachedDecoders = {
95114} ;
96115
97116export function uint8ArrayToString ( array , encoding = 'utf8' ) {
98- assertUint8Array ( array ) ;
117+ assertUint8ArrayOrArrayBuffer ( array ) ;
99118 cachedDecoders [ encoding ] ??= new globalThis . TextDecoder ( encoding ) ;
100119 return cachedDecoders [ encoding ] . decode ( array ) ;
101120}
0 commit comments