UNPKG

ox

Version:

Ethereum Standard Library

70 lines 2.81 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fromBytes = fromBytes; exports.fromHex = fromHex; exports.fromString = fromString; exports.toBytes = toBytes; exports.toHex = toHex; exports.toString = toString; const Bytes = require("./Bytes.js"); const Hex = require("./Hex.js"); const encoder = new TextEncoder(); const decoder = new TextDecoder(); const integerToCharacter = Object.fromEntries(Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/').map((a, i) => [i, a.charCodeAt(0)])); const characterToInteger = { ...Object.fromEntries(Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/').map((a, i) => [a.charCodeAt(0), i])), ['='.charCodeAt(0)]: 0, ['-'.charCodeAt(0)]: 62, ['_'.charCodeAt(0)]: 63, }; function fromBytes(value, options = {}) { const { pad = true, url = false } = options; const encoded = new Uint8Array(Math.ceil(value.length / 3) * 4); for (let i = 0, j = 0; j < value.length; i += 4, j += 3) { const y = (value[j] << 16) + (value[j + 1] << 8) + (value[j + 2] | 0); encoded[i] = integerToCharacter[y >> 18]; encoded[i + 1] = integerToCharacter[(y >> 12) & 0x3f]; encoded[i + 2] = integerToCharacter[(y >> 6) & 0x3f]; encoded[i + 3] = integerToCharacter[y & 0x3f]; } const k = value.length % 3; const end = Math.floor(value.length / 3) * 4 + (k && k + 1); let base64 = decoder.decode(new Uint8Array(encoded.buffer, 0, end)); if (pad && k === 1) base64 += '=='; if (pad && k === 2) base64 += '='; if (url) base64 = base64.replaceAll('+', '-').replaceAll('/', '_'); return base64; } function fromHex(value, options = {}) { return fromBytes(Bytes.fromHex(value), options); } function fromString(value, options = {}) { return fromBytes(Bytes.fromString(value), options); } function toBytes(value) { const base64 = value.replace(/=+$/, ''); const size = base64.length; const decoded = new Uint8Array(size + 3); encoder.encodeInto(base64 + '===', decoded); for (let i = 0, j = 0; i < base64.length; i += 4, j += 3) { const x = (characterToInteger[decoded[i]] << 18) + (characterToInteger[decoded[i + 1]] << 12) + (characterToInteger[decoded[i + 2]] << 6) + characterToInteger[decoded[i + 3]]; decoded[j] = x >> 16; decoded[j + 1] = (x >> 8) & 0xff; decoded[j + 2] = x & 0xff; } const decodedSize = (size >> 2) * 3 + (size % 4 && (size % 4) - 1); return new Uint8Array(decoded.buffer, 0, decodedSize); } function toHex(value) { return Hex.fromBytes(toBytes(value)); } function toString(value) { return Bytes.toString(toBytes(value)); } //# sourceMappingURL=Base64.js.map