-
Notifications
You must be signed in to change notification settings - Fork 23
/
Utf16StringBuf.h
52 lines (44 loc) · 1.21 KB
/
Utf16StringBuf.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#pragma once
class Utf16StringBuf
{
public:
Utf16StringBuf() : m_pBuf(nullptr), m_cwch(0) {}
Utf16StringBuf(const Utf16StringBuf&) = delete;
Utf16StringBuf(const Utf16StringBuf&&) = delete;
Utf16StringBuf(UINT cp, LPCCH psz, size_t cch)
{
FromBytes(cp, psz, cch);
}
~Utf16StringBuf()
{
if (m_pBuf != m_wcsBuf) free(m_pBuf);
}
operator const char16_t*() const { return (char16_t*)m_pBuf; }
operator const wchar_t*() const { return m_pBuf; }
__declspec(property(get = getCount)) size_t Count;
size_t getCount() const { return m_cwch; }
void FromBytes(UINT cp, LPCCH psz, size_t cch)
{
if (cch < _countof(m_wcsBuf))
{
m_pBuf = m_wcsBuf;
}
else
{
m_pBuf = reinterpret_cast<WCHAR*>(malloc((cch + 1) * sizeof(WCHAR)));
}
m_cwch = static_cast<size_t>(::MultiByteToWideChar(cp, 0, psz, cch, m_pBuf, cch));
ASSERT(m_cwch <= cch);
m_pBuf[m_cwch] = 0;
}
size_t ToUtf8(uint8_t* pDest = nullptr, size_t cchDest = 0) const
{
int cch = ::WideCharToMultiByte(CP_UTF8, 0, m_pBuf, m_cwch, reinterpret_cast<LPSTR>(pDest), cchDest, nullptr, nullptr);
ASSERT(cch >= 0);
return static_cast<size_t>(cch);
}
private:
WCHAR* m_pBuf;
size_t m_cwch;
WCHAR m_wcsBuf[256-sizeof(void*)-sizeof(size_t)];
};