From 4e3dd40cfef9f06fa48c8a8d804405ec196885cf Mon Sep 17 00:00:00 2001 From: Jonas Borchelt Date: Tue, 16 May 2023 12:57:05 +0200 Subject: [PATCH] Replace deprecated wstring_convert (#290) Co-authored-by: Jonas Borchelt --- include/jwt-cpp/jwt.h | 40 ++++++++++++++++++++++++++++++---------- tests/HelperTest.cpp | 5 ++--- 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/include/jwt-cpp/jwt.h b/include/jwt-cpp/jwt.h index b257cdd..a51edf9 100644 --- a/include/jwt-cpp/jwt.h +++ b/include/jwt-cpp/jwt.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -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, 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(-1)) { + throw std::runtime_error("encoding error: " + std::string(std::strerror(errno))); + } else if (result == static_cast(-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>(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(-1)) out.append(mb, n); + } + + return out; } }; } // namespace verify_ops diff --git a/tests/HelperTest.cpp b/tests/HelperTest.cpp index 9164875..558ca90 100644 --- a/tests/HelperTest.cpp +++ b/tests/HelperTest.cpp @@ -18,9 +18,8 @@ TEST(HelperTest, Base64DER2PemCert) { } TEST(HelperTest, DER2PemCert) { - auto decoded = jwt::base::decode( - jwt::base::pad(google_cert_base64_der) - ); + auto decoded = + jwt::base::decode(jwt::base::pad(google_cert_base64_der)); auto cert_pem = jwt::helper::convert_der_to_pem(decoded); ASSERT_EQ(google_cert, cert_pem); }