UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

76 lines (75 loc) 2.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TextCodec = void 0; const primitives_1 = require("../guards/primitives"); const specials_1 = require("../guards/specials"); const helpers_1 = require("./helpers"); const utils_1 = require("./utils"); class TextCodec { constructor() { } static isValidHex(hex) { return (0, specials_1.isHexString)(hex); } static isValidBinary(binary) { return (0, specials_1.isBinaryString)(binary); } static isValidBase64(b64) { return (0, specials_1.isBase64)(b64); } static utf8ToHex(text, spaced = true) { return [...(0, utils_1.utf8ToBytes)(text)] .map((b) => (0, helpers_1._padStartWith0)(b, 'hex')) .join(spaced ? ' ' : ''); } static utf8ToBinary(text, spaced = true) { return [...(0, utils_1.utf8ToBytes)(text)] .map((b) => (0, helpers_1._padStartWith0)(b, 'binary')) .join(spaced ? ' ' : ''); } static hexToUtf8(hex) { return (0, utils_1.bytesToUtf8)((0, utils_1.hexToBytes)(hex)); } static binaryToUtf8(binary) { if (!(0, specials_1.isBinaryString)(binary)) return ''; const bytes = (0, helpers_1._splitByCharLength)(binary, 8).map((b) => parseInt(b, 2)); return (0, utils_1.bytesToUtf8)(new Uint8Array(bytes)); } static hexToBinary(hex, spaced = true) { if (!(0, specials_1.isHexString)(hex)) return ''; return (0, helpers_1._splitByCharLength)(hex, 2) .map((h) => (0, helpers_1._padStartWith0)(parseInt(h, 16), 'binary')) .join(spaced ? ' ' : ''); } static binaryToHex(binary, spaced = true) { if (!(0, specials_1.isBinaryString)(binary)) return ''; return (0, helpers_1._splitByCharLength)(binary, 8) .map((b) => (0, helpers_1._padStartWith0)(parseInt(b, 2), 'hex')) .join(spaced ? ' ' : ''); } static base64ToUtf8(b64) { if (!(0, specials_1.isBase64)(b64)) return ''; return (0, utils_1.bytesToUtf8)((0, utils_1.base64ToBytes)(b64)); } static utf8ToBase64(text) { if (!(0, primitives_1.isNonEmptyString)(text)) return ''; return (0, utils_1.bytesToBase64)((0, utils_1.utf8ToBytes)(text)); } static base64ToHex(b64, spaced = true) { return TextCodec.utf8ToHex(TextCodec.base64ToUtf8(b64), spaced); } static base64ToBinary(b64, spaced = true) { return TextCodec.utf8ToBinary(TextCodec.base64ToUtf8(b64), spaced); } static hexToBase64(hex) { return TextCodec.utf8ToBase64(TextCodec.hexToUtf8(hex)); } static binaryToBase64(binary) { return TextCodec.utf8ToBase64(TextCodec.binaryToUtf8(binary)); } } exports.TextCodec = TextCodec;