arrbuffstr
Version:
Creates Strings from ArrayBuffers and viceversa in NodeJS and the Browser
105 lines (98 loc) • 3.33 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.arrbuffstr = factory());
}(this, (function () { 'use strict';
var Env;
(function (Env) {
Env["Browser"] = "Browser";
Env["Node"] = "Node";
})(Env || (Env = {}));
function getEnv() {
if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
return Env.Browser;
}
if (typeof process !== 'undefined' &&
process.versions !== null &&
process.versions.node !== null) {
return Env.Node;
}
throw new Error('Current runtime environment is not supported');
}
function toArrayBufferFactory(env) {
if (env === Env.Browser) {
if ('TextEncoder' in window) {
return (str) => {
const encoder = new TextEncoder();
const unint8 = encoder.encode(str);
return unint8.buffer;
};
}
return (str) => {
const raw = String.raw `${str}`;
const buff = new ArrayBuffer(raw.length * 2);
const strLength = raw.length;
const uint16 = new Uint16Array(buff);
let i = 0;
for (i; i < strLength; i++) {
uint16[i] = raw.charCodeAt(i);
}
return buff;
};
}
if ('TextEncoder' in global) {
return (str) => {
const encoder = new TextEncoder();
const unint8 = encoder.encode(str);
return unint8.buffer;
};
}
return (str) => {
const raw = String.raw `${str}`;
const buff = new ArrayBuffer(raw.length * 2);
const strLength = raw.length;
const uint16 = new Uint16Array(buff);
let i = 0;
for (i; i < strLength; i++) {
uint16[i] = raw.charCodeAt(i);
}
return buff;
};
}
function toStringFactory(env) {
if (env === Env.Browser) {
if ('TextDecoder' in window) {
return (arrbuff) => {
const decoder = new TextDecoder('utf-8');
return decoder.decode(arrbuff);
};
}
return (arrbuff) => {
return String.fromCharCode.apply(null, new Uint16Array(arrbuff));
};
}
if ('TextDecoder' in global) {
return (arrbuff) => {
const decoder = new TextDecoder('utf-8');
return decoder.decode(arrbuff);
};
}
return (arrbuff) => {
return String.fromCharCode.apply(null, new Uint16Array(arrbuff));
};
}
function make() {
const currentEnv = getEnv();
if (currentEnv === 'Node') {
return {
toArrayBuffer: toArrayBufferFactory(Env.Node),
toString: toStringFactory(Env.Node),
};
}
return {
toArrayBuffer: toArrayBufferFactory(Env.Browser),
toString: toStringFactory(Env.Browser),
};
}
return make;
})));