uint-array.js
This file
Path
lib/utils/uint-array.js
69 lines · 2.3 KiB · JavaScript
Last changed by
Allow passing `Buffer` to the `input` option (#1029)ehmickybefore adoption40fdc75
History of this fileTake it
Rename files (#977)ehmickybefore adoption4b2e316
lines 1–6why, one step back1import {StringDecoder} from 'node:string_decoder';23const {toString: objectToString} = Object.prototype;45export const isArrayBuffer = value => objectToString.call(value) === '[object ArrayBuffer]';6Allow passing `Buffer` to the `input` option (#1029)ehmickybefore adoption40fdc75
lines 7–8why, one step back7// Is either Uint8Array or Buffer8export const isUint8Array = value => objectToString.call(value) === '[object Uint8Array]';Rename files (#977)ehmickybefore adoption4b2e316
lines 9–69why, one step back910export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);1112const textEncoder = new TextEncoder();13const stringToUint8Array = string => textEncoder.encode(string);1415const textDecoder = new TextDecoder();16export const uint8ArrayToString = uint8Array => textDecoder.decode(uint8Array);1718export const joinToString = (uint8ArraysOrStrings, encoding) => {19 const strings = uint8ArraysToStrings(uint8ArraysOrStrings, encoding);20 return strings.join('');21};2223const uint8ArraysToStrings = (uint8ArraysOrStrings, encoding) => {24 if (encoding === 'utf8' && uint8ArraysOrStrings.every(uint8ArrayOrString => typeof uint8ArrayOrString === 'string')) {25 return uint8ArraysOrStrings;26 }2728 const decoder = new StringDecoder(encoding);29 const strings = uint8ArraysOrStrings30 .map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'31 ? stringToUint8Array(uint8ArrayOrString)32 : uint8ArrayOrString)33 .map(uint8Array => decoder.write(uint8Array));34 const finalString = decoder.end();35 return finalString === '' ? strings : [...strings, finalString];36};3738export const joinToUint8Array = uint8ArraysOrStrings => {39 if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {40 return uint8ArraysOrStrings[0];41 }4243 return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));44};4546const stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'47 ? stringToUint8Array(uint8ArrayOrString)48 : uint8ArrayOrString);4950export const concatUint8Arrays = uint8Arrays => {51 const result = new Uint8Array(getJoinLength(uint8Arrays));5253 let index = 0;54 for (const uint8Array of uint8Arrays) {55 result.set(uint8Array, index);56 index += uint8Array.length;57 }5859 return result;60};6162const getJoinLength = uint8Arrays => {63 let joinLength = 0;64 for (const uint8Array of uint8Arrays) {65 joinLength += uint8Array.length;66 }6768 return joinLength;69};