blob: 62064a35aa344809db1c2e0d4eb9d41702e74352 [file] [log] [blame]
Olivier Deprezf4ef2d02021-04-20 13:36:24 +02001//===--- 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 <string>
17
18namespace llvm {
19
20template <class InputBytes> std::string encodeBase64(InputBytes const &Bytes) {
21 static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
22 "abcdefghijklmnopqrstuvwxyz"
23 "0123456789+/";
24 std::string Buffer;
25 Buffer.resize(((Bytes.size() + 2) / 3) * 4);
26
27 size_t i = 0, j = 0;
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];
36 }
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];
41 Buffer[j + 2] = '=';
42 Buffer[j + 3] = '=';
43 } else if (i + 2 == Bytes.size()) {
44 uint32_t x =
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];
49 Buffer[j + 3] = '=';
50 }
51 return Buffer;
52}
53
54} // end namespace llvm
55
56#endif