Skip to content
Myr

uint-array.js

This file

Path

lib/stdio/uint-array.js

62 lines · 2.0 KiB · JavaScript

Last changed by

Add support for `all` option to `execaSync()` (#956)ehmickybefore adoption63b5ac4

History of this file

Take it

Add support for transforms with `execaSync()` (#945)ehmickybefore adoptionc5f9f09

lines 1–35why, one step back
1import {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 }35

Add support for `all` option to `execaSync()` (#956)ehmickybefore adoption63b5ac4

lines 36–43why, one step back
36 return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));
37};3839const stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'40 ? stringToUint8Array(uint8ArrayOrString)41 : uint8ArrayOrString);4243export const concatUint8Arrays = uint8Arrays => {

Add support for transforms with `execaSync()` (#945)ehmickybefore adoptionc5f9f09

lines 44–62why, one step back
44 const result = new Uint8Array(getJoinLength(uint8Arrays));
4546 let index = 0;47 for (const uint8Array of uint8Arrays) {48 result.set(uint8Array, index);49 index += uint8Array.length;50 }5152 return result;53};5455const getJoinLength = uint8Arrays => {56 let joinLength = 0;57 for (const uint8Array of uint8Arrays) {58 joinLength += uint8Array.length;59 }6061 return joinLength;62};