(buffer, base)
| 41 | * @returns {string} encoded buffer |
| 42 | */ |
| 43 | const encode = (buffer, base) => { |
| 44 | if (buffer.length === 0) return ""; |
| 45 | const alphabet = ENCODE_TABLE[base]; |
| 46 | const bigIntBase = BigInt(alphabet.length); |
| 47 | // Leading zero bytes are not significant in the BigInt below, so they would be |
| 48 | // lost; Base58Check-style, re-emit each as one leading alphabet[0] char. Keeps |
| 49 | // the encoding reversible and its length tracking the input (prefix-stable slices). |
| 50 | let zeros = 0; |
| 51 | while (zeros < buffer.length && buffer[zeros] === 0) zeros++; |
| 52 | // Convert buffer to BigInt efficiently using bitwise operations |
| 53 | let value = ZERO; |
| 54 | for (let i = 0; i < buffer.length; i++) { |
| 55 | value = (value << EIGHT) | BigInt(buffer[i]); |
| 56 | } |
| 57 | // Convert to baseX string efficiently using array |
| 58 | /** @type {string[]} */ |
| 59 | const digits = []; |
| 60 | while (value > ZERO) { |
| 61 | const remainder = Number(value % bigIntBase); |
| 62 | digits.push(alphabet[remainder]); |
| 63 | value /= bigIntBase; |
| 64 | } |
| 65 | // Pushed last so they land first after the reverse below. |
| 66 | for (let i = 0; i < zeros; i++) digits.push(alphabet[0]); |
| 67 | return digits.reverse().join(""); |
| 68 | }; |
| 69 | |
| 70 | /** |
| 71 | * Returns buffer. |
no test coverage detected