aboutsummaryrefslogtreecommitdiff
path: root/c/data.cpp
blob: 1a78ef2cb5e533c71b091962533dcc784ce913ad (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <memory>
#include <vector>

#include "data.h"
#include "win.h"

template <typename T>
inline unsigned char* ValToBuf(const T& val, unsigned char* const buf)
{
	memcpy(buf, &val, sizeof(val));
	return buf+sizeof(val);
}

template <typename T>
inline unsigned char* BufToVal(unsigned char* const buf, T& val)
{
	memcpy(&val, buf, sizeof(val));
	return buf+sizeof(val);
}

DatView::DatView(const wchar_t* const filename, const size_t cb)
{
	hf = CreateFile(filename, GENERIC_READ|GENERIC_WRITE,
	    0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
	if (hf == INVALID_HANDLE_VALUE) {
		if (GetLastError() == ERROR_FILE_NOT_FOUND) {
			hf = CreateFile(filename, GENERIC_READ|GENERIC_WRITE,
			    0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
			if (hf == INVALID_HANDLE_VALUE)
				throw Win32Error{};
		} else
			throw Win32Error{};
	}

	LARGE_INTEGER cbMap;
	cbMap.QuadPart = cb;
	hm = CreateFileMapping(hf, nullptr, PAGE_READWRITE,
	    cbMap.HighPart, cbMap.LowPart, nullptr);
	if (!hm)
		throw Win32Error{};

	view = MapViewOfFile(hm, FILE_MAP_ALL_ACCESS, 0, 0, 0);
	if (!view)
		throw Win32Error{};
}

DatView::~DatView()
{
	FlushViewOfFile(view, 0);
	UnmapViewOfFile(view);
	CloseHandle(hm);
	CloseHandle(hf);
}

unsigned char* Serialize(const ElvData& e, unsigned char* buf)
{
	unsigned char version = 'a';
	buf = ValToBuf(version, buf);
	buf = ValToBuf(e.rating, buf);
	buf = ValToBuf(e.bWatched, buf);
	buf = ValToBuf(e.bTVOriginal, buf);
	buf = ValToBuf(e.sRating, buf);
	buf = ValToBuf(e.siEp, buf);
	buf = ValToBuf(e.title, buf);
	return buf;
}

unsigned char* Unserialize(ElvData& e, unsigned char* buf)
{
	unsigned char version;
	buf = BufToVal(buf, version);
	if (version != 'a')
		return nullptr;

	buf = BufToVal(buf, e.rating);
	buf = BufToVal(buf, e.bWatched);
	buf = BufToVal(buf, e.bTVOriginal);
	buf = BufToVal(buf, e.sRating);
	buf = BufToVal(buf, e.siEp);
	buf = BufToVal(buf, e.title);
	return buf;
}