DNA Calib 1.1
Project brief
Base64.h
Go to the documentation of this file.
1// Copyright Epic Games, Inc. All Rights Reserved.
2
3#pragma once
4
5#ifdef _MSC_VER
6 #pragma warning(push)
7 #pragma warning(disable : 4365 4987)
8#endif
9#include <algorithm>
10#include <cstddef>
11#ifdef _MSC_VER
12 #pragma warning(pop)
13#endif
14
15namespace terse {
16
17static const char* alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
18
19constexpr std::size_t base64encode(std::size_t size) {
20 return ((4ul * size / 3ul) + 3ul) & ~3ul;
21}
22
23// destination should be of length ((4 * size / 3) + 3) & ~3
24inline std::size_t base64encode(char* destination, const char* source, std::size_t size) {
25 char* out = destination;
26
27 int val = 0;
28 int valb = -6;
29
30 for (std::size_t pos = {}; pos < size; ++pos) {
31 const auto c = static_cast<unsigned char>(source[pos]);
32 val = (val << 8) + c;
33 valb += 8;
34 while (valb >= 0) {
35 *out++ = (alphabet[(val >> valb) & 0x3F]);
36 valb -= 6;
37 }
38 }
39
40 if (valb > -6) {
41 *out++ = alphabet[((val << 8) >> (valb + 8)) & 0x3F];
42 }
43
44 while (static_cast<std::size_t>(out - destination) % 4) {
45 *out++ = '=';
46 }
47
48 // Length of base64encoded data
49 return static_cast<std::size_t>(out - destination);
50}
51
52constexpr std::size_t base64decode(std::size_t size) {
53 return (size * 3ul) / 4ul;
54}
55
56// destination should be of length (size / 4) * 3
57inline std::size_t base64decode(char* destination, const char* source, std::size_t size) {
58 char* out = destination;
59
60 int buffer[256];
61 std::fill_n(buffer, 256, -1);
62 for (int i = 0; i < 64; i++) {
63 buffer[static_cast<std::size_t>(alphabet[i])] = i;
64 }
65
66 int val = 0;
67 int valb = -8;
68
69 for (std::size_t pos = {}; pos < size; ++pos) {
70 const auto c = static_cast<unsigned char>(source[pos]);
71 if (buffer[c] == -1) {
72 break;
73 }
74 val = (val << 6) + buffer[c];
75 valb += 6;
76 if (valb >= 0) {
77 *out++ = static_cast<char>((val >> valb) & 0xFF);
78 valb -= 8;
79 }
80 }
81
82 // Length of base64decoded data
83 return static_cast<std::size_t>(out - destination);
84}
85
86} // namespace terse
Definition: Archive.h:14
static const char * alphabet
Definition: Base64.h:17
constexpr std::size_t base64decode(std::size_t size)
Definition: Base64.h:52
constexpr std::size_t base64encode(std::size_t size)
Definition: Base64.h:19