|
| 1 | +// rewrite from https://github.com/beatgammit/base64-js |
| 2 | +import { lookup } from './config' |
| 3 | + |
| 4 | + |
| 5 | +export function fromUint8Array(input: Uint8Array): string { |
| 6 | + /* tslint:disable: no-bitwise */ |
| 7 | + const len = input.length |
| 8 | + const extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes |
| 9 | + const len2 = len - extraBytes |
| 10 | + const maxChunkLength = 12000 // must be multiple of 3 |
| 11 | + const parts: string[] = new Array( |
| 12 | + Math.ceil(len2 / maxChunkLength) + (extraBytes ? 1 : 0), |
| 13 | + ) |
| 14 | + let curChunk = 0 |
| 15 | + |
| 16 | + // go through the array every three bytes, we'll deal with trailing stuff later |
| 17 | + for (let i = 0, nextI = 0; i < len2; i = nextI) { |
| 18 | + nextI = i + maxChunkLength |
| 19 | + parts[curChunk] = encodeChunk(input, i, Math.min(nextI, len2)) |
| 20 | + curChunk += 1 |
| 21 | + } |
| 22 | + |
| 23 | + // pad the end with zeros, but make sure to not forget the extra bytes |
| 24 | + if (extraBytes === 1) { |
| 25 | + const tmp = input[len2] & 0xFF |
| 26 | + parts[curChunk] = lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '==' |
| 27 | + } |
| 28 | + else if (extraBytes === 2) { |
| 29 | + const tmp = (input[len2] & 0xFF) << 8 | (input[len2 + 1] & 0xFF) |
| 30 | + parts[curChunk] = lookup[tmp >> 10] + |
| 31 | + lookup[tmp >> 4 & 0x3F] + |
| 32 | + lookup[tmp << 2 & 0x3F] + |
| 33 | + '=' |
| 34 | + } |
| 35 | + |
| 36 | + /* tslint:enable: no-bitwise */ |
| 37 | + return parts.join('') |
| 38 | +} |
| 39 | + |
| 40 | + |
| 41 | +function encodeChunk(input: Uint8Array, start: number, end: number): string { |
| 42 | + /* tslint:disable: no-bitwise */ |
| 43 | + if (start > end) { |
| 44 | + throw new Error('parameters of start should less then end') |
| 45 | + } |
| 46 | + const ret: string[] = new Array((end - start) / 3) |
| 47 | + for (let i = start, curTriplet = 0; i < end; i += 3) { |
| 48 | + ret[curTriplet++] = tripletToBase64( |
| 49 | + (input[i] & 0xFF) << 16 | |
| 50 | + (input[i + 1] & 0xFF) << 8 | |
| 51 | + (input[i + 2] & 0xFF), |
| 52 | + ) |
| 53 | + } |
| 54 | + /* tslint:enable: no-bitwise */ |
| 55 | + return ret.join('') |
| 56 | +} |
| 57 | + |
| 58 | +function tripletToBase64(pos: number): string { |
| 59 | + /* tslint:disable: no-bitwise */ |
| 60 | + const ret = lookup[pos >> 18 & 0x3F] + |
| 61 | + lookup[pos >> 12 & 0x3F] + |
| 62 | + lookup[pos >> 6 & 0x3F] + |
| 63 | + lookup[pos & 0x3F] |
| 64 | + |
| 65 | + /* tslint:enable: no-bitwise */ |
| 66 | + return ret |
| 67 | +} |
0 commit comments