LiteFX 0.3.1.2022
Computer Graphics Engine
string.hpp
1#pragma once
2
3#include <string>
4#include <sstream>
5#include <string_view>
6#include <iterator>
7#include <vector>
8#include <stdexcept>
9
10#if defined _WIN32 || defined WINCE
11#define LITEFX_CODECVT_USE_WIN32
12#include <Windows.h>
13#else
14// Continue using std::codecvt for now, since other platforms than Win32 are currently unsupported anyway.
15#include <codecvt>
16#endif
17
18namespace LiteFX {
19 using String = std::string;
20 using WString = std::wstring;
21 using StringView = std::string_view;
22 using WStringView = std::wstring_view;
23
24 // Based on: https://stackoverflow.com/a/5289170/1254352
25 template <typename TStrings, typename Value = typename TStrings::value_type>
26 String Join(const TStrings& elements, const String& delimiter = "")
27 {
28 std::ostringstream stream;
29
30 auto beg = std::begin(elements);
31 auto end = std::end(elements);
32
33 if (beg != end)
34 {
35 std::copy(beg, std::prev(end), std::ostream_iterator<Value>(stream, delimiter.c_str()));
36 beg = std::prev(end);
37 }
38
39 if (beg != end)
40 stream << *beg;
41
42 return stream.str();
43 }
44
51 {
52#if defined LITEFX_CODECVT_USE_WIN32
53 if (utf8.empty())
54 return L"";
55
56 const auto size = ::MultiByteToWideChar(CP_UTF8, 0, utf8.data(), static_cast<int>(utf8.size()), nullptr, 0);
57
58 if (size <= 0)
59 throw std::runtime_error("Unable to convert string to UTF-16: " + std::to_string(size));
60
61 WString result(size, 0);
62 ::MultiByteToWideChar(CP_UTF8, 0, utf8.data(), static_cast<int>(utf8.size()), result.data(), size);
63
64 return result;
65#else
66 std::wstring_convert<std::codecvt_utf8_utf16<WCHAR>> conv;
67 return conv.from_bytes(utf8);
68#endif
69 }
70
77 {
78#if defined LITEFX_CODECVT_USE_WIN32
79 if (utf16.empty())
80 return "";
81
82 const auto size = ::WideCharToMultiByte(CP_UTF8, 0, utf16.data(), static_cast<int>(utf16.size()), nullptr, 0, nullptr, nullptr);
83
84 if (size <= 0)
85 throw std::runtime_error("Unable to convert string to UTF-8: " + std::to_string(size));
86
87 String result(size, 0);
88 ::WideCharToMultiByte(CP_UTF8, 0, utf16.data(), static_cast<int>(utf16.size()), result.data(), size, nullptr, nullptr);
89
90 return result;
91#else
92 std::wstring_convert<std::codecvt_utf8_utf16<WCHAR>> conv;
93 return conv.to_bytes(utf16);
94#endif
95 }
96}
97
98#undef LITEFX_CODECVT_USE_WIN32
Definition: app.hpp:6
std::string String
Definition: string.hpp:19
String Narrow(WStringView utf16)
Converts an UTF-16 multi-byte encoded string into an UTF-8 representation.
Definition: string.hpp:76
WString Widen(StringView utf8)
Converts an UTF-8 single-byte encoded string into an UTF-16 representation.
Definition: string.hpp:50
std::wstring_view WStringView
Definition: string.hpp:22
std::wstring WString
Definition: string.hpp:20
std::string_view StringView
Definition: string.hpp:21
String Join(const TStrings &elements, const String &delimiter="")
Definition: string.hpp:26