1 //===--- Base64.h - Base64 Encoder/Decoder ----------------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides generic base64 encoder/decoder.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_SUPPORT_BASE64_H
14 #define LLVM_SUPPORT_BASE64_H
15 
16 #include "llvm/Support/Error.h"
17 #include <cstdint>
18 #include <string>
19 #include <vector>
20 
21 namespace llvm {
22 
23 template <class InputBytes> std::string encodeBase64(InputBytes const &Bytes) {
24   static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25                               "abcdefghijklmnopqrstuvwxyz"
26                               "0123456789+/";
27   std::string Buffer;
28   Buffer.resize(((Bytes.size() + 2) / 3) * 4);
29 
30   size_t i = 0, j = 0;
31   for (size_t n = Bytes.size() / 3 * 3; i < n; i += 3, j += 4) {
32     uint32_t x = ((unsigned char)Bytes[i] << 16) |
33                  ((unsigned char)Bytes[i + 1] << 8) |
34                  (unsigned char)Bytes[i + 2];
35     Buffer[j + 0] = Table[(x >> 18) & 63];
36     Buffer[j + 1] = Table[(x >> 12) & 63];
37     Buffer[j + 2] = Table[(x >> 6) & 63];
38     Buffer[j + 3] = Table[x & 63];
39   }
40   if (i + 1 == Bytes.size()) {
41     uint32_t x = ((unsigned char)Bytes[i] << 16);
42     Buffer[j + 0] = Table[(x >> 18) & 63];
43     Buffer[j + 1] = Table[(x >> 12) & 63];
44     Buffer[j + 2] = '=';
45     Buffer[j + 3] = '=';
46   } else if (i + 2 == Bytes.size()) {
47     uint32_t x =
48         ((unsigned char)Bytes[i] << 16) | ((unsigned char)Bytes[i + 1] << 8);
49     Buffer[j + 0] = Table[(x >> 18) & 63];
50     Buffer[j + 1] = Table[(x >> 12) & 63];
51     Buffer[j + 2] = Table[(x >> 6) & 63];
52     Buffer[j + 3] = '=';
53   }
54   return Buffer;
55 }
56 
57 llvm::Error decodeBase64(llvm::StringRef Input, std::vector<char> &Output);
58 
59 } // end namespace llvm
60 
61 #endif
62