├── .editorconfig ├── .gitattributes ├── .github ├── security.md └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── benchmark.mjs ├── index.d.ts ├── index.js ├── license ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/security.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. 4 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | - 18 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /benchmark.mjs: -------------------------------------------------------------------------------- 1 | /* eslint no-undef: "off" */ 2 | 3 | import {Buffer} from 'node:buffer'; 4 | import {randomBytes} from 'node:crypto'; 5 | import benchmark from 'benchmark'; 6 | import { 7 | base64ToString, 8 | compareUint8Arrays, 9 | concatUint8Arrays, 10 | hexToUint8Array, 11 | isUint8Array, 12 | stringToBase64, 13 | stringToUint8Array, 14 | uint8ArrayToBase64, 15 | uint8ArrayToHex, 16 | uint8ArrayToString, 17 | getUintBE, 18 | indexOf, 19 | includes, 20 | } from './index.js'; 21 | 22 | const oneMb = 1024 * 1024; 23 | const largeUint8Array = new Uint8Array(randomBytes(oneMb).buffer); 24 | // eslint-disable-next-line unicorn/prefer-spread 25 | const largeUint8ArrayDuplicate = largeUint8Array.slice(); 26 | const partOfUint8Array = largeUint8Array.slice(-1024); 27 | const textFromUint8Array = uint8ArrayToString(largeUint8Array); 28 | const base64FromUint8Array = Buffer.from(textFromUint8Array).toString('base64'); 29 | const hexFromUint8Array = uint8ArrayToHex(largeUint8Array); 30 | const view = new DataView(largeUint8Array.buffer, 0, 10); 31 | 32 | const suite = new benchmark.Suite(); 33 | 34 | suite.add('isUint8Array', () => isUint8Array(largeUint8Array)); 35 | 36 | suite.add('compareUint8Arrays', () => compareUint8Arrays(largeUint8Array, largeUint8ArrayDuplicate)); 37 | 38 | suite.add('concatUint8Arrays with 2 arrays', () => concatUint8Arrays([largeUint8Array, largeUint8Array])); 39 | 40 | suite.add('concatUint8Arrays with 3 arrays', () => concatUint8Arrays([largeUint8Array, largeUint8Array])); 41 | 42 | suite.add('concatUint8Arrays with 4 arrays', () => concatUint8Arrays([largeUint8Array, largeUint8Array, largeUint8Array, largeUint8Array])); 43 | 44 | suite.add('uint8ArrayToString', () => uint8ArrayToString(largeUint8Array)); 45 | 46 | suite.add('uint8ArrayToString - latin1', () => uint8ArrayToString(largeUint8Array, 'latin1')); 47 | 48 | suite.add('stringToUint8Array', () => stringToUint8Array(textFromUint8Array)); 49 | 50 | suite.add('uint8ArrayToBase64', () => uint8ArrayToBase64(largeUint8Array)); 51 | 52 | suite.add('stringToBase64', () => stringToBase64(textFromUint8Array)); 53 | 54 | suite.add('base64ToString', () => base64ToString(base64FromUint8Array)); 55 | 56 | suite.add('uint8ArrayToHex', () => uint8ArrayToHex(largeUint8Array)); 57 | 58 | suite.add('hexToUint8Array', () => hexToUint8Array(hexFromUint8Array)); 59 | 60 | suite.add('getUintBE', () => getUintBE(view)); 61 | 62 | suite.add('indexOf', () => indexOf(largeUint8Array, partOfUint8Array)); 63 | 64 | suite.add('includes', () => includes(largeUint8Array, partOfUint8Array)); 65 | 66 | suite.on('cycle', event => console.log(event.target.toString())); 67 | suite.run({async: false}); 68 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export type TypedArray = 2 | | Int8Array 3 | | Uint8Array 4 | | Uint8ClampedArray 5 | | Int16Array 6 | | Uint16Array 7 | | Int32Array 8 | | Uint32Array 9 | | Float32Array 10 | | Float64Array 11 | | BigInt64Array 12 | | BigUint64Array; 13 | 14 | /** 15 | Check if the given value is an instance of `Uint8Array`. 16 | 17 | Replacement for [`Buffer.isBuffer()`](https://nodejs.org/api/buffer.html#static-method-bufferisbufferobj). 18 | 19 | @example 20 | ``` 21 | import {isUint8Array} from 'uint8array-extras'; 22 | 23 | console.log(isUint8Array(new Uint8Array())); 24 | //=> true 25 | 26 | console.log(isUint8Array(Buffer.from('x'))); 27 | //=> true 28 | 29 | console.log(isUint8Array(new ArrayBuffer(10))); 30 | //=> false 31 | ``` 32 | */ 33 | export function isUint8Array(value: unknown): value is Uint8Array; 34 | 35 | /** 36 | Throw a `TypeError` if the given value is not an instance of `Uint8Array`. 37 | 38 | @example 39 | ``` 40 | import {assertUint8Array} from 'uint8array-extras'; 41 | 42 | try { 43 | assertUint8Array(new ArrayBuffer(10)); // Throws a TypeError 44 | } catch (error) { 45 | console.error(error.message); 46 | } 47 | ``` 48 | */ 49 | export function assertUint8Array(value: unknown): asserts value is Uint8Array; 50 | 51 | /** 52 | Convert a value to a `Uint8Array` without copying its data. 53 | 54 | This can be useful for converting a `Buffer` to a pure `Uint8Array`. `Buffer` is already an `Uint8Array` subclass, but [`Buffer` alters some behavior](https://sindresorhus.com/blog/goodbye-nodejs-buffer), so it can be useful to cast it to a pure `Uint8Array` before returning it. 55 | 56 | Tip: If you want a copy, just call `.slice()` on the return value. 57 | */ 58 | export function toUint8Array(value: TypedArray | ArrayBuffer | DataView): Uint8Array; 59 | 60 | /** 61 | Concatenate the given arrays into a new array. 62 | 63 | If `arrays` is empty, it will return a zero-sized `Uint8Array`. 64 | 65 | If `totalLength` is not specified, it is calculated from summing the lengths of the given arrays. 66 | 67 | Replacement for [`Buffer.concat()`](https://nodejs.org/api/buffer.html#static-method-bufferconcatlist-totallength). 68 | 69 | @example 70 | ``` 71 | import {concatUint8Arrays} from 'uint8array-extras'; 72 | 73 | const a = new Uint8Array([1, 2, 3]); 74 | const b = new Uint8Array([4, 5, 6]); 75 | 76 | console.log(concatUint8Arrays([a, b])); 77 | //=> Uint8Array [1, 2, 3, 4, 5, 6] 78 | ``` 79 | */ 80 | export function concatUint8Arrays(arrays: Uint8Array[], totalLength?: number): Uint8Array; 81 | 82 | /** 83 | Check if two arrays are identical by verifying that they contain the same bytes in the same sequence. 84 | 85 | Replacement for [`Buffer#equals()`](https://nodejs.org/api/buffer.html#bufequalsotherbuffer). 86 | 87 | @example 88 | ``` 89 | import {areUint8ArraysEqual} from 'uint8array-extras'; 90 | 91 | const a = new Uint8Array([1, 2, 3]); 92 | const b = new Uint8Array([1, 2, 3]); 93 | const c = new Uint8Array([4, 5, 6]); 94 | 95 | console.log(areUint8ArraysEqual(a, b)); 96 | //=> true 97 | 98 | console.log(areUint8ArraysEqual(a, c)); 99 | //=> false 100 | ``` 101 | */ 102 | export function areUint8ArraysEqual(a: Uint8Array, b: Uint8Array): boolean; 103 | 104 | /** 105 | Compare two arrays and indicate their relative order or equality. Useful for sorting. 106 | 107 | Replacement for [`Buffer.compare()`](https://nodejs.org/api/buffer.html#static-method-buffercomparebuf1-buf2). 108 | 109 | @example 110 | ``` 111 | import {compareUint8Arrays} from 'uint8array-extras'; 112 | 113 | const array1 = new Uint8Array([1, 2, 3]); 114 | const array2 = new Uint8Array([4, 5, 6]); 115 | const array3 = new Uint8Array([7, 8, 9]); 116 | 117 | [array3, array1, array2].sort(compareUint8Arrays); 118 | //=> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 119 | ``` 120 | */ 121 | export function compareUint8Arrays(a: Uint8Array, b: Uint8Array): 0 | 1 | -1; 122 | 123 | /** 124 | Convert a `Uint8Array` to a string. 125 | 126 | @param encoding - The [encoding](https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API/Encodings) to convert from. Default: `'utf8'` 127 | 128 | Replacement for [`Buffer#toString()`](https://nodejs.org/api/buffer.html#buftostringencoding-start-end). For the `encoding` parameter, `latin1` should be used instead of `binary` and `utf-16le` instead of `utf16le`. 129 | 130 | @example 131 | ``` 132 | import {uint8ArrayToString} from 'uint8array-extras'; 133 | 134 | const byteArray = new Uint8Array([72, 101, 108, 108, 111]); 135 | console.log(uint8ArrayToString(byteArray)); 136 | //=> 'Hello' 137 | 138 | const zh = new Uint8Array([167, 65, 166, 110]); 139 | console.log(uint8ArrayToString(zh, 'big5')); 140 | //=> '你好' 141 | 142 | const ja = new Uint8Array([130, 177, 130, 241, 130, 201, 130, 191, 130, 205]); 143 | console.log(uint8ArrayToString(ja, 'shift-jis')); 144 | //=> 'こんにちは' 145 | ``` 146 | */ 147 | export function uint8ArrayToString(array: Uint8Array | ArrayBuffer, encoding?: string): string; 148 | 149 | /** 150 | Convert a string to a `Uint8Array` (using UTF-8 encoding). 151 | 152 | Replacement for [`Buffer.from('Hello')`](https://nodejs.org/api/buffer.html#static-method-bufferfromstring-encoding). 153 | 154 | @example 155 | ``` 156 | import {stringToUint8Array} from 'uint8array-extras'; 157 | 158 | console.log(stringToUint8Array('Hello')); 159 | //=> Uint8Array [72, 101, 108, 108, 111] 160 | ``` 161 | */ 162 | export function stringToUint8Array(string: string): Uint8Array; 163 | 164 | /** 165 | Convert a `Uint8Array` to a Base64-encoded string. 166 | 167 | Specify `{urlSafe: true}` to get a [Base64URL](https://base64.guru/standards/base64url)-encoded string. 168 | 169 | Replacement for [`Buffer#toString('base64')`](https://nodejs.org/api/buffer.html#buftostringencoding-start-end). 170 | 171 | @example 172 | ``` 173 | import {uint8ArrayToBase64} from 'uint8array-extras'; 174 | 175 | const byteArray = new Uint8Array([72, 101, 108, 108, 111]); 176 | 177 | console.log(uint8ArrayToBase64(byteArray)); 178 | //=> 'SGVsbG8=' 179 | ``` 180 | */ 181 | export function uint8ArrayToBase64(array: Uint8Array, options?: {urlSafe: boolean}): string; 182 | 183 | /** 184 | Convert a Base64-encoded or [Base64URL](https://base64.guru/standards/base64url)-encoded string to a `Uint8Array`. 185 | 186 | Replacement for [`Buffer.from('SGVsbG8=', 'base64')`](https://nodejs.org/api/buffer.html#static-method-bufferfromstring-encoding). 187 | 188 | @example 189 | ``` 190 | import {base64ToUint8Array} from 'uint8array-extras'; 191 | 192 | console.log(base64ToUint8Array('SGVsbG8=')); 193 | //=> Uint8Array [72, 101, 108, 108, 111] 194 | ``` 195 | */ 196 | export function base64ToUint8Array(string: string): Uint8Array; 197 | 198 | /** 199 | Encode a string to Base64-encoded string. 200 | 201 | Specify `{urlSafe: true}` to get a [Base64URL](https://base64.guru/standards/base64url)-encoded string. 202 | 203 | Replacement for `Buffer.from('Hello').toString('base64')` and [`btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/btoa). 204 | 205 | @example 206 | ``` 207 | import {stringToBase64} from 'uint8array-extras'; 208 | 209 | console.log(stringToBase64('Hello')); 210 | //=> 'SGVsbG8=' 211 | ``` 212 | */ 213 | export function stringToBase64(string: string, options?: {urlSafe: boolean}): string; 214 | 215 | /** 216 | Decode a Base64-encoded or [Base64URL](https://base64.guru/standards/base64url)-encoded string to a string. 217 | 218 | Replacement for `Buffer.from('SGVsbG8=', 'base64').toString()` and [`atob()`](https://developer.mozilla.org/en-US/docs/Web/API/atob). 219 | 220 | @example 221 | ``` 222 | import {base64ToString} from 'uint8array-extras'; 223 | 224 | console.log(base64ToString('SGVsbG8=')); 225 | //=> 'Hello' 226 | ``` 227 | */ 228 | export function base64ToString(base64String: string): string; 229 | 230 | /** 231 | Convert a `Uint8Array` to a Hex string. 232 | 233 | Replacement for [`Buffer#toString('hex')`](https://nodejs.org/api/buffer.html#buftostringencoding-start-end). 234 | 235 | @example 236 | ``` 237 | import {uint8ArrayToHex} from 'uint8array-extras'; 238 | 239 | const byteArray = new Uint8Array([72, 101, 108, 108, 111]); 240 | 241 | console.log(uint8ArrayToHex(byteArray)); 242 | //=> '48656c6c6f' 243 | ``` 244 | */ 245 | export function uint8ArrayToHex(array: Uint8Array): string; 246 | 247 | /** 248 | Convert a Hex string to a `Uint8Array`. 249 | 250 | Replacement for [`Buffer.from('48656c6c6f', 'hex')`](https://nodejs.org/api/buffer.html#static-method-bufferfromstring-encoding). 251 | 252 | @example 253 | ``` 254 | import {hexToUint8Array} from 'uint8array-extras'; 255 | 256 | console.log(hexToUint8Array('48656c6c6f')); 257 | //=> Uint8Array [72, 101, 108, 108, 111] 258 | ``` 259 | */ 260 | export function hexToUint8Array(hexString: string): Uint8Array; 261 | 262 | /** 263 | Read `DataView#byteLength` number of bytes from the given view, up to 48-bit. 264 | 265 | Replacement for [`Buffer#readUintBE`](https://nodejs.org/api/buffer.html#bufreadintbeoffset-bytelength) 266 | 267 | @example 268 | ``` 269 | import {getUintBE} from 'uint8array-extras'; 270 | 271 | const byteArray = new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); 272 | 273 | console.log(getUintBE(new DataView(byteArray.buffer))); 274 | //=> 20015998341291 275 | ``` 276 | */ 277 | export function getUintBE(view: DataView): number; // eslint-disable-line @typescript-eslint/naming-convention 278 | 279 | /** 280 | Find the index of the first occurrence of the given sequence of bytes (`value`) within the given `Uint8Array` (`array`). 281 | 282 | Replacement for [`Buffer#indexOf`](https://nodejs.org/api/buffer.html#bufindexofvalue-byteoffset-encoding). `Uint8Array#indexOf` only takes a number which is different from Buffer's `indexOf` implementation. 283 | 284 | @example 285 | ``` 286 | import {indexOf} from 'uint8array-extras'; 287 | 288 | const byteArray = new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]); 289 | 290 | console.log(indexOf(byteArray, new Uint8Array([0x78, 0x90]))); 291 | //=> 3 292 | ``` 293 | */ 294 | export function indexOf(array: Uint8Array, value: Uint8Array): number; 295 | 296 | /** 297 | Checks if the given sequence of bytes (`value`) is within the given `Uint8Array` (`array`). 298 | 299 | Returns true if the value is included, otherwise false. 300 | 301 | Replacement for [`Buffer#includes`](https://nodejs.org/api/buffer.html#bufincludesvalue-byteoffset-encoding). `Uint8Array#includes` only takes a number which is different from Buffer's `includes` implementation. 302 | 303 | ``` 304 | import {includes} from 'uint8array-extras'; 305 | 306 | const byteArray = new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]); 307 | 308 | console.log(includes(byteArray, new Uint8Array([0x78, 0x90]))); 309 | //=> true 310 | ``` 311 | */ 312 | export function includes(array: Uint8Array, value: Uint8Array): boolean; 313 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const objectToString = Object.prototype.toString; 2 | const uint8ArrayStringified = '[object Uint8Array]'; 3 | const arrayBufferStringified = '[object ArrayBuffer]'; 4 | 5 | function isType(value, typeConstructor, typeStringified) { 6 | if (!value) { 7 | return false; 8 | } 9 | 10 | if (value.constructor === typeConstructor) { 11 | return true; 12 | } 13 | 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); 27 | } 28 | 29 | export function assertUint8Array(value) { 30 | if (!isUint8Array(value)) { 31 | throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof value}\``); 32 | } 33 | } 34 | 35 | export function assertUint8ArrayOrArrayBuffer(value) { 36 | if (!isUint8ArrayOrArrayBuffer(value)) { 37 | throw new TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof value}\``); 38 | } 39 | } 40 | 41 | export function toUint8Array(value) { 42 | if (value instanceof ArrayBuffer) { 43 | return new Uint8Array(value); 44 | } 45 | 46 | if (ArrayBuffer.isView(value)) { 47 | return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); 48 | } 49 | 50 | throw new TypeError(`Unsupported value, got \`${typeof value}\`.`); 51 | } 52 | 53 | export function concatUint8Arrays(arrays, totalLength) { 54 | if (arrays.length === 0) { 55 | return new Uint8Array(0); 56 | } 57 | 58 | totalLength ??= arrays.reduce((accumulator, currentValue) => accumulator + currentValue.length, 0); 59 | 60 | const returnValue = new Uint8Array(totalLength); 61 | 62 | let offset = 0; 63 | for (const array of arrays) { 64 | assertUint8Array(array); 65 | returnValue.set(array, offset); 66 | offset += array.length; 67 | } 68 | 69 | return returnValue; 70 | } 71 | 72 | export function areUint8ArraysEqual(a, b) { 73 | assertUint8Array(a); 74 | assertUint8Array(b); 75 | 76 | if (a === b) { 77 | return true; 78 | } 79 | 80 | if (a.length !== b.length) { 81 | return false; 82 | } 83 | 84 | // eslint-disable-next-line unicorn/no-for-loop 85 | for (let index = 0; index < a.length; index++) { 86 | if (a[index] !== b[index]) { 87 | return false; 88 | } 89 | } 90 | 91 | return true; 92 | } 93 | 94 | export function compareUint8Arrays(a, b) { 95 | assertUint8Array(a); 96 | assertUint8Array(b); 97 | 98 | const length = Math.min(a.length, b.length); 99 | 100 | for (let index = 0; index < length; index++) { 101 | const diff = a[index] - b[index]; 102 | if (diff !== 0) { 103 | return Math.sign(diff); 104 | } 105 | } 106 | 107 | // At this point, all the compared elements are equal. 108 | // The shorter array should come first if the arrays are of different lengths. 109 | return Math.sign(a.length - b.length); 110 | } 111 | 112 | const cachedDecoders = { 113 | utf8: new globalThis.TextDecoder('utf8'), 114 | }; 115 | 116 | export function uint8ArrayToString(array, encoding = 'utf8') { 117 | assertUint8ArrayOrArrayBuffer(array); 118 | cachedDecoders[encoding] ??= new globalThis.TextDecoder(encoding); 119 | return cachedDecoders[encoding].decode(array); 120 | } 121 | 122 | function assertString(value) { 123 | if (typeof value !== 'string') { 124 | throw new TypeError(`Expected \`string\`, got \`${typeof value}\``); 125 | } 126 | } 127 | 128 | const cachedEncoder = new globalThis.TextEncoder(); 129 | 130 | export function stringToUint8Array(string) { 131 | assertString(string); 132 | return cachedEncoder.encode(string); 133 | } 134 | 135 | function base64ToBase64Url(base64) { 136 | return base64.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); 137 | } 138 | 139 | function base64UrlToBase64(base64url) { 140 | return base64url.replaceAll('-', '+').replaceAll('_', '/'); 141 | } 142 | 143 | // Reference: https://phuoc.ng/collection/this-vs-that/concat-vs-push/ 144 | const MAX_BLOCK_SIZE = 65_535; 145 | 146 | export function uint8ArrayToBase64(array, {urlSafe = false} = {}) { 147 | assertUint8Array(array); 148 | 149 | let base64; 150 | 151 | if (array.length < MAX_BLOCK_SIZE) { 152 | // Required as `btoa` and `atob` don't properly support Unicode: https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem 153 | base64 = globalThis.btoa(String.fromCodePoint.apply(this, array)); 154 | } else { 155 | base64 = ''; 156 | for (const value of array) { 157 | base64 += String.fromCodePoint(value); 158 | } 159 | 160 | base64 = globalThis.btoa(base64); 161 | } 162 | 163 | return urlSafe ? base64ToBase64Url(base64) : base64; 164 | } 165 | 166 | export function base64ToUint8Array(base64String) { 167 | assertString(base64String); 168 | return Uint8Array.from(globalThis.atob(base64UrlToBase64(base64String)), x => x.codePointAt(0)); 169 | } 170 | 171 | export function stringToBase64(string, {urlSafe = false} = {}) { 172 | assertString(string); 173 | return uint8ArrayToBase64(stringToUint8Array(string), {urlSafe}); 174 | } 175 | 176 | export function base64ToString(base64String) { 177 | assertString(base64String); 178 | return uint8ArrayToString(base64ToUint8Array(base64String)); 179 | } 180 | 181 | const byteToHexLookupTable = Array.from({length: 256}, (_, index) => index.toString(16).padStart(2, '0')); 182 | 183 | export function uint8ArrayToHex(array) { 184 | assertUint8Array(array); 185 | 186 | // Concatenating a string is faster than using an array. 187 | let hexString = ''; 188 | 189 | // eslint-disable-next-line unicorn/no-for-loop -- Max performance is critical. 190 | for (let index = 0; index < array.length; index++) { 191 | hexString += byteToHexLookupTable[array[index]]; 192 | } 193 | 194 | return hexString; 195 | } 196 | 197 | const hexToDecimalLookupTable = { 198 | 0: 0, 199 | 1: 1, 200 | 2: 2, 201 | 3: 3, 202 | 4: 4, 203 | 5: 5, 204 | 6: 6, 205 | 7: 7, 206 | 8: 8, 207 | 9: 9, 208 | a: 10, 209 | b: 11, 210 | c: 12, 211 | d: 13, 212 | e: 14, 213 | f: 15, 214 | A: 10, 215 | B: 11, 216 | C: 12, 217 | D: 13, 218 | E: 14, 219 | F: 15, 220 | }; 221 | 222 | export function hexToUint8Array(hexString) { 223 | assertString(hexString); 224 | 225 | if (hexString.length % 2 !== 0) { 226 | throw new Error('Invalid Hex string length.'); 227 | } 228 | 229 | const resultLength = hexString.length / 2; 230 | const bytes = new Uint8Array(resultLength); 231 | 232 | for (let index = 0; index < resultLength; index++) { 233 | const highNibble = hexToDecimalLookupTable[hexString[index * 2]]; 234 | const lowNibble = hexToDecimalLookupTable[hexString[(index * 2) + 1]]; 235 | 236 | if (highNibble === undefined || lowNibble === undefined) { 237 | throw new Error(`Invalid Hex character encountered at position ${index * 2}`); 238 | } 239 | 240 | bytes[index] = (highNibble << 4) | lowNibble; // eslint-disable-line no-bitwise 241 | } 242 | 243 | return bytes; 244 | } 245 | 246 | /** 247 | @param {DataView} view 248 | @returns {number} 249 | */ 250 | export function getUintBE(view) { 251 | const {byteLength} = view; 252 | 253 | if (byteLength === 6) { 254 | return (view.getUint16(0) * (2 ** 32)) + view.getUint32(2); 255 | } 256 | 257 | if (byteLength === 5) { 258 | return (view.getUint8(0) * (2 ** 32)) + view.getUint32(1); 259 | } 260 | 261 | if (byteLength === 4) { 262 | return view.getUint32(0); 263 | } 264 | 265 | if (byteLength === 3) { 266 | return (view.getUint8(0) * (2 ** 16)) + view.getUint16(1); 267 | } 268 | 269 | if (byteLength === 2) { 270 | return view.getUint16(0); 271 | } 272 | 273 | if (byteLength === 1) { 274 | return view.getUint8(0); 275 | } 276 | } 277 | 278 | /** 279 | @param {Uint8Array} array 280 | @param {Uint8Array} value 281 | @returns {number} 282 | */ 283 | export function indexOf(array, value) { 284 | const arrayLength = array.length; 285 | const valueLength = value.length; 286 | 287 | if (valueLength === 0) { 288 | return -1; 289 | } 290 | 291 | if (valueLength > arrayLength) { 292 | return -1; 293 | } 294 | 295 | const validOffsetLength = arrayLength - valueLength; 296 | 297 | for (let index = 0; index <= validOffsetLength; index++) { 298 | let isMatch = true; 299 | for (let index2 = 0; index2 < valueLength; index2++) { 300 | if (array[index + index2] !== value[index2]) { 301 | isMatch = false; 302 | break; 303 | } 304 | } 305 | 306 | if (isMatch) { 307 | return index; 308 | } 309 | } 310 | 311 | return -1; 312 | } 313 | 314 | /** 315 | @param {Uint8Array} array 316 | @param {Uint8Array} value 317 | @returns {boolean} 318 | */ 319 | export function includes(array, value) { 320 | return indexOf(array, value) !== -1; 321 | } 322 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "uint8array-extras", 3 | "version": "1.4.0", 4 | "description": "Useful utilities for working with Uint8Array (and Buffer)", 5 | "license": "MIT", 6 | "repository": "sindresorhus/uint8array-extras", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": { 15 | "types": "./index.d.ts", 16 | "default": "./index.js" 17 | }, 18 | "sideEffects": false, 19 | "engines": { 20 | "node": ">=18" 21 | }, 22 | "scripts": { 23 | "test": "xo && ava && tsc index.d.ts" 24 | }, 25 | "files": [ 26 | "index.js", 27 | "index.d.ts" 28 | ], 29 | "keywords": [ 30 | "uint8array", 31 | "uint8", 32 | "typedarray", 33 | "buffer", 34 | "typedarray", 35 | "arraybuffer", 36 | "is", 37 | "assert", 38 | "concat", 39 | "equals", 40 | "compare", 41 | "base64", 42 | "string", 43 | "atob", 44 | "btoa", 45 | "hex", 46 | "hexadecimal" 47 | ], 48 | "devDependencies": { 49 | "ava": "^6.0.1", 50 | "typescript": "^5.3.3", 51 | "xo": "^0.56.0", 52 | "benchmark": "2.1.4" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # uint8array-extras 2 | 3 | > Useful utilities for working with [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) (and [`Buffer`](https://nodejs.org/api/buffer.html)) 4 | 5 | It's time to [transition from `Buffer` to `Uint8Array`](https://sindresorhus.com/blog/goodbye-nodejs-buffer), and this package helps fill in the gaps. 6 | 7 | Note that `Buffer` is a `Uint8Array` subclass, so you can use this package with `Buffer` too. 8 | 9 | This package is tree-shakeable and browser-compatible. 10 | 11 | This package also includes methods to convert a string to Base64 and back. 12 | 13 | Note: In the browser, do not use [`globalThis.atob()`](https://developer.mozilla.org/en-US/docs/Web/API/atob) / [`globalThis.btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/btoa) because they [do not support Unicode](https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem). This package does. 14 | 15 | ## Install 16 | 17 | ```sh 18 | npm install uint8array-extras 19 | ``` 20 | 21 | ## Usage 22 | 23 | ```js 24 | import {concatUint8Arrays} from 'uint8array-extras'; 25 | 26 | const a = new Uint8Array([1, 2, 3]); 27 | const b = new Uint8Array([4, 5, 6]); 28 | 29 | console.log(concatUint8Arrays([a, b])); 30 | //=> Uint8Array [1, 2, 3, 4, 5, 6] 31 | ``` 32 | 33 | ## API 34 | 35 | ### `isUint8Array(value: unknown): boolean` 36 | 37 | Check if the given value is an instance of `Uint8Array`. 38 | 39 | Replacement for [`Buffer.isBuffer()`](https://nodejs.org/api/buffer.html#static-method-bufferisbufferobj). 40 | 41 | ```js 42 | import {isUint8Array} from 'uint8array-extras'; 43 | 44 | console.log(isUint8Array(new Uint8Array())); 45 | //=> true 46 | 47 | console.log(isUint8Array(Buffer.from('x'))); 48 | //=> true 49 | 50 | console.log(isUint8Array(new ArrayBuffer(10))); 51 | //=> false 52 | ``` 53 | 54 | ### `assertUint8Array(value: unknown)` 55 | 56 | Throw a `TypeError` if the given value is not an instance of `Uint8Array`. 57 | 58 | ```js 59 | import {assertUint8Array} from 'uint8array-extras'; 60 | 61 | try { 62 | assertUint8Array(new ArrayBuffer(10)); // Throws a TypeError 63 | } catch (error) { 64 | console.error(error.message); 65 | } 66 | ``` 67 | 68 | ### `toUint8Array(value: TypedArray | ArrayBuffer | DataView): Uint8Array` 69 | 70 | Convert a value to a `Uint8Array` without copying its data. 71 | 72 | This can be useful for converting a `Buffer` to a pure `Uint8Array`. `Buffer` is already an `Uint8Array` subclass, but [`Buffer` alters some behavior](https://sindresorhus.com/blog/goodbye-nodejs-buffer), so it can be useful to cast it to a pure `Uint8Array` before returning it. 73 | 74 | Tip: If you want a copy, just call `.slice()` on the return value. 75 | 76 | ### `concatUint8Arrays(arrays: Uint8Array[], totalLength?: number): Uint8Array` 77 | 78 | Concatenate the given arrays into a new array. 79 | 80 | If `arrays` is empty, it will return a zero-sized `Uint8Array`. 81 | 82 | If `totalLength` is not specified, it is calculated from summing the lengths of the given arrays. 83 | 84 | Replacement for [`Buffer.concat()`](https://nodejs.org/api/buffer.html#static-method-bufferconcatlist-totallength). 85 | 86 | ```js 87 | import {concatUint8Arrays} from 'uint8array-extras'; 88 | 89 | const a = new Uint8Array([1, 2, 3]); 90 | const b = new Uint8Array([4, 5, 6]); 91 | 92 | console.log(concatUint8Arrays([a, b])); 93 | //=> Uint8Array [1, 2, 3, 4, 5, 6] 94 | ``` 95 | 96 | ### `areUint8ArraysEqual(a: Uint8Array, b: Uint8Array): boolean` 97 | 98 | Check if two arrays are identical by verifying that they contain the same bytes in the same sequence. 99 | 100 | Replacement for [`Buffer#equals()`](https://nodejs.org/api/buffer.html#bufequalsotherbuffer). 101 | 102 | ```js 103 | import {areUint8ArraysEqual} from 'uint8array-extras'; 104 | 105 | const a = new Uint8Array([1, 2, 3]); 106 | const b = new Uint8Array([1, 2, 3]); 107 | const c = new Uint8Array([4, 5, 6]); 108 | 109 | console.log(areUint8ArraysEqual(a, b)); 110 | //=> true 111 | 112 | console.log(areUint8ArraysEqual(a, c)); 113 | //=> false 114 | ``` 115 | 116 | ### `compareUint8Arrays(a: Uint8Array, b: Uint8Array): 0 | 1 | -1` 117 | 118 | Compare two arrays and indicate their relative order or equality. Useful for sorting. 119 | 120 | Replacement for [`Buffer.compare()`](https://nodejs.org/api/buffer.html#static-method-buffercomparebuf1-buf2). 121 | 122 | ```js 123 | import {compareUint8Arrays} from 'uint8array-extras'; 124 | 125 | const array1 = new Uint8Array([1, 2, 3]); 126 | const array2 = new Uint8Array([4, 5, 6]); 127 | const array3 = new Uint8Array([7, 8, 9]); 128 | 129 | [array3, array1, array2].sort(compareUint8Arrays); 130 | //=> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 131 | ``` 132 | 133 | ### `uint8ArrayToString(array: Uint8Array | ArrayBuffer, encoding?: string = 'utf8'): string` 134 | 135 | Convert a `Uint8Array` to a string. 136 | 137 | - Parameter: `encoding` - The [encoding](https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API/Encodings) to convert from. 138 | 139 | Replacement for [`Buffer#toString()`](https://nodejs.org/api/buffer.html#buftostringencoding-start-end). For the `encoding` parameter, `latin1` should be used instead of `binary` and `utf-16le` instead of `utf16le`. 140 | 141 | ```js 142 | import {uint8ArrayToString} from 'uint8array-extras'; 143 | 144 | const byteArray = new Uint8Array([72, 101, 108, 108, 111]); 145 | console.log(uint8ArrayToString(byteArray)); 146 | //=> 'Hello' 147 | 148 | const zh = new Uint8Array([167, 65, 166, 110]); 149 | console.log(uint8ArrayToString(zh, 'big5')); 150 | //=> '你好' 151 | 152 | const ja = new Uint8Array([130, 177, 130, 241, 130, 201, 130, 191, 130, 205]); 153 | console.log(uint8ArrayToString(ja, 'shift-jis')); 154 | //=> 'こんにちは' 155 | ``` 156 | 157 | ### `stringToUint8Array(string: string): Uint8Array` 158 | 159 | Convert a string to a `Uint8Array` (using UTF-8 encoding). 160 | 161 | Replacement for [`Buffer.from('Hello')`](https://nodejs.org/api/buffer.html#static-method-bufferfromstring-encoding). 162 | 163 | ```js 164 | import {stringToUint8Array} from 'uint8array-extras'; 165 | 166 | console.log(stringToUint8Array('Hello')); 167 | //=> Uint8Array [72, 101, 108, 108, 111] 168 | ``` 169 | 170 | ### `uint8ArrayToBase64(array: Uint8Array, options?: {urlSafe: boolean}): string` 171 | 172 | Convert a `Uint8Array` to a Base64-encoded string. 173 | 174 | Specify `{urlSafe: true}` to get a [Base64URL](https://base64.guru/standards/base64url)-encoded string. 175 | 176 | Replacement for [`Buffer#toString('base64')`](https://nodejs.org/api/buffer.html#buftostringencoding-start-end). 177 | 178 | ```js 179 | import {uint8ArrayToBase64} from 'uint8array-extras'; 180 | 181 | const byteArray = new Uint8Array([72, 101, 108, 108, 111]); 182 | 183 | console.log(uint8ArrayToBase64(byteArray)); 184 | //=> 'SGVsbG8=' 185 | ``` 186 | 187 | ### `base64ToUint8Array(string: string): Uint8Array` 188 | 189 | Convert a Base64-encoded or [Base64URL](https://base64.guru/standards/base64url)-encoded string to a `Uint8Array`. 190 | 191 | Replacement for [`Buffer.from('SGVsbG8=', 'base64')`](https://nodejs.org/api/buffer.html#static-method-bufferfromstring-encoding). 192 | 193 | ```js 194 | import {base64ToUint8Array} from 'uint8array-extras'; 195 | 196 | console.log(base64ToUint8Array('SGVsbG8=')); 197 | //=> Uint8Array [72, 101, 108, 108, 111] 198 | ``` 199 | 200 | ### `stringToBase64(string: string, options?: {urlSafe: boolean}): string` 201 | 202 | Encode a string to Base64-encoded string. 203 | 204 | Specify `{urlSafe: true}` to get a [Base64URL](https://base64.guru/standards/base64url)-encoded string. 205 | 206 | Replacement for `Buffer.from('Hello').toString('base64')` and [`btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/btoa). 207 | 208 | ```js 209 | import {stringToBase64} from 'uint8array-extras'; 210 | 211 | console.log(stringToBase64('Hello')); 212 | //=> 'SGVsbG8=' 213 | ``` 214 | 215 | ### `base64ToString(base64String: string): string` 216 | 217 | Decode a Base64-encoded or [Base64URL](https://base64.guru/standards/base64url)-encoded string to a string. 218 | 219 | Replacement for `Buffer.from('SGVsbG8=', 'base64').toString()` and [`atob()`](https://developer.mozilla.org/en-US/docs/Web/API/atob). 220 | 221 | ```js 222 | import {base64ToString} from 'uint8array-extras'; 223 | 224 | console.log(base64ToString('SGVsbG8=')); 225 | //=> 'Hello' 226 | ``` 227 | 228 | ### `uint8ArrayToHex(array: Uint8Array): string` 229 | 230 | Convert a `Uint8Array` to a Hex string. 231 | 232 | Replacement for [`Buffer#toString('hex')`](https://nodejs.org/api/buffer.html#buftostringencoding-start-end). 233 | 234 | ```js 235 | import {uint8ArrayToHex} from 'uint8array-extras'; 236 | 237 | const byteArray = new Uint8Array([72, 101, 108, 108, 111]); 238 | 239 | console.log(uint8ArrayToHex(byteArray)); 240 | //=> '48656c6c6f' 241 | ``` 242 | 243 | ### `hexToUint8Array(hexString: string): Uint8Array` 244 | 245 | Convert a Hex string to a `Uint8Array`. 246 | 247 | Replacement for [`Buffer.from('48656c6c6f', 'hex')`](https://nodejs.org/api/buffer.html#static-method-bufferfromstring-encoding). 248 | 249 | ```js 250 | import {hexToUint8Array} from 'uint8array-extras'; 251 | 252 | console.log(hexToUint8Array('48656c6c6f')); 253 | //=> Uint8Array [72, 101, 108, 108, 111] 254 | ``` 255 | 256 | ### `getUintBE(view: DataView): number` 257 | 258 | Read `DataView#byteLength` number of bytes from the given view, up to 48-bit. 259 | 260 | Replacement for [`Buffer#readUintBE`](https://nodejs.org/api/buffer.html#bufreadintbeoffset-bytelength) 261 | 262 | ```js 263 | import {getUintBE} from 'uint8array-extras'; 264 | 265 | const byteArray = new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); 266 | 267 | console.log(getUintBE(new DataView(byteArray.buffer))); 268 | //=> 20015998341291 269 | ``` 270 | 271 | ### `indexOf(array: Uint8Array, value: Uint8Array): number` 272 | 273 | Find the index of the first occurrence of the given sequence of bytes (`value`) within the given `Uint8Array` (`array`). 274 | 275 | Replacement for [`Buffer#indexOf`](https://nodejs.org/api/buffer.html#bufindexofvalue-byteoffset-encoding). `Uint8Array#indexOf` only takes a number which is different from Buffer's `indexOf` implementation. 276 | 277 | ```js 278 | import {indexOf} from 'uint8array-extras'; 279 | 280 | const byteArray = new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]); 281 | 282 | console.log(indexOf(byteArray, new Uint8Array([0x78, 0x90]))); 283 | //=> 3 284 | ``` 285 | 286 | ### `includes(array: Uint8Array, value: Uint8Array): boolean` 287 | 288 | Checks if the given sequence of bytes (`value`) is within the given `Uint8Array` (`array`). 289 | 290 | Returns true if the value is included, otherwise false. 291 | 292 | Replacement for [`Buffer#includes`](https://nodejs.org/api/buffer.html#bufincludesvalue-byteoffset-encoding). `Uint8Array#includes` only takes a number which is different from Buffer's `includes` implementation. 293 | 294 | ```js 295 | import {includes} from 'uint8array-extras'; 296 | 297 | const byteArray = new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]); 298 | 299 | console.log(includes(byteArray, new Uint8Array([0x78, 0x90]))); 300 | //=> true 301 | ``` 302 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import { 3 | isUint8Array, 4 | assertUint8Array, 5 | toUint8Array, 6 | concatUint8Arrays, 7 | areUint8ArraysEqual, 8 | compareUint8Arrays, 9 | uint8ArrayToString, 10 | stringToUint8Array, 11 | uint8ArrayToBase64, 12 | base64ToUint8Array, 13 | stringToBase64, 14 | base64ToString, 15 | uint8ArrayToHex, 16 | hexToUint8Array, 17 | getUintBE, 18 | indexOf, 19 | includes, 20 | } from './index.js'; 21 | 22 | test('isUint8Array', t => { 23 | t.true(isUint8Array(new Uint8Array())); 24 | t.false(isUint8Array(new Uint16Array())); 25 | }); 26 | 27 | test('assertUint8Array', t => { 28 | t.throws(() => { 29 | assertUint8Array(1); 30 | }, { 31 | instanceOf: TypeError, 32 | }); 33 | }); 34 | 35 | const isUint8ArrayStrict = value => Object.getPrototypeOf(value) === Uint8Array.prototype; 36 | 37 | test('toUint8Array - TypedArray', t => { 38 | const fixture = new Float32Array(1); 39 | t.true(isUint8ArrayStrict(toUint8Array(fixture))); 40 | }); 41 | 42 | test('toUint8Array - ArrayBuffer', t => { 43 | const fixture = new ArrayBuffer(1); 44 | t.true(isUint8ArrayStrict(toUint8Array(fixture))); 45 | }); 46 | 47 | test('toUint8Array - DataView', t => { 48 | const fixture = new DataView(new ArrayBuffer(1)); 49 | t.true(isUint8ArrayStrict(toUint8Array(fixture))); 50 | }); 51 | 52 | test('concatUint8Arrays - combining multiple Uint8Arrays', t => { 53 | const array1 = new Uint8Array([1, 2, 3]); 54 | const array2 = new Uint8Array([4, 5, 6]); 55 | const array3 = new Uint8Array([7, 8, 9]); 56 | 57 | const result = concatUint8Arrays([array1, array2, array3]); 58 | t.deepEqual(result, new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9])); 59 | }); 60 | 61 | test('concatUint8Arrays - with an empty array', t => { 62 | const emptyResult = concatUint8Arrays([]); 63 | t.deepEqual(emptyResult, new Uint8Array(0)); 64 | }); 65 | 66 | test('concatUint8Arrays - throws when input is not a Uint8Array', t => { 67 | t.throws(() => { 68 | concatUint8Arrays([123]); 69 | }, { 70 | instanceOf: TypeError, 71 | message: 'Expected `Uint8Array`, got `number`', 72 | }); 73 | }); 74 | 75 | test('areUint8ArraysEqual - with identical Uint8Arrays', t => { 76 | const array1 = new Uint8Array([1, 2, 3]); 77 | const array2 = new Uint8Array([1, 2, 3]); 78 | t.true(areUint8ArraysEqual(array1, array2)); 79 | }); 80 | 81 | test('areUint8ArraysEqual - with different content', t => { 82 | const array1 = new Uint8Array([1, 2, 3]); 83 | const array3 = new Uint8Array([1, 2, 4]); 84 | t.false(areUint8ArraysEqual(array1, array3)); 85 | }); 86 | 87 | test('areUint8ArraysEqual - with different sizes', t => { 88 | const array1 = new Uint8Array([1, 2, 3]); 89 | const array4 = new Uint8Array([1, 2, 3, 4]); 90 | t.false(areUint8ArraysEqual(array1, array4)); 91 | }); 92 | 93 | test('compareUint8Arrays - with identical Uint8Arrays', t => { 94 | const array1 = new Uint8Array([1, 2, 3]); 95 | const array2 = new Uint8Array([1, 2, 3]); 96 | t.is(compareUint8Arrays(array1, array2), 0); 97 | }); 98 | 99 | test('compareUint8Arrays - first array is less than the second', t => { 100 | const array1 = new Uint8Array([1, 2, 3]); 101 | const array3 = new Uint8Array([1, 1, 3]); 102 | t.is(compareUint8Arrays(array1, array3), 1); 103 | }); 104 | 105 | test('compareUint8Arrays - first array is greater than the second', t => { 106 | const array1 = new Uint8Array([1, 2, 3]); 107 | const array4 = new Uint8Array([1, 3, 3]); 108 | t.is(compareUint8Arrays(array1, array4), -1); 109 | }); 110 | 111 | test('compareUint8Arrays - with different lengths', t => { 112 | const array1 = new Uint8Array([1, 2, 3]); 113 | const array5 = new Uint8Array([1, 2, 3, 4]); 114 | t.is(compareUint8Arrays(array1, array5), -1); 115 | t.is(compareUint8Arrays(array5, array1), 1); 116 | }); 117 | 118 | test('stringToUint8Array and uint8ArrayToString', t => { 119 | const fixture = 'Hello'; 120 | const array = stringToUint8Array(fixture); 121 | t.deepEqual(array, new Uint8Array([72, 101, 108, 108, 111])); 122 | t.is(uint8ArrayToString(array), fixture); 123 | }); 124 | 125 | test('uint8ArrayToString with encoding', t => { 126 | t.is(uint8ArrayToString(new Uint8Array([ 127 | 207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33, 128 | ]), 'windows-1251'), 'Привет, мир!'); 129 | 130 | t.is(uint8ArrayToString(new Uint8Array([ 131 | 167, 65, 166, 110, 132 | ]), 'big5'), '你好'); 133 | 134 | t.is(uint8ArrayToString(new Uint8Array([ 135 | 130, 177, 130, 241, 130, 201, 130, 191, 130, 205, 136 | ]), 'shift-jis'), 'こんにちは'); 137 | }); 138 | 139 | test('uint8ArrayToString with ArrayBuffer', t => { 140 | const fixture = new Uint8Array([72, 101, 108, 108, 111]).buffer; 141 | t.is(uint8ArrayToString(fixture), 'Hello'); 142 | }); 143 | 144 | test('uint8ArrayToBase64 and base64ToUint8Array', t => { 145 | const fixture = stringToUint8Array('Hello'); 146 | const base64 = uint8ArrayToBase64(fixture); 147 | t.is(base64, 'SGVsbG8='); 148 | t.deepEqual(base64ToUint8Array(base64), fixture); 149 | }); 150 | 151 | test('should handle uint8ArrayToBase64 with 200k items', t => { 152 | const fixture = stringToUint8Array('H'.repeat(200_000)); 153 | const base64 = uint8ArrayToBase64(fixture); 154 | t.deepEqual(base64ToUint8Array(base64), fixture); 155 | }); 156 | 157 | test('uint8ArrayToBase64 and base64ToUint8Array #2', t => { 158 | const fixture = stringToUint8Array('a Ā 𐀀 文 🦄'); 159 | t.deepEqual(base64ToUint8Array(uint8ArrayToBase64(base64ToUint8Array(uint8ArrayToBase64(fixture)))), fixture); 160 | }); 161 | 162 | test('stringToBase64 and base64ToString', t => { 163 | const fixture = 'a Ā 𐀀 文 🦄'; 164 | t.is(base64ToString(stringToBase64(base64ToString(stringToBase64(fixture)))), fixture); 165 | }); 166 | 167 | test('stringToBase64 - urlSafe option', t => { 168 | const fixture = 'subjects?_d=1 🦄'; 169 | t.is(stringToBase64(fixture, {urlSafe: true}), Buffer.from(fixture).toString('base64url')); // eslint-disable-line n/prefer-global/buffer 170 | t.is(base64ToString(stringToBase64(base64ToString(stringToBase64(fixture, {urlSafe: true})), {urlSafe: true})), fixture); 171 | }); 172 | 173 | test('uint8ArrayToHex', t => { 174 | const fixture = stringToUint8Array('Hello - a Ā 𐀀 文 🦄'); 175 | t.is(uint8ArrayToHex(fixture), Buffer.from(fixture).toString('hex')); // eslint-disable-line n/prefer-global/buffer 176 | }); 177 | 178 | test('hexToUint8Array', t => { 179 | const fixtureString = 'Hello - a Ā 𐀀 文 🦄'; 180 | const fixtureHex = Buffer.from(fixtureString).toString('hex'); // eslint-disable-line n/prefer-global/buffer 181 | t.deepEqual(hexToUint8Array(fixtureHex), new Uint8Array(Buffer.from(fixtureHex, 'hex'))); // eslint-disable-line n/prefer-global/buffer 182 | }); 183 | 184 | test('getUintBE', t => { 185 | const fixture = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab]; // eslint-disable-line unicorn/number-literal-case 186 | 187 | for (let index = 1; index < 6; index += 1) { 188 | t.is(getUintBE(new DataView(new Uint8Array(fixture).buffer, 0, index)), Buffer.from(fixture).readUintBE(0, index)); // eslint-disable-line n/prefer-global/buffer 189 | } 190 | 191 | for (let index = 0; index < 5; index += 1) { 192 | t.is(getUintBE(new DataView(new Uint8Array(fixture).buffer, index, 6 - index)), Buffer.from(fixture).readUintBE(index, 6 - index)); // eslint-disable-line n/prefer-global/buffer 193 | } 194 | }); 195 | 196 | test('indexOf - sequence found in the middle', t => { 197 | const fixture = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]; // eslint-disable-line unicorn/number-literal-case 198 | const sequence = [0x78, 0x90]; 199 | t.is(indexOf(new Uint8Array(fixture), new Uint8Array(sequence)), 3); 200 | }); 201 | 202 | test('indexOf - sequence found at the end', t => { 203 | const fixture2 = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab]; // eslint-disable-line unicorn/number-literal-case 204 | const sequence2 = [0x90, 0xab]; // eslint-disable-line unicorn/number-literal-case 205 | t.is(indexOf(new Uint8Array(fixture2), new Uint8Array(sequence2)), 4); 206 | }); 207 | 208 | test('indexOf - sequence not found', t => { 209 | const fixture = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]; // eslint-disable-line unicorn/number-literal-case 210 | t.is(indexOf(new Uint8Array(fixture), new Uint8Array([0x00, 0x01])), -1); 211 | }); 212 | 213 | test('indexOf - sequence found at the beginning', t => { 214 | const fixture = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]; // eslint-disable-line unicorn/number-literal-case 215 | const sequence3 = [0x12, 0x34]; 216 | t.is(indexOf(new Uint8Array(fixture), new Uint8Array(sequence3)), 0); 217 | }); 218 | 219 | test('indexOf - sequence is the entire array', t => { 220 | const fixture = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]; // eslint-disable-line unicorn/number-literal-case 221 | const sequence4 = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]; // eslint-disable-line unicorn/number-literal-case 222 | t.is(indexOf(new Uint8Array(fixture), new Uint8Array(sequence4)), 0); 223 | }); 224 | 225 | test('indexOf - empty array as sequence', t => { 226 | const fixture = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]; // eslint-disable-line unicorn/number-literal-case 227 | const emptyArray = []; 228 | t.is(indexOf(new Uint8Array(emptyArray), new Uint8Array([0x78, 0x90])), -1); 229 | t.is(indexOf(new Uint8Array(fixture), new Uint8Array(emptyArray)), -1); 230 | }); 231 | 232 | test('indexOf - single element found', t => { 233 | const fixture = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]; // eslint-disable-line unicorn/number-literal-case 234 | const singleElement = [0x56]; 235 | t.is(indexOf(new Uint8Array(fixture), new Uint8Array(singleElement)), 2); 236 | }); 237 | 238 | test('includes', t => { 239 | const fixture = [0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]; // eslint-disable-line unicorn/number-literal-case 240 | t.true(includes(new Uint8Array(fixture), new Uint8Array([0x78, 0x90]))); 241 | t.false(includes(new Uint8Array(fixture), new Uint8Array([0x90, 0x78]))); 242 | }); 243 | --------------------------------------------------------------------------------