From f392ded8b3d5ae362838aa87a87b347fdb33ceed Mon Sep 17 00:00:00 2001 From: Antoine Pilote Date: Mon, 5 Aug 2024 23:29:09 -0400 Subject: [PATCH] Added base64 Encore & Decode function --- Nuake/src/Core/String.cpp | 39 +++++++++++++++++++++++++++++++++++++++ Nuake/src/Core/String.h | 3 +++ 2 files changed, 42 insertions(+) diff --git a/Nuake/src/Core/String.cpp b/Nuake/src/Core/String.cpp index 45383b78..d663a8a0 100644 --- a/Nuake/src/Core/String.cpp +++ b/Nuake/src/Core/String.cpp @@ -99,4 +99,43 @@ namespace Nuake return result; } + std::string String::Base64Encode(const std::vector& data) + { + static const char* chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + std::string result; + int val = 0, valb = -6; + for (uint8_t c : data) + { + val = (val << 8) + c; + valb += 8; + while (valb >= 0) + { + result.push_back(chars[(val >> valb) & 0x3F]); + valb -= 6; + } + } + if (valb > -6) result.push_back(chars[((val << 8) >> (valb + 8)) & 0x3F]); + while (result.size() % 4) result.push_back('='); + return result; + } + std::vector String::Base64Decode(const std::string& data) + { + static const std::string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + std::vector out; + std::vector T(256, -1); + for (int i = 0; i < 64; i++) T[chars[i]] = i; + int val = 0, valb = -8; + for (unsigned char c : data) + { + if (T[c] == -1) break; + val = (val << 6) + T[c]; + valb += 6; + if (valb >= 0) + { + out.push_back(uint8_t((val >> valb) & 0xFF)); + valb -= 8; + } + } + return out; + } } \ No newline at end of file diff --git a/Nuake/src/Core/String.h b/Nuake/src/Core/String.h index d4cae7eb..c362a07a 100644 --- a/Nuake/src/Core/String.h +++ b/Nuake/src/Core/String.h @@ -21,5 +21,8 @@ namespace Nuake static float ToFloat(const std::string& string); static std::string ToUpper(const std::string& string); static std::string ToLower(const std::string& string); + + static std::string Base64Encode(const std::vector& data); + static std::vector Base64Decode(const std::string& data); }; }