1 //===--- Base64.h - Base64 Encoder/Decoder ----------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file provides generic base64 encoder/decoder.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_SUPPORT_BASE64_H
14 #define LLVM_SUPPORT_BASE64_H
20 template <class InputBytes> std::string encodeBase64(InputBytes const &Bytes) {
21 static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
22 "abcdefghijklmnopqrstuvwxyz"
25 Buffer.resize(((Bytes.size() + 2) / 3) * 4);
28 for (size_t n = Bytes.size() / 3 * 3; i < n; i += 3, j += 4) {
29 uint32_t x = ((unsigned char)Bytes[i] << 16) |
30 ((unsigned char)Bytes[i + 1] << 8) |
31 (unsigned char)Bytes[i + 2];
32 Buffer[j + 0] = Table[(x >> 18) & 63];
33 Buffer[j + 1] = Table[(x >> 12) & 63];
34 Buffer[j + 2] = Table[(x >> 6) & 63];
35 Buffer[j + 3] = Table[x & 63];
37 if (i + 1 == Bytes.size()) {
38 uint32_t x = ((unsigned char)Bytes[i] << 16);
39 Buffer[j + 0] = Table[(x >> 18) & 63];
40 Buffer[j + 1] = Table[(x >> 12) & 63];
43 } else if (i + 2 == Bytes.size()) {
45 ((unsigned char)Bytes[i] << 16) | ((unsigned char)Bytes[i + 1] << 8);
46 Buffer[j + 0] = Table[(x >> 18) & 63];
47 Buffer[j + 1] = Table[(x >> 12) & 63];
48 Buffer[j + 2] = Table[(x >> 6) & 63];
54 } // end namespace llvm