UNPKG

@nurliman/base85

Version:

Browser and Node.js-compatible Base85 encoder/decoder.

77 lines (74 loc) 2.66 kB
// src/utils.ts function charCodeArrayToString(charCodes) { let output = ""; for (let i = 0; i < charCodes.length; i++) { output += String.fromCharCode(charCodes[i]); } return output; } // src/decode.ts function decodeBase85(input) { const ASCII_OFFSET = 33; const BASE85_BLOCK_SIZE = 5; const BYTE_MASK = 255; input = input.replace(/^<~/g, "").replace(/~>$/g, ""); if (!input) return ""; input = input.replace(/\s/g, "").replace("z", "!!!!!"); const paddingLength = input.length % BASE85_BLOCK_SIZE || BASE85_BLOCK_SIZE; const paddingCharacters = "uuuuu".slice(paddingLength); input += paddingCharacters; const decodedBytes = []; for (let chunkStart = 0; input.length > chunkStart; chunkStart += 5) { const decodedChunk = 52200625 * (input.charCodeAt(chunkStart) - ASCII_OFFSET) + 614125 * (input.charCodeAt(chunkStart + 1) - ASCII_OFFSET) + 7225 * (input.charCodeAt(chunkStart + 2) - ASCII_OFFSET) + 85 * (input.charCodeAt(chunkStart + 3) - ASCII_OFFSET) + (input.charCodeAt(chunkStart + 4) - ASCII_OFFSET); decodedBytes.push( BYTE_MASK & decodedChunk >> 24, BYTE_MASK & decodedChunk >> 16, BYTE_MASK & decodedChunk >> 8, BYTE_MASK & decodedChunk ); } if (paddingCharacters.length > 0) { decodedBytes.splice(-paddingCharacters.length); } return charCodeArrayToString(decodedBytes); } // src/encode.ts function encodeBase85(input, { wrap = true } = {}) { if (!input) return wrap ? "<~~>" : ""; const paddingLength = input.length % 4 || 4; const paddingCharacters = "\0\0\0\0".slice(paddingLength); input += paddingCharacters; const encodedArray = []; for (let index = 0; index < input.length; index += 4) { let charCodeSum = (input.charCodeAt(index) << 24) + (input.charCodeAt(index + 1) << 16) + (input.charCodeAt(index + 2) << 8) + input.charCodeAt(index + 3); if (charCodeSum !== 0) { const encodedChars = []; for (let j = 0; j < 5; j++) { const encodedChar = charCodeSum % 85; charCodeSum = (charCodeSum - encodedChar) / 85; encodedChars.unshift(encodedChar + 33); } encodedArray.push(...encodedChars); } else { encodedArray.push(122); } } if (paddingCharacters.length > 0) { encodedArray.splice(-paddingCharacters.length); } const encodedString = charCodeArrayToString(encodedArray); const output = wrap ? `<~${encodedString}~>` : encodedString; return output; } // src/index.ts var base85 = { encode: encodeBase85, decode: decodeBase85 }; var src_default = base85; export { decodeBase85, src_default as default, encodeBase85 }; //# sourceMappingURL=index.js.map