1 // 2 // Copyright (c) 2019 Mika Fischer (mika.fischer@zoopnet.de) 3 // 4 // Distributed under the Boost Software License, Version 1.0. (See accompanying 5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 6 // 7 // Official repository: https://github.com/boostorg/beast 8 // 9 10 #ifndef BOOST_BEAST_CORE_DETAIL_WIN32_UNICODE_PATH_HPP 11 #define BOOST_BEAST_CORE_DETAIL_WIN32_UNICODE_PATH_HPP 12 13 #ifdef _WIN32 14 #include <boost/config.hpp> 15 #include <boost/beast/core/error.hpp> 16 #include <boost/winapi/character_code_conversion.hpp> 17 #include <boost/winapi/file_management.hpp> 18 #include <boost/winapi/get_last_error.hpp> 19 #include <array> 20 #include <vector> 21 22 namespace boost { 23 namespace beast { 24 namespace detail { 25 26 class win32_unicode_path 27 { 28 using WCHAR_ = boost::winapi::WCHAR_; 29 30 public: win32_unicode_path(const char * utf8_path,error_code & ec)31 win32_unicode_path(const char* utf8_path, error_code& ec) { 32 int ret = mb2wide(utf8_path, static_buf_.data(), 33 static_buf_.size()); 34 if (ret == 0) 35 { 36 int sz = mb2wide(utf8_path, nullptr, 0); 37 if (sz == 0) 38 { 39 ec.assign(boost::winapi::GetLastError(), 40 system_category()); 41 return; 42 } 43 dynamic_buf_.resize(sz); 44 int ret2 = mb2wide(utf8_path, 45 dynamic_buf_.data(), 46 dynamic_buf_.size()); 47 if (ret2 == 0) 48 { 49 ec.assign(boost::winapi::GetLastError(), 50 system_category()); 51 return; 52 } 53 } 54 } 55 c_str() const56 WCHAR_ const* c_str() const noexcept 57 { 58 return dynamic_buf_.empty() 59 ? static_buf_.data() 60 : dynamic_buf_.data(); 61 } 62 63 private: mb2wide(const char * utf8_path,WCHAR_ * buf,size_t sz)64 int mb2wide(const char* utf8_path, WCHAR_* buf, size_t sz) 65 { 66 return boost::winapi::MultiByteToWideChar( 67 boost::winapi::CP_UTF8_, 68 boost::winapi::MB_ERR_INVALID_CHARS_, 69 utf8_path, -1, 70 buf, static_cast<int>(sz)); 71 } 72 73 std::array<WCHAR_, boost::winapi::MAX_PATH_> static_buf_; 74 std::vector<WCHAR_> dynamic_buf_; 75 }; 76 77 } // detail 78 } // beast 79 } // boost 80 #endif 81 82 #endif 83