libosmscout  1.1.1
Base64.h
Go to the documentation of this file.
1 
2 #ifndef LIBOSMSCOUT_BASE64_H
3 #define LIBOSMSCOUT_BASE64_H
4 
10 #include <string>
11 #include <sstream>
12 #include <iostream>
13 #include <vector>
14 
15 namespace osmscout {
16 
17  constexpr const char *Base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
18 
19  static inline std::string Base64Encode(const std::vector<char> &in)
20  {
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 
49  std::vector<char> out;
50 
51  std::vector<int> T(256, -1);
52  for (int i = 0; i < 64; i++) T[Base64Chars[i]] = i;
53 
54  uint32_t val = 0;
55  int32_t valb = -8;
56  for (char c : in) {
57  if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
58  continue; // skip whitespaces
59  }
60 
61  if (T[c] == -1) {
62  break; // terminate on invalid character
63  }
64 
65  val = (val << 6) + T[c];
66  valb += 6;
67  if (valb >= 0) {
68  out.push_back(char((val >> valb) & 0xFF));
69  valb -= 8;
70  }
71  }
72  return out;
73  }
74 }
75 
76 #endif //LIBOSMSCOUT_BASE64_H
static std::vector< char > Base64Decode(const std::string &in)
Definition: Base64.h:46
Definition: Area.h:38
constexpr const char * Base64Chars
Definition: Base64.h:17
static std::string Base64Encode(const std::vector< char > &in)
Definition: Base64.h:19