From b8e9f6f48210a7f68fd602e361b56c6235fd4425 Mon Sep 17 00:00:00 2001 From: 0xFEEDC0DE64 Date: Thu, 30 Jun 2022 06:56:08 +0200 Subject: [PATCH] Add toBase64String() --- src/strutils.cpp | 29 +++++++++++++++++++++++++++++ src/strutils.h | 6 ++++++ 2 files changed, 35 insertions(+) diff --git a/src/strutils.cpp b/src/strutils.cpp index c900145..3c1656d 100644 --- a/src/strutils.cpp +++ b/src/strutils.cpp @@ -78,6 +78,35 @@ tl::expected, std::string> fromHexString(std::s return result; } +std::string toBase64String(std::basic_string_view buf) +{ + constexpr std::string_view base64_chars{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}; + + std::string out; + + int val = 0; + int valb = -6; + for (unsigned char c : buf) + { + val = (val << 8) + c; + valb += 8; + + while (valb >= 0) + { + out.push_back(base64_chars[(val>>valb)&0x3F]); + valb -= 6; + } + } + + if (valb>-6) + out.push_back(base64_chars[((val << 8) >> (valb + 8)) & 0x3F]); + + while (out.size() % 4) + out.push_back('='); + + return out; +} + bool stringEqualsIgnoreCase(std::string_view a, std::string_view b) { if (a.size() != b.size()) diff --git a/src/strutils.h b/src/strutils.h index 6ef8eb7..068c5bc 100644 --- a/src/strutils.h +++ b/src/strutils.h @@ -44,6 +44,12 @@ inline std::string toHexString(std::string_view str) tl::expected, std::string> fromHexString(std::string_view hex); +std::string toBase64String(std::basic_string_view buf); +inline std::string toBase64String(std::string_view str) +{ + return toBase64String(std::basic_string_view{reinterpret_cast(str.data()), str.size()}); +} + bool stringEqualsIgnoreCase(std::string_view a, std::string_view b); //void stringReplaceAll(char search, char replace, std::string &subject);