From 23a1d79a662a17398a3ea2c12bc818eedff24756 Mon Sep 17 00:00:00 2001 From: yhirose Date: Fri, 2 Jan 2026 20:45:01 -0500 Subject: [PATCH] Fix #2318 --- httplib.h | 20 ++++++++++++-------- test/test.cc | 15 +++++++++++++++ 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/httplib.h b/httplib.h index 5c2c287..e40e7f6 100644 --- a/httplib.h +++ b/httplib.h @@ -2443,16 +2443,20 @@ namespace detail { #if defined(_WIN32) inline std::wstring u8string_to_wstring(const char *s) { - std::wstring ws; + if (!s) { return std::wstring(); } + auto len = static_cast(strlen(s)); + if (!len) { return std::wstring(); } + auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0); - if (wlen > 0) { - ws.resize(wlen); - wlen = ::MultiByteToWideChar( - CP_UTF8, 0, s, len, - const_cast(reinterpret_cast(ws.data())), wlen); - if (wlen != static_cast(ws.size())) { ws.clear(); } - } + if (!wlen) { return std::wstring(); } + + std::wstring ws; + ws.resize(wlen); + wlen = ::MultiByteToWideChar( + CP_UTF8, 0, s, len, + const_cast(reinterpret_cast(ws.data())), wlen); + if (wlen != static_cast(ws.size())) { ws.clear(); } return ws; } #endif diff --git a/test/test.cc b/test/test.cc index e1fa239..41f072b 100644 --- a/test/test.cc +++ b/test/test.cc @@ -14086,3 +14086,18 @@ TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) { EXPECT_EQ(received_last_event_ids[1], "event-0"); } } + +TEST(Issue2318Test, EmptyHostString) { + { + httplib::Client cli_empty("", PORT); + auto res = cli_empty.Get("/"); + ASSERT_FALSE(res); + EXPECT_EQ(httplib::Error::Connection, res.error()); + } + { + httplib::Client cli(" ", PORT); + auto res = cli.Get("/"); + ASSERT_FALSE(res); + EXPECT_EQ(httplib::Error::Connection, res.error()); + } +}