|
| 1 | +module.exports = function fromBase64(string /* , options */) { |
| 2 | + aString(string); |
| 3 | + var options = arguments.length > 1 ? anObjectOrUndefined(arguments[1]) : undefined; |
| 4 | + var alphabet = getAlphabetOption(options) === 'base64' ? base64Alphabet : base64UrlAlphabet; |
| 5 | + var strict = options ? !!options.strict : false; |
| 6 | + |
| 7 | + var input = strict ? string : replace(string, SPACES, ''); |
| 8 | + |
| 9 | + if (input.length % 4 === 0) { |
| 10 | + if (stringSlice(input, -2) === '==') input = stringSlice(input, 0, -2); |
| 11 | + else if (stringSlice(input, -1) === '=') input = stringSlice(input, 0, -1); |
| 12 | + } else if (strict) throw new SyntaxError('Input is not correctly padded'); |
| 13 | + |
| 14 | + var lastChunkSize = input.length % 4; |
| 15 | + |
| 16 | + switch (lastChunkSize) { |
| 17 | + case 1: throw new SyntaxError('Bad input length'); |
| 18 | + case 2: input += 'AA'; break; |
| 19 | + case 3: input += 'A'; |
| 20 | + } |
| 21 | + |
| 22 | + var bytes = []; |
| 23 | + var i = 0; |
| 24 | + var inputLength = input.length; |
| 25 | + |
| 26 | + var at = function (shift) { |
| 27 | + var chr = charAt(input, i + shift); |
| 28 | + if (!hasOwn(alphabet, chr)) throw new SyntaxError('Bad char in input: "' + chr + '"'); |
| 29 | + return alphabet[chr] << (18 - 6 * shift); |
| 30 | + }; |
| 31 | + |
| 32 | + for (; i < inputLength; i += 4) { |
| 33 | + var triplet = at(0) + at(1) + at(2) + at(3); |
| 34 | + push(bytes, (triplet >> 16) & 255, (triplet >> 8) & 255, triplet & 255); |
| 35 | + } |
| 36 | + |
| 37 | + var byteLength = bytes.length; |
| 38 | + |
| 39 | + if (lastChunkSize === 2) { |
| 40 | + if (strict && bytes[byteLength - 2] !== 0) throw new SyntaxError(EXTRA_BITS); |
| 41 | + byteLength -= 2; |
| 42 | + } else if (lastChunkSize === 3) { |
| 43 | + if (strict && bytes[byteLength - 1] !== 0) throw new SyntaxError(EXTRA_BITS); |
| 44 | + byteLength--; |
| 45 | + } |
| 46 | + |
| 47 | + return arrayFromConstructorAndList(Uint8Array, bytes, byteLength); |
| 48 | +}; |
0 commit comments