Replace deprecated wstring_convert (#290)

Co-authored-by: Jonas Borchelt <jonas.borchelt@icloud.com>
This commit is contained in:
Jonas Borchelt
2023-05-16 12:57:05 +02:00
committed by GitHub
parent a068ebd661
commit 4e3dd40cfe
2 changed files with 32 additions and 13 deletions

View File

@@ -24,6 +24,7 @@
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstring>
#include <functional>
#include <iterator>
#include <locale>
@@ -3016,18 +3017,37 @@ namespace jwt {
}
static std::string to_lower_unicode(const std::string& str, const std::locale& loc) {
#if __cplusplus > 201103L
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> conv;
auto wide = conv.from_bytes(str);
std::mbstate_t state = std::mbstate_t();
const char* in_next = str.data();
const char* in_end = str.data() + str.size();
std::wstring wide;
wide.reserve(str.size());
while (in_next != in_end) {
wchar_t wc;
std::size_t result = std::mbrtowc(&wc, in_next, in_end - in_next, &state);
if (result == static_cast<std::size_t>(-1)) {
throw std::runtime_error("encoding error: " + std::string(std::strerror(errno)));
} else if (result == static_cast<std::size_t>(-2)) {
throw std::runtime_error("conversion error: next bytes constitute an incomplete, but so far "
"valid, multibyte character.");
}
in_next += result;
wide.push_back(wc);
}
auto& f = std::use_facet<std::ctype<wchar_t>>(loc);
f.tolower(&wide[0], &wide[0] + wide.size());
return conv.to_bytes(wide);
#else
std::string result;
std::transform(str.begin(), str.end(), std::back_inserter(result),
[&loc](unsigned char c) { return std::tolower(c, loc); });
return result;
#endif
std::string out;
out.reserve(wide.size());
for (wchar_t wc : wide) {
char mb[MB_CUR_MAX];
std::size_t n = std::wcrtomb(mb, wc, &state);
if (n != static_cast<std::size_t>(-1)) out.append(mb, n);
}
return out;
}
};
} // namespace verify_ops

View File

@@ -18,9 +18,8 @@ TEST(HelperTest, Base64DER2PemCert) {
}
TEST(HelperTest, DER2PemCert) {
auto decoded = jwt::base::decode<jwt::alphabet::base64>(
jwt::base::pad<jwt::alphabet::base64>(google_cert_base64_der)
);
auto decoded =
jwt::base::decode<jwt::alphabet::base64>(jwt::base::pad<jwt::alphabet::base64>(google_cert_base64_der));
auto cert_pem = jwt::helper::convert_der_to_pem(decoded);
ASSERT_EQ(google_cert, cert_pem);
}