LLVM 22.0.0git
Base64.h
Go to the documentation of this file.
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
17#include "llvm/Support/Error.h"
18#include <cstdint>
19#include <string>
20#include <vector>
21
22namespace llvm {
23
24template <class InputBytes> std::string encodeBase64(InputBytes const &Bytes) {
25 static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
26 "abcdefghijklmnopqrstuvwxyz"
27 "0123456789+/";
28 std::string Buffer;
29 Buffer.resize(((Bytes.size() + 2) / 3) * 4);
30
31 size_t i = 0, j = 0;
32 for (size_t n = Bytes.size() / 3 * 3; i < n; i += 3, j += 4) {
33 uint32_t x = ((unsigned char)Bytes[i] << 16) |
34 ((unsigned char)Bytes[i + 1] << 8) |
35 (unsigned char)Bytes[i + 2];
36 Buffer[j + 0] = Table[(x >> 18) & 63];
37 Buffer[j + 1] = Table[(x >> 12) & 63];
38 Buffer[j + 2] = Table[(x >> 6) & 63];
39 Buffer[j + 3] = Table[x & 63];
40 }
41 if (i + 1 == Bytes.size()) {
42 uint32_t x = ((unsigned char)Bytes[i] << 16);
43 Buffer[j + 0] = Table[(x >> 18) & 63];
44 Buffer[j + 1] = Table[(x >> 12) & 63];
45 Buffer[j + 2] = '=';
46 Buffer[j + 3] = '=';
47 } else if (i + 2 == Bytes.size()) {
48 uint32_t x =
49 ((unsigned char)Bytes[i] << 16) | ((unsigned char)Bytes[i + 1] << 8);
50 Buffer[j + 0] = Table[(x >> 18) & 63];
51 Buffer[j + 1] = Table[(x >> 12) & 63];
52 Buffer[j + 2] = Table[(x >> 6) & 63];
53 Buffer[j + 3] = '=';
54 }
55 return Buffer;
56}
57
59 std::vector<char> &Output);
60
61} // end namespace llvm
62
63#endif
#define LLVM_ABI
Definition: Compiler.h:213
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::string encodeBase64(InputBytes const &Bytes)
Definition: Base64.h:24
LLVM_ABI llvm::Error decodeBase64(llvm::StringRef Input, std::vector< char > &Output)
Definition: Base64.cpp:37