uint-array.js
This file
Path
lib/stdio/uint-array.js
59 lines · 2.0 KiB · JavaScript
Last changed by
Add support for transforms with `execaSync()` (#945)ehmickybefore adoptionc5f9f09
History of this fileTake it
Add support for transforms with `execaSync()` (#945)ehmickybefore adoptionc5f9f09
lines 1–59why, one step back1import {Buffer} from 'node:buffer';23export const isUint8Array = value => Object.prototype.toString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);45export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);67const textEncoder = new TextEncoder();8const stringToUint8Array = string => textEncoder.encode(string);910const textDecoder = new TextDecoder();11export const uint8ArrayToString = uint8Array => textDecoder.decode(uint8Array);1213export const joinToString = (uint8ArraysOrStrings, areRelated) => {14 if (uint8ArraysOrStrings.length === 1 && typeof uint8ArraysOrStrings[0] === 'string') {15 return uint8ArraysOrStrings[0];16 }1718 const strings = uint8ArraysToStrings(uint8ArraysOrStrings, areRelated);19 return strings.join('');20};2122const uint8ArraysToStrings = (uint8ArraysOrStrings, areRelated) => {23 const decoder = new TextDecoder();24 const strings = uint8ArraysOrStrings.map(uint8ArrayOrString => isUint8Array(uint8ArrayOrString)25 ? decoder.decode(uint8ArrayOrString, {stream: areRelated})26 : uint8ArrayOrString);27 const finalString = decoder.decode();28 return finalString === '' ? strings : [...strings, finalString];29};3031export const joinToUint8Array = uint8ArraysOrStrings => {32 if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {33 return uint8ArraysOrStrings[0];34 }3536 const uint8Arrays = stringsToUint8Arrays(uint8ArraysOrStrings);37 const result = new Uint8Array(getJoinLength(uint8Arrays));3839 let index = 0;40 for (const uint8Array of uint8Arrays) {41 result.set(uint8Array, index);42 index += uint8Array.length;43 }4445 return result;46};4748const stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'49 ? stringToUint8Array(uint8ArrayOrString)50 : uint8ArrayOrString);5152const getJoinLength = uint8Arrays => {53 let joinLength = 0;54 for (const uint8Array of uint8Arrays) {55 joinLength += uint8Array.length;56 }5758 return joinLength;59};