From 5095c2e2ba9aadf468514804fb3a872d10fdc17d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Ankarstr=C3=B6m?= Date: Tue, 16 Aug 2022 04:37:48 +0200 Subject: Implement preliminary IO. It might be a good idea to eschew the structs and access the data directly from the view. Alternatively, the serialization functions might be rewritten to simply memcpy the structs, after either adding __attribute__((packed)) or ensuring consistent padding. --- c/data.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'c/data.cpp') diff --git a/c/data.cpp b/c/data.cpp index e28378e..1a78ef2 100644 --- a/c/data.cpp +++ b/c/data.cpp @@ -1,6 +1,8 @@ #include +#include #include "data.h" +#include "win.h" template inline unsigned char* ValToBuf(const T& val, unsigned char* const buf) @@ -16,6 +18,40 @@ inline unsigned char* BufToVal(unsigned char* const buf, T& 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'; -- cgit v1.2.3