encoding.ts (1731B)
1 /** 2 * @license 3 * Copyright 2024 Google Inc. 4 * SPDX-License-Identifier: Apache-2.0 5 */ 6 7 /** 8 * @internal 9 */ 10 export function stringToTypedArray( 11 string: string, 12 base64Encoded = false, 13 ): Uint8Array { 14 if (base64Encoded) { 15 // TODO: use 16 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/fromBase64 17 // once available. 18 if (typeof Buffer === 'function') { 19 return Buffer.from(string, 'base64'); 20 } 21 return Uint8Array.from(atob(string), m => { 22 return m.codePointAt(0)!; 23 }); 24 } 25 return new TextEncoder().encode(string); 26 } 27 28 /** 29 * @internal 30 */ 31 export function stringToBase64(str: string): string { 32 return typedArrayToBase64(new TextEncoder().encode(str)); 33 } 34 35 /** 36 * @internal 37 */ 38 export function typedArrayToBase64(typedArray: Uint8Array): string { 39 // chunkSize should be less V8 limit on number of arguments! 40 // https://github.com/v8/v8/blob/d3de848bea727518aee94dd2fd42ba0b62037a27/src/objects/code.h#L444 41 const chunkSize = 65534; 42 const chunks = []; 43 44 for (let i = 0; i < typedArray.length; i += chunkSize) { 45 const chunk = typedArray.subarray(i, i + chunkSize); 46 chunks.push(String.fromCodePoint.apply(null, chunk as unknown as number[])); 47 } 48 49 const binaryString = chunks.join(''); 50 return btoa(binaryString); 51 } 52 53 /** 54 * @internal 55 */ 56 export function mergeUint8Arrays(items: Uint8Array[]): Uint8Array { 57 let length = 0; 58 for (const item of items) { 59 length += item.length; 60 } 61 62 // Create a new array with total length and merge all source arrays. 63 const result = new Uint8Array(length); 64 let offset = 0; 65 for (const item of items) { 66 result.set(item, offset); 67 offset += item.length; 68 } 69 70 return result; 71 }