-
Notifications
You must be signed in to change notification settings - Fork 86
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Introduce base64 encode & decode in xeus
- Loading branch information
1 parent
26f26e6
commit 9a21035
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
/*************************************************************************** | ||
* Copyright (c) Sylvain Corlay and Johan Mabille and Wolf Vollprecht * | ||
* Copyright (c) QuantStack * | ||
* * | ||
* Distributed under the terms of the BSD 3-Clause License. * | ||
* * | ||
* The full license is in the file LICENSE, distributed with this software. * | ||
****************************************************************************/ | ||
|
||
#ifndef XEUS_BASE64_HPP | ||
#define XEUS_BASE64_HPP | ||
|
||
#include <array> | ||
#include <cstddef> | ||
#include <string> | ||
|
||
namespace xeus | ||
{ | ||
inline std::string base64decode(const std::string& input) | ||
{ | ||
std::array<int, 256> T; | ||
T.fill(-1); | ||
for (std::size_t i = 0; i < 64; ++i) | ||
{ | ||
T[std::size_t("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i])] = int(i); | ||
} | ||
|
||
std::string output; | ||
int val = 0; | ||
int valb = -8; | ||
for (char c : input) | ||
{ | ||
if (T[std::size_t(c)] == -1) | ||
{ | ||
break; | ||
} | ||
val = (val << 6) + T[std::size_t(c)]; | ||
valb += 6; | ||
if (valb >= 0) | ||
{ | ||
output.push_back(char((val >> valb) & 0xFF)); | ||
valb -= 8; | ||
} | ||
} | ||
return output; | ||
} | ||
|
||
inline std::string base64encode(const std::string& input) | ||
{ | ||
std::string output; | ||
int val = 0; | ||
int valb = -6; | ||
for (char sc : input) | ||
{ | ||
unsigned char c = static_cast<unsigned char>(sc); | ||
val = (val << 8) + c; | ||
valb += 8; | ||
while (valb >= 0) | ||
{ | ||
output.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(val >> valb) & 0x3F]); | ||
valb -= 6; | ||
} | ||
} | ||
if (valb > -6) | ||
{ | ||
output.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[((val << 8) >> (valb + 8)) & 0x3F]); | ||
} | ||
while (output.size() % 4) | ||
{ | ||
output.push_back('='); | ||
} | ||
return output; | ||
} | ||
} | ||
#endif |