|
| 1 | +// imported from https://github.com/socketio/base64-arraybuffer |
| 2 | +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; |
| 3 | + |
| 4 | +// Use a lookup table to find the index. |
| 5 | +const lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); |
| 6 | +for (let i = 0; i < chars.length; i++) { |
| 7 | + lookup[chars.charCodeAt(i)] = i; |
| 8 | +} |
| 9 | + |
| 10 | +export const encode = (arraybuffer: ArrayBuffer): string => { |
| 11 | + let bytes = new Uint8Array(arraybuffer), |
| 12 | + i, |
| 13 | + len = bytes.length, |
| 14 | + base64 = ''; |
| 15 | + |
| 16 | + for (i = 0; i < len; i += 3) { |
| 17 | + base64 += chars[bytes[i] >> 2]; |
| 18 | + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; |
| 19 | + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; |
| 20 | + base64 += chars[bytes[i + 2] & 63]; |
| 21 | + } |
| 22 | + |
| 23 | + if (len % 3 === 2) { |
| 24 | + base64 = base64.substring(0, base64.length - 1) + '='; |
| 25 | + } else if (len % 3 === 1) { |
| 26 | + base64 = base64.substring(0, base64.length - 2) + '=='; |
| 27 | + } |
| 28 | + |
| 29 | + return base64; |
| 30 | +}; |
| 31 | + |
| 32 | +export const decode = (base64: string): ArrayBuffer => { |
| 33 | + let bufferLength = base64.length * 0.75, |
| 34 | + len = base64.length, |
| 35 | + i, |
| 36 | + p = 0, |
| 37 | + encoded1, |
| 38 | + encoded2, |
| 39 | + encoded3, |
| 40 | + encoded4; |
| 41 | + |
| 42 | + if (base64[base64.length - 1] === '=') { |
| 43 | + bufferLength--; |
| 44 | + if (base64[base64.length - 2] === '=') { |
| 45 | + bufferLength--; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + const arraybuffer = new ArrayBuffer(bufferLength), |
| 50 | + bytes = new Uint8Array(arraybuffer); |
| 51 | + |
| 52 | + for (i = 0; i < len; i += 4) { |
| 53 | + encoded1 = lookup[base64.charCodeAt(i)]; |
| 54 | + encoded2 = lookup[base64.charCodeAt(i + 1)]; |
| 55 | + encoded3 = lookup[base64.charCodeAt(i + 2)]; |
| 56 | + encoded4 = lookup[base64.charCodeAt(i + 3)]; |
| 57 | + |
| 58 | + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); |
| 59 | + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); |
| 60 | + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); |
| 61 | + } |
| 62 | + |
| 63 | + return arraybuffer; |
| 64 | +}; |
0 commit comments