libosmscout 1.1.1
Loading...
Searching...
No Matches
Base64.h
Go to the documentation of this file.
1
2#ifndef LIBOSMSCOUT_BASE64_H
3#define LIBOSMSCOUT_BASE64_H
4
9
10#include <cstdint>
11#include <string>
12#include <sstream>
13#include <iostream>
14#include <vector>
15
16namespace osmscout {
17
18 constexpr const char *Base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
19
20 static inline std::string Base64Encode(const std::vector<char> &in)
21 {
22 std::string out;
23
24 uint32_t val = 0;
25 int32_t valb = -6;
26 for (char jj : in) {
27 unsigned char c = (unsigned char)jj;
28 val = (val << 8) + c;
29 valb += 8;
30 while (valb >= 0) {
31 out.push_back(Base64Chars[(val >> valb) & 0x3F]);
32 valb -= 6;
33 }
34 }
35 if (valb > -6) {
36 out.push_back(Base64Chars[((val << 8) >> (valb + 8)) & 0x3F]);
37 }
38
39 while ((out.size() % 4)!=0) {
40 out.push_back('=');
41 }
42
43 return out;
44 }
45
46 static inline std::vector<char> Base64Decode(const std::string &in)
47 {
48 std::vector<char> out;
49
50 std::vector<int> T(256, -1);
51 for (int i = 0; i < 64; i++) T[Base64Chars[i]] = i;
52
53 uint32_t val = 0;
54 int32_t valb = -8;
55 for (char c : in) {
56 if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
57 continue; // skip whitespaces
58 }
59
60 if (T[c] == -1) {
61 break; // terminate on invalid character
62 }
63
64 val = (val << 6) + T[c];
65 valb += 6;
66 if (valb >= 0) {
67 out.push_back(char((val >> valb) & 0xFF));
68 valb -= 8;
69 }
70 }
71 return out;
72 }
73}
74
75#endif //LIBOSMSCOUT_BASE64_H
Definition Area.h:39
constexpr const char * Base64Chars
Definition Base64.h:18
static std::vector< char > Base64Decode(const std::string &in)
Definition Base64.h:46
static std::string Base64Encode(const std::vector< char > &in)
Definition Base64.h:20