diff --git a/include/of_util.h b/include/of_util.h index e85d023..bbac325 100644 --- a/include/of_util.h +++ b/include/of_util.h @@ -38,10 +38,12 @@ private: template std::shared_ptr OfSingleton::instance = nullptr; template std::once_flag OfSingleton::init_flag; -class OfUtil { +class OfUtil +{ public: OfUtil(); ~OfUtil(); + public: static ofString now_time(); }; @@ -231,4 +233,17 @@ private: std::condition_variable cv_; }; +class CCodec +{ +public: + CCodec() = default; + ~CCodec() = default; + +public: +#ifdef _WIN32 + static std::string u8ToGBK(const std::string& str); + static std::string GBKTou8(const std::string& str); +#endif +}; + } // namespace ofen diff --git a/src/of_util.cpp b/src/of_util.cpp index f5bbdc5..ea3bbf8 100644 --- a/src/of_util.cpp +++ b/src/of_util.cpp @@ -3,6 +3,10 @@ #include #include +#ifdef _WIN32 +#include +#endif + namespace ofen { void CMutBuffer::push(const char* data, int len) { @@ -27,7 +31,11 @@ void CMutBuffer::remove_of(int start_pos, int len) if (start_pos < 0 || start_pos >= static_cast(buffer_.size()) || len <= 0) { return; } +#ifdef _WIN32 + auto end_pos = min(start_pos + len, static_cast(buffer_.size())); +#else auto end_pos = std::min(start_pos + len, static_cast(buffer_.size())); +#endif buffer_.erase(buffer_.begin() + start_pos, buffer_.begin() + end_pos); } @@ -66,4 +74,44 @@ ofString OfUtil::now_time() oss << std::put_time(&tm_now, "%Y-%m-%d %H:%M:%S"); return oss.str(); } + +#ifdef _WIN32 +std::string CCodec::u8ToGBK(const std::string& str) +{ + int wideCharLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0); + if (wideCharLen <= 0) { + return ""; + } + std::wstring wideStr(wideCharLen, L'\0'); + MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &wideStr[0], wideCharLen); + int gbkLen = WideCharToMultiByte(CP_ACP, 0, wideStr.c_str(), -1, nullptr, 0, nullptr, nullptr); + if (gbkLen <= 0) { + return ""; + } + std::string gbkStr(gbkLen, '\0'); + WideCharToMultiByte(CP_ACP, 0, wideStr.c_str(), -1, &gbkStr[0], gbkLen, nullptr, nullptr); + + gbkStr.resize(gbkLen - 1); + return gbkStr; +} +std::string CCodec::GBKTou8(const std::string& str) +{ + int wideCharLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0); + if (wideCharLen <= 0) { + return ""; + } + std::wstring wideStr(wideCharLen, L'\0'); + MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, &wideStr[0], wideCharLen); + + int utf8Len = WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, nullptr, 0, nullptr, nullptr); + if (utf8Len <= 0) { + return ""; + } + std::string utf8Str(utf8Len, '\0'); + WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, &utf8Str[0], utf8Len, nullptr, nullptr); + + utf8Str.resize(utf8Len - 1); + return utf8Str; +} +#endif } // namespace ofen