* Returns bytes from given base64 string. * @param {string} string Base64 string * @param {object} [options] Base64 options * @param {string} [options.alphabet] Base64 alphabet * @param {string} [options.padding='='] Padding character * @param {boolean} [options.paddingOptional=false]
(string, options = {})
| 181 | * @return {string} Base64 string |
| 182 | */ |
| 183 | static bytesFromBase64String (string, options = {}) { |
| 184 | // Compose options |
| 185 | const { |
| 186 | alphabet, |
| 187 | padding, |
| 188 | foreignCharacters, |
| 189 | maxLineLength, |
| 190 | lineSeparator |
| 191 | } = Object.assign({}, defaultBase64Options, options) |
| 192 | |
| 193 | // Translate each character into an octet |
| 194 | const length = string.length |
| 195 | const octets = [] |
| 196 | let character, octet |
| 197 | let i = -1 |
| 198 | |
| 199 | // Go through each character |
| 200 | while (++i < length) { |
| 201 | character = string[i] |
| 202 | |
| 203 | if (maxLineLength !== null && |
| 204 | lineSeparator && |
| 205 | character === lineSeparator[0] && |
| 206 | string.substr(i, lineSeparator.length) === lineSeparator) { |
| 207 | // This is a line separator, skip it |
| 208 | i = i + lineSeparator.length - 1 |
| 209 | } else if (character === padding) { |
| 210 | // This is a pad character, ignore it |
| 211 | } else { |
| 212 | // This is an octet or a foreign character |
| 213 | octet = alphabet.indexOf(character) |
| 214 | if (octet !== -1) { |
| 215 | octets.push(octet) |
| 216 | } else if (!foreignCharacters) { |
| 217 | throw new ByteEncodingError( |
| 218 | `Forbidden character '${character}' at index ${i}`) |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // Calculate original padding and verify it |
| 224 | const paddingSize = (4 - octets.length % 4) % 4 |
| 225 | if (paddingSize === 3) { |
| 226 | throw new ByteEncodingError( |
| 227 | 'A single remaining encoded character in the last quadruple or a ' + |
| 228 | 'padding of 3 characters is not allowed') |
| 229 | } |
| 230 | |
| 231 | // Fill up octets |
| 232 | for (i = 0; i < paddingSize; i++) { |
| 233 | octets.push(0) |
| 234 | } |
| 235 | |
| 236 | // Map pairs of octets (4) to pairs of bytes (3) |
| 237 | const size = octets.length / 4 * 3 |
| 238 | const bytes = new Uint8Array(size) |
| 239 | let j |
| 240 | for (i = 0; i < octets.length; i += 4) { |
no test coverage detected