aboutsummaryrefslogtreecommitdiff
path: root/c/wcharptr.cpp
blob: e406ed195611d4b48685d4dc2acb7e0dd212c6cd (plain)
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
53
54
55
56
57
58
59
60
61
62
63
64
#include <utility>
#include <windows.h>

#include "wcharptr.h"
#include "win.h"

wchar_ptr::wchar_ptr() noexcept {}

wchar_ptr::wchar_ptr(wchar_t* const s) noexcept : m_p(s) {}

wchar_ptr& wchar_ptr::operator=(wchar_t* const s) noexcept
{
	if (m_p != s) {
		delete m_p;
		m_p = s;
	}
	return *this;
}

wchar_ptr::wchar_ptr(wchar_ptr&& other) noexcept
	: m_p(std::exchange(other.m_p, nullptr)) {}

wchar_ptr& wchar_ptr::operator=(wchar_ptr&& other) noexcept
{
	std::swap(m_p, other.m_p);
	return *this;
}

wchar_ptr::operator wchar_t*() noexcept
{
	return m_p;
}

wchar_t* wchar_ptr::release() noexcept
{
	wchar_t* p2 = m_p;
	m_p = nullptr;
	return p2;
}

wchar_ptr::~wchar_ptr() noexcept
{
	delete m_p;
}

wchar_ptr wchar_ptr::from_narrow(const char* const src, const int cp)
{
	int cbMultiByte = strlen(src)+1;
	int cchWideChar = MultiByteToWideChar(cp, 0, src, cbMultiByte, NULL, 0);
	wchar_t* dst = new wchar_t[cchWideChar];
	if (!MultiByteToWideChar(cp, 0, src, cbMultiByte, dst, cchWideChar)) {
		delete dst;
		throw Win32Error();
	}
	return dst;
}

wchar_ptr wchar_ptr::copy(const wchar_t* const src)
{
	const int cb = wcslen(src)+1;
	wchar_t* dst = new wchar_t[cb];
	memcpy(dst, src, cb*sizeof(wchar_t));
	return dst;
}