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 <cstdint> 17 #include <string> 18 19 namespace llvm { 20 21 template <class InputBytes> std::string encodeBase64(InputBytes const &Bytes) { 22 static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 23 "abcdefghijklmnopqrstuvwxyz" 24 "0123456789+/"; 25 std::string Buffer; 26 Buffer.resize(((Bytes.size() + 2) / 3) * 4); 27 28 size_t i = 0, j = 0; 29 for (size_t n = Bytes.size() / 3 * 3; i < n; i += 3, j += 4) { 30 uint32_t x = ((unsigned char)Bytes[i] << 16) | 31 ((unsigned char)Bytes[i + 1] << 8) | 32 (unsigned char)Bytes[i + 2]; 33 Buffer[j + 0] = Table[(x >> 18) & 63]; 34 Buffer[j + 1] = Table[(x >> 12) & 63]; 35 Buffer[j + 2] = Table[(x >> 6) & 63]; 36 Buffer[j + 3] = Table[x & 63]; 37 } 38 if (i + 1 == Bytes.size()) { 39 uint32_t x = ((unsigned char)Bytes[i] << 16); 40 Buffer[j + 0] = Table[(x >> 18) & 63]; 41 Buffer[j + 1] = Table[(x >> 12) & 63]; 42 Buffer[j + 2] = '='; 43 Buffer[j + 3] = '='; 44 } else if (i + 2 == Bytes.size()) { 45 uint32_t x = 46 ((unsigned char)Bytes[i] << 16) | ((unsigned char)Bytes[i + 1] << 8); 47 Buffer[j + 0] = Table[(x >> 18) & 63]; 48 Buffer[j + 1] = Table[(x >> 12) & 63]; 49 Buffer[j + 2] = Table[(x >> 6) & 63]; 50 Buffer[j + 3] = '='; 51 } 52 return Buffer; 53 } 54 55 } // end namespace llvm 56 57 #endif 58