-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase64_module.cpp
More file actions
67 lines (58 loc) · 2.1 KB
/
Copy pathbase64_module.cpp
File metadata and controls
67 lines (58 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// base64_module.cpp
// C++ extension (built with pybind11) exposing a fast file -> base64 encoder
// to Python. Build with setup.py (see README).
#include <pybind11/pybind11.h>
#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>
namespace py = pybind11;
static const char* kB64Chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static std::string base64_encode(const std::vector<unsigned char>& data) {
std::string encoded;
encoded.reserve(((data.size() + 2) / 3) * 4);
size_t i = 0;
while (i + 2 < data.size()) {
unsigned int n = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2];
encoded += kB64Chars[(n >> 18) & 0x3F];
encoded += kB64Chars[(n >> 12) & 0x3F];
encoded += kB64Chars[(n >> 6) & 0x3F];
encoded += kB64Chars[n & 0x3F];
i += 3;
}
size_t remaining = data.size() - i;
if (remaining == 1) {
unsigned int n = data[i] << 16;
encoded += kB64Chars[(n >> 18) & 0x3F];
encoded += kB64Chars[(n >> 12) & 0x3F];
encoded += "==";
} else if (remaining == 2) {
unsigned int n = (data[i] << 16) | (data[i + 1] << 8);
encoded += kB64Chars[(n >> 18) & 0x3F];
encoded += kB64Chars[(n >> 12) & 0x3F];
encoded += kB64Chars[(n >> 6) & 0x3F];
encoded += "=";
}
return encoded;
}
// Reads a file from disk and returns its contents as a base64 string.
// Equivalent to the Python read_b64() helper, just implemented in C++.
std::string read_file_b64(const std::string& path) {
std::ifstream f(path, std::ios::binary);
if (!f) {
throw std::runtime_error("Cannot open file: " + path);
}
std::vector<unsigned char> buffer(
(std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
return base64_encode(buffer);
}
PYBIND11_MODULE(fastb64, m) {
m.doc() = "Fast base64 file encoder implemented in C++, used from Python";
m.def("read_file_b64", &read_file_b64,
"Read a file from disk and return its base64-encoded contents",
py::arg("path"));
}