|
| 1 | +import { Coder } from "./Coder"; |
| 2 | + |
| 3 | +export class Base85Encoder implements Coder { |
| 4 | + |
| 5 | + from = "text"; |
| 6 | + to = "base85"; |
| 7 | + |
| 8 | + transform(text: string): string { |
| 9 | + const encoder = new TextEncoder(); |
| 10 | + const bytes = encoder.encode(text); |
| 11 | + let base85 = ""; |
| 12 | + |
| 13 | + for (let i = 0; i < bytes.length; i += 4) { |
| 14 | + let chunk = 0; |
| 15 | + for (let j = 0; j < 4; j++) { |
| 16 | + chunk = (chunk << 8) | (bytes[i + j] || 0); |
| 17 | + } |
| 18 | + for (let j = 4; j >= 0; j--) { |
| 19 | + base85 += String.fromCharCode((chunk / (85 ** j) % 85) + 33); |
| 20 | + } |
| 21 | + } |
| 22 | + return base85; |
| 23 | + } |
| 24 | + |
| 25 | + checkInput(text: string): boolean { |
| 26 | + // Ensure the input is a non-empty string |
| 27 | + return typeof text === "string" && text.length > 0; |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +export class Base85Decoder implements Coder { |
| 32 | + |
| 33 | + from = "base85"; |
| 34 | + to = "text"; |
| 35 | + |
| 36 | + transform(text: string): string { |
| 37 | + if (!this.checkInput(text)) { |
| 38 | + throw new Error("Invalid Base85 input"); |
| 39 | + } |
| 40 | + |
| 41 | + const decoder = new TextDecoder(); |
| 42 | + const chunks = text.match(/.{1,5}/g) || []; |
| 43 | + const bytes = []; |
| 44 | + |
| 45 | + for (const chunk of chunks) { |
| 46 | + let value = 0; |
| 47 | + for (let i = 0; i < chunk.length; i++) { |
| 48 | + value = value * 85 + (chunk.charCodeAt(i) - 33); |
| 49 | + } |
| 50 | + |
| 51 | + for (let i = 3; i >= 0; i--) { |
| 52 | + bytes.push((value >> (i * 8)) & 0xff); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return decoder.decode(new Uint8Array(bytes).filter(byte => byte !== 0)); |
| 57 | + } |
| 58 | + |
| 59 | + checkInput(text: string): boolean { |
| 60 | + // Check if the input is a valid Base64 string |
| 61 | +// const base64Regex = /^[A-Za-z0-9+/=]+$/; |
| 62 | +// return typeof text === "string" && base64Regex.test(text) && text.length % 4 === 0; |
| 63 | + return true; |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments