NBEngine/engine/NBCore/Utils.hpp

84 lines
2.1 KiB
C++

#pragma once
#include <cstdlib>
#include <type_traits>
#ifndef _NB_CORE_TYPES
#define _NB_CORE_TYPES
#include <string>
namespace nb {
#ifdef _NB_TARGET_WINDOWS
const std::string NEWLINE = "\r\n";
const std::wstring WNEWLINE = L"\r\n";
#endif // _NB_TARGET_WINDOWS
#ifdef _NB_TARGET_LINUX
const std::string NEWLINE = "\n";
const std::wstring WNEWLINE = L"\n";
#endif // _NB_TARGET_LINUX
template<typename T>
std::enable_if_t<std::is_convertible_v<const T&, std::string>, std::wstring> str_to_wstr(const T& in) {
std::string str(in);
std::wstring ret(str.begin(), str.end());
return ret;
}
template<typename T>
std::enable_if_t<std::is_convertible_v<const T&, std::wstring>, std::string> wstr_to_str(const T& in) {
std::wstring wstr(in);
std::size_t wstrlen = wstr.length();
char* c_str= new char[wstrlen];
std::wcstombs(c_str, wstr.c_str(), wstrlen);
std::string ret(c_str, wstrlen);
delete[] c_str;
return ret;
}
template <typename T = std::string, typename A, typename B, typename C>
T find_and_replace(
const A& original,
const B& find,
const C& replace
) {
const T& original_t = T(original);
const T& find_t = T(find);
const T& replace_t = T(replace);
T ret = original_t;
std::size_t find_len = find_t.length();
std::size_t replace_len = replace_t.length();
std::size_t currpos = 0;
std::size_t lastpos = 0;
while(true) {
lastpos = currpos;
currpos = original_t.find(find_t, lastpos);
if (currpos == T::npos) {
break;
}
ret = ret.erase(currpos, find_len);
ret = ret.insert(currpos, replace_t);
currpos += replace_len;
}
return ret;
}
/* template<typename T>
T swap_endian(const T& val) {
T ret;
const int size = sizeof(T);
auto retLoc = static_cast<void*>(&ret);
auto valLoc = static_cast<const void*>(&val);
for (int i = 0; i < size; ++i) {
memcpy(retLoc+i, valLoc+(size-i-1), 1);
}
return ret;
} */
// using ByteVector = std::vector<uint8_t>;
} // namespace nb
#endif // _NB_CORE_TYPES