(data, base)
| 74 | * @returns {Buffer} buffer |
| 75 | */ |
| 76 | const decode = (data, base) => { |
| 77 | if (data.length === 0) return Buffer.from(""); |
| 78 | const alphabet = ENCODE_TABLE[base]; |
| 79 | const bigIntBase = BigInt(alphabet.length); |
| 80 | // Leading alphabet[0] chars decode back to leading zero bytes (inverse of encode). |
| 81 | const zeroChar = alphabet[0]; |
| 82 | let zeros = 0; |
| 83 | while (zeros < data.length && data[zeros] === zeroChar) zeros++; |
| 84 | // Convert the baseX string to a BigInt value |
| 85 | let value = ZERO; |
| 86 | for (let i = 0; i < data.length; i++) { |
| 87 | const digit = alphabet.indexOf(data[i]); |
| 88 | if (digit === -1) { |
| 89 | throw new Error(`Invalid character at position ${i}: ${data[i]}`); |
| 90 | } |
| 91 | value = value * bigIntBase + BigInt(digit); |
| 92 | } |
| 93 | // Significant byte count of the numeric part (excludes the leading zeros above) |
| 94 | let temp = value; |
| 95 | let numLength = 0; |
| 96 | while (temp > ZERO) { |
| 97 | temp >>= EIGHT; |
| 98 | numLength++; |
| 99 | } |
| 100 | // Create buffer and fill the numeric part from right to left, leaving the |
| 101 | // leading `zeros` bytes as 0. |
| 102 | const buffer = Buffer.alloc(zeros + numLength); |
| 103 | for (let i = zeros + numLength - 1; i >= zeros; i--) { |
| 104 | buffer[i] = Number(value & FF); |
| 105 | value >>= EIGHT; |
| 106 | } |
| 107 | return buffer; |
| 108 | }; |
| 109 | |
| 110 | // Compatibility with the old hash libraries, they can return different structures, so let's stringify them firstly |
| 111 |
no outgoing calls
no test coverage detected