66 lines
1.9 KiB
C++
66 lines
1.9 KiB
C++
#ifndef XENITH_PLATFORM_H
|
|
#define XENITH_PLATFORM_H
|
|
// platform.h — небольшие кроссплатформенные помощники.
|
|
//
|
|
// Главное здесь — конвертация UTF-8 ↔ std::filesystem::path. На Windows
|
|
// std::filesystem::path из std::string трактует байты как ANSI, поэтому путь
|
|
// с кириллицей («модель.xnh») ломался. На POSIX конвертация — no-op.
|
|
#pragma once
|
|
|
|
#include <ctime>
|
|
#include <filesystem>
|
|
#include <string>
|
|
|
|
#ifdef _WIN32
|
|
# ifndef WIN32_LEAN_AND_MEAN
|
|
# define WIN32_LEAN_AND_MEAN
|
|
# endif
|
|
# ifndef NOMINMAX
|
|
# define NOMINMAX
|
|
# endif
|
|
# include <windows.h>
|
|
#endif
|
|
|
|
namespace xt {
|
|
|
|
inline std::filesystem::path path_from_utf8(const std::string& s) {
|
|
#ifdef _WIN32
|
|
if (s.empty()) return {};
|
|
const int n = ::MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), nullptr, 0);
|
|
if (n <= 0) return std::filesystem::path(s);
|
|
std::wstring w((size_t)n, L'\0');
|
|
::MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), w.data(), n);
|
|
return std::filesystem::path(w);
|
|
#else
|
|
return std::filesystem::path(s);
|
|
#endif
|
|
}
|
|
|
|
inline std::string path_to_utf8(const std::filesystem::path& p) {
|
|
#ifdef _WIN32
|
|
const std::wstring w = p.wstring();
|
|
if (w.empty()) return {};
|
|
const int n = ::WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(),
|
|
nullptr, 0, nullptr, nullptr);
|
|
if (n <= 0) return {};
|
|
std::string s((size_t)n, '\0');
|
|
::WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), s.data(), n, nullptr, nullptr);
|
|
return s;
|
|
#else
|
|
return p.string();
|
|
#endif
|
|
}
|
|
|
|
// Кроссплатформенный gmtime (POSIX gmtime_r / Windows gmtime_s).
|
|
inline void gmtime_portable(const std::time_t* t, std::tm* out) {
|
|
#ifdef _WIN32
|
|
gmtime_s(out, t);
|
|
#else
|
|
gmtime_r(t, out);
|
|
#endif
|
|
}
|
|
|
|
} // namespace xt
|
|
|
|
#endif // XENITH_PLATFORM_H
|