@deepkit/core
Version:
Deepkit core library
61 lines • 2.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.base64ToUint8Array = exports.uint8ArrayToUtf8 = exports.createBuffer = void 0;
exports.bufferConcat = bufferConcat;
exports.bufferToString = bufferToString;
exports.nativeBase64ToUint8Array = nativeBase64ToUint8Array;
function __assignType(fn, args) {
fn.__type = args;
return fn;
}
/**
* Create a buffer of the given size (uninitialized, so it may contain random data).
*
* Note that the result is either Uin8Array or Buffer, depending on the environment.
* Buffer from NodeJS works slightly different than Uint8Array.
*/
exports.createBuffer = 'undefined' !== typeof Buffer && 'function' === typeof Buffer.allocUnsafe ? Buffer.allocUnsafe : __assignType((size) => new Uint8Array(size), ['size', '', 'P"2!"/"']);
/**
* Concat multiple buffers into one.
*/
function bufferConcat(chunks, length) {
if (undefined === length) {
length = 0;
for (const chunk of chunks)
length += chunk.length;
}
const result = (0, exports.createBuffer)(length);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
bufferConcat.__type = ['chunks', 'length', 'bufferConcat', 'PWF2!\'2"8W/#'];
const textEncoder = new TextDecoder();
exports.uint8ArrayToUtf8 = 'undefined' !== typeof Buffer ? __assignType((buffer) => Buffer.from(buffer).toString('utf8'), ['buffer', '', 'PW2!"/"']) : __assignType((buffer) => textEncoder.decode(buffer), ['buffer', '', 'PW2!"/"']);
/**
* Convert a buffer to a string.
*/
function bufferToString(buffer) {
if ('string' === typeof buffer)
return buffer;
return (0, exports.uint8ArrayToUtf8)(buffer);
}
bufferToString.__type = ['buffer', 'bufferToString', 'PP&WJ2!&/"'];
function nativeBase64ToUint8Array(base64) {
const raw = atob(base64);
const rawLength = raw.length;
const array = (0, exports.createBuffer)(rawLength);
for (let i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
nativeBase64ToUint8Array.__type = ['base64', 'nativeBase64ToUint8Array', 'P&2!W/"'];
/**
* Converts a base64 string to a Uint8Array.
*/
exports.base64ToUint8Array = 'undefined' === typeof Buffer ? nativeBase64ToUint8Array : __assignType((base64) => Buffer.from(base64, 'base64'), ['base64', '', 'P&2!"/"']);
//# sourceMappingURL=buffer.js.map