aboutsummaryrefslogtreecommitdiff
path: root/zenstore/basicfile.cpp
blob: cfc77e2a52aa99672e78ed03796285a6e88ab004 (plain) (blame)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright Epic Games, Inc. All Rights Reserved.

#include "zenstore/basicfile.h"

#include <zencore/except.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/testing.h>
#include <zencore/testutils.h>

#include <fmt/format.h>
#include <gsl/gsl-lite.hpp>

namespace zen {

using namespace fmt::literals;

BasicFile::~BasicFile()
{
	Close();
}

void
BasicFile::Open(std::filesystem::path FileName, bool IsCreate)
{
	std::error_code Ec;
	Open(FileName, IsCreate, Ec);

	if (Ec)
	{
		throw std::system_error(Ec, "failed to open file '{}'"_format(FileName));
	}
}

void
BasicFile::Open(std::filesystem::path FileName, bool IsCreate, std::error_code& Ec)
{
	Ec.clear();

	const DWORD dwCreationDisposition = IsCreate ? CREATE_ALWAYS : OPEN_EXISTING;
	DWORD		dwDesiredAccess		  = GENERIC_READ | GENERIC_WRITE;
	const DWORD dwShareMode			  = FILE_SHARE_READ;
	const DWORD dwFlagsAndAttributes  = FILE_ATTRIBUTE_NORMAL;
	HANDLE		hTemplateFile		  = nullptr;

	if (IsCreate)
	{
		dwDesiredAccess |= DELETE;
	}

	HANDLE FileHandle = CreateFile(FileName.c_str(),
								   dwDesiredAccess,
								   dwShareMode,
								   /* lpSecurityAttributes */ nullptr,
								   dwCreationDisposition,
								   dwFlagsAndAttributes,
								   hTemplateFile);

	if (FileHandle == INVALID_HANDLE_VALUE)
	{
		Ec = zen::MakeErrorCodeFromLastError();

		return;
	}

	m_FileHandle = FileHandle;
}

void
BasicFile::Close()
{
	if (m_FileHandle)
	{
		::CloseHandle(m_FileHandle);
		m_FileHandle = nullptr;
	}
}

void
BasicFile::Read(void* Data, uint64_t BytesToRead, uint64_t FileOffset)
{
	const uint64_t MaxChunkSize = 2u * 1024 * 1024 * 1024;

	while (BytesToRead)
	{
		const uint64_t NumberOfBytesToRead = Min(BytesToRead, MaxChunkSize);

		OVERLAPPED Ovl{};

		Ovl.Offset	   = DWORD(FileOffset & 0xffff'ffffu);
		Ovl.OffsetHigh = DWORD(FileOffset >> 32);

		DWORD dwNumberOfBytesRead = 0;
		BOOL  Success			  = ::ReadFile(m_FileHandle, Data, DWORD(NumberOfBytesToRead), &dwNumberOfBytesRead, &Ovl);

		ZEN_ASSERT(dwNumberOfBytesRead == NumberOfBytesToRead);

		if (!Success)
		{
			ThrowLastError("Failed to read from file '{}'"_format(zen::PathFromHandle(m_FileHandle)));
		}

		BytesToRead -= NumberOfBytesToRead;
		FileOffset += NumberOfBytesToRead;
		Data = reinterpret_cast<uint8_t*>(Data) + NumberOfBytesToRead;
	}
}

IoBuffer
BasicFile::ReadAll()
{
	IoBuffer Buffer(FileSize());
	Read(Buffer.MutableData(), Buffer.Size(), 0);
	return Buffer;
}

void
BasicFile::StreamFile(std::function<void(const void* Data, uint64_t Size)>&& ChunkFun)
{
	StreamByteRange(0, FileSize(), std::move(ChunkFun));
}

void
BasicFile::StreamByteRange(uint64_t FileOffset, uint64_t Size, std::function<void(const void* Data, uint64_t Size)>&& ChunkFun)
{
	const uint64_t ChunkSize = 128 * 1024;
	IoBuffer	   ReadBuffer{ChunkSize};
	void*		   BufferPtr = ReadBuffer.MutableData();

	uint64_t RemainBytes   = Size;
	uint64_t CurrentOffset = FileOffset;

	while (RemainBytes)
	{
		const uint64_t ThisChunkBytes = zen::Min(ChunkSize, RemainBytes);

		Read(BufferPtr, ThisChunkBytes, CurrentOffset);

		ChunkFun(BufferPtr, ThisChunkBytes);

		CurrentOffset += ThisChunkBytes;
		RemainBytes -= ThisChunkBytes;
	}
}

void 
BasicFile::Write(MemoryView Data, uint64_t FileOffset, std::error_code& Ec)
{
	Write(Data.GetData(), Data.GetSize(), FileOffset, Ec);
}

void
BasicFile::Write(const void* Data, uint64_t Size, uint64_t FileOffset, std::error_code& Ec)
{
	Ec.clear();

	const uint64_t MaxChunkSize = 2u * 1024 * 1024 * 1024;

	while (Size)
	{
		const uint64_t NumberOfBytesToWrite = Min(Size, MaxChunkSize);

		OVERLAPPED Ovl{};

		Ovl.Offset	   = DWORD(FileOffset & 0xffff'ffffu);
		Ovl.OffsetHigh = DWORD(FileOffset >> 32);

		DWORD dwNumberOfBytesWritten = 0;

		BOOL Success = ::WriteFile(m_FileHandle, Data, DWORD(NumberOfBytesToWrite), &dwNumberOfBytesWritten, &Ovl);

		if (!Success)
		{
			Ec = MakeErrorCodeFromLastError();

			return;
		}

		Size -= NumberOfBytesToWrite;
		FileOffset += NumberOfBytesToWrite;
		Data = reinterpret_cast<const uint8_t*>(Data) + NumberOfBytesToWrite;
	}
}

void
BasicFile::Write(MemoryView Data, uint64_t FileOffset)
{
	Write(Data.GetData(), Data.GetSize(), FileOffset);
}

void
BasicFile::Write(const void* Data, uint64_t Size, uint64_t Offset)
{
	std::error_code Ec;
	Write(Data, Size, Offset, Ec);

	if (Ec)
	{
		throw std::system_error(Ec, "Failed to write to file '{}'"_format(zen::PathFromHandle(m_FileHandle)));
	}
}

void
BasicFile::WriteAll(IoBuffer Data, std::error_code& Ec)
{
	Write(Data.Data(), Data.Size(), 0, Ec);
}

void
BasicFile::Flush()
{
	FlushFileBuffers(m_FileHandle);
}

uint64_t
BasicFile::FileSize()
{
	ULARGE_INTEGER liFileSize;
	liFileSize.LowPart = ::GetFileSize(m_FileHandle, &liFileSize.HighPart);

	return uint64_t(liFileSize.QuadPart);
}

//////////////////////////////////////////////////////////////////////////

TemporaryFile::~TemporaryFile()
{
	Close();
}

void
TemporaryFile::Close()
{
	if (m_FileHandle)
	{
		// Mark file for deletion when final handle is closed

		FILE_DISPOSITION_INFO Fdi{.DeleteFile = TRUE};

		SetFileInformationByHandle(m_FileHandle, FileDispositionInfo, &Fdi, sizeof Fdi);

		BasicFile::Close();
	}
}

void
TemporaryFile::CreateTemporary(std::filesystem::path TempDirName, std::error_code& Ec)
{
	StringBuilder<64> TempName;
	Oid::NewOid().ToString(TempName);

	m_TempPath = TempDirName / TempName.c_str();

	const bool IsCreate = true;

	Open(m_TempPath, IsCreate, Ec);
}

void
TemporaryFile::MoveTemporaryIntoPlace(std::filesystem::path FinalFileName, std::error_code& Ec)
{
	// We intentionally call the base class Close() since otherwise we'll end up
	// deleting the temporary file
	BasicFile::Close();

	std::filesystem::rename(m_TempPath, FinalFileName, Ec);
}

/*
		___________              __
		\__    ___/___   _______/  |_  ______
		  |    |_/ __ \ /  ___/\   __\/  ___/
		  |    |\  ___/ \___ \  |  |  \___ \
		  |____| \___  >____  > |__| /____  >
					 \/     \/            \/
*/

#if ZEN_WITH_TESTS

TEST_CASE("BasicFile")
{
	ScopedCurrentDirectoryChange _;

	BasicFile File1;
	CHECK_THROWS(File1.Open("zonk", false));
	CHECK_NOTHROW(File1.Open("zonk", true));
	CHECK_NOTHROW(File1.Write("abcd", 4, 0));
	CHECK(File1.FileSize() == 4);
	{
		IoBuffer Data = File1.ReadAll();
		CHECK(Data.Size() == 4);
		CHECK_EQ(memcmp(Data.Data(), "abcd", 4), 0);
	}
	CHECK_NOTHROW(File1.Write("efgh", 4, 2));
	CHECK(File1.FileSize() == 6);
	{
		IoBuffer Data = File1.ReadAll();
		CHECK(Data.Size() == 6);
		CHECK_EQ(memcmp(Data.Data(), "abefgh", 6), 0);
	}
}

TEST_CASE("TemporaryFile")
{
	ScopedCurrentDirectoryChange _;

	SUBCASE("DeleteOnClose")
	{
		TemporaryFile	TmpFile;
		std::error_code Ec;
		TmpFile.CreateTemporary(std::filesystem::current_path(), Ec);
		CHECK(!Ec);
		CHECK(std::filesystem::exists(TmpFile.GetPath()));
		TmpFile.Close();
		CHECK(std::filesystem::exists(TmpFile.GetPath()) == false);
	}

	SUBCASE("MoveIntoPlace")
	{
		TemporaryFile	TmpFile;
		std::error_code Ec;
		TmpFile.CreateTemporary(std::filesystem::current_path(), Ec);
		CHECK(!Ec);
		std::filesystem::path TempPath	= TmpFile.GetPath();
		std::filesystem::path FinalPath = std::filesystem::current_path() / "final";
		CHECK(std::filesystem::exists(TempPath));
		TmpFile.MoveTemporaryIntoPlace(FinalPath, Ec);
		CHECK(!Ec);
		CHECK(std::filesystem::exists(TempPath) == false);
		CHECK(std::filesystem::exists(FinalPath));
	}
}

void
basicfile_forcelink()
{
}

#endif

}  // namespace zen