UNPKG

2.63 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright Google LLC All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.io/license
8 */
9Object.defineProperty(exports, "__esModule", { value: true });
10exports.fileBufferToString = exports.fileBuffer = exports.stringToFileBuffer = void 0;
11function stringToFileBuffer(str) {
12 // If we're in Node...
13 if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
14 const buf = Buffer.from(str);
15 const ab = new ArrayBuffer(buf.length);
16 const view = new Uint8Array(ab);
17 for (let i = 0; i < buf.length; ++i) {
18 view[i] = buf[i];
19 }
20 return ab;
21 }
22 else if (typeof TextEncoder !== 'undefined') {
23 // Modern browsers implement TextEncode.
24 return new TextEncoder('utf-8').encode(str).buffer;
25 }
26 else {
27 // Slowest method but sure to be compatible with every platform.
28 const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
29 const bufView = new Uint16Array(buf);
30 for (let i = 0, strLen = str.length; i < strLen; i++) {
31 bufView[i] = str.charCodeAt(i);
32 }
33 return buf;
34 }
35}
36exports.stringToFileBuffer = stringToFileBuffer;
37const fileBuffer = (strings, ...values) => {
38 return stringToFileBuffer(String.raw(strings, ...values));
39};
40exports.fileBuffer = fileBuffer;
41function fileBufferToString(fileBuffer) {
42 if (fileBuffer.toString.length == 1) {
43 return fileBuffer.toString('utf-8');
44 }
45 else if (typeof Buffer !== 'undefined') {
46 return Buffer.from(fileBuffer).toString('utf-8');
47 }
48 else if (typeof TextDecoder !== 'undefined') {
49 // Modern browsers implement TextEncode.
50 return new TextDecoder('utf-8').decode(new Uint8Array(fileBuffer));
51 }
52 else {
53 // Slowest method but sure to be compatible with every platform.
54 const bufView = new Uint8Array(fileBuffer);
55 const bufLength = bufView.length;
56 let result = '';
57 let chunkLength = Math.pow(2, 16) - 1;
58 // We have to chunk it because String.fromCharCode.apply will throw
59 // `Maximum call stack size exceeded` on big inputs.
60 for (let i = 0; i < bufLength; i += chunkLength) {
61 if (i + chunkLength > bufLength) {
62 chunkLength = bufLength - i;
63 }
64 result += String.fromCharCode.apply(null, [...bufView.subarray(i, i + chunkLength)]);
65 }
66 return result;
67 }
68}
69exports.fileBufferToString = fileBufferToString;