aboutsummaryrefslogtreecommitdiff
path: root/app/source/Cplt/Utils/IO/FileStream_Custom.inl
blob: 004dd017940c4c6f495780661dd3edc789ba8a61 (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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Note: included by FileStream.cpp conditionally, not compiled separately
#include "FileStream.hpp"

#include <cstring>
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

#if defined(_WIN32)
#	define WIN32_LEAN_AND_MEAN
#	define NOMINMAX
#	include <Windows.h>

InputFileStream::InputFileStream(const fs::path& path)
	: mOsFileHandle{ 0 }
{
	auto handle = reinterpret_cast<HANDLE*>(mOsFileHandle);

	*handle = CreateFileW(
		path.c_str(), // fs::path::c_str() returns a wide string on Windows
		GENERIC_READ,
		/* No sharing */ 0,
		/* Use default security*/ nullptr,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		/* No attribute template */ nullptr);

	// TODO handle error
}

InputFileStream::~InputFileStream()
{
	auto handle = reinterpret_cast<HANDLE*>(mOsFileHandle);
	CloseHandle(*handle);
}

OutputFileStream::OutputFileStream(const fs::path& path, WriteMode mode)
	: mOsFileHandle{ 0 }
{
	auto handle = reinterpret_cast<HANDLE*>(mOsFileHandle);

	DWORD creationDisposition;
	switch (mode) {
		case AppendFile: creationDisposition = OPEN_ALWAYS; break;
		case TruncateFile: creationDisposition = CREATE_ALWAYS; break;
	}

	*handle = CreateFileW(
		path.c_str(),
		GENERIC_WRITE,
		/* No sharing */ 0,
		/* Use default security*/ nullptr,
		creationDisposition,
		FILE_ATTRIBUTE_NORMAL,
		/* No attribute template */ nullptr);

	// TODO handle error
}

OutputFileStream::~OutputFileStream()
{
	auto handle = reinterpret_cast<HANDLE*>(mOsFileHandle);
	CloseHandle(*handle);
}

static IoResult::ErrorKind MapErrorCodeToIoResult(DWORD error)
{
	switch (error) {
		// TODO

        default:
			std::cerr << "Unimplemented win32 error code " << error << ", report bug immediately.\n";
			std::abort();
	}
}

static IoResult ReadBytesDirect(HANDLE hFile, size_t byteCount, std::byte* bytes)
{
	DWORD bytesRead;
	BOOL result = ReadFile(hFile, bytes, byteCount, &bytesRead, nullptr);

	if (result) {
		return IoResult{
			.Error = IoResult::ERR_None,
			.SystemError = 0,
			.BytesMoved = bytesRead,
		};
	} else {
		DWORD errorCode = GetLastError();
		return IoResult{
			.Error = ::MapErrorCodeToIoResult(errorCode),
			.SystemError = errorCode,
			.BytesMoved = bytesRead,
		};
	}
}

static IoResult WriteBytesDirect(HANDLE hFile, size_t byteCount, const std::byte* bytes)
{
	DWORD bytesWritten;
	BOOL result = WriteFile(hFile, bytes, byteCount, &bytesWritten, nullptr);

	if (result) {
		return IoResult{
			.Error = IoResult::ERR_None,
			.SystemError = 0,
			.BytesMoved = bytesWritten,
		};
	} else {
		DWORD errorCode = GetLastError();
		return IoResult{
			.Error = ::MapErrorCodeToIoResult(errorCode),
			.SystemError = errorCode,
			.BytesMoved = bytesWritten,
		};
	}
}

#elif defined(__APPLE__) || defined(__linux__)
#	include <fcntl.h>
#	include <sys/stat.h>
#	include <sys/types.h>
#	include <unistd.h>

InputFileStream::InputFileStream(const fs::path& path)
	: mOsFileHandle{ 0 }
{
	auto fd = reinterpret_cast<int*>(mOsFileHandle);
	*fd = open(path.c_str(), O_RDONLY);
}

InputFileStream::~InputFileStream()
{
	auto fd = reinterpret_cast<int*>(mOsFileHandle);
	close(*fd);
}

OutputFileStream::OutputFileStream(const fs::path& path, WriteMode mode)
	: mOsFileHandle{ 0 }
{
	auto fd = reinterpret_cast<int*>(mOsFileHandle);

	int flags = O_WRONLY | O_CREAT;
	switch (mode) {
		case AppendFile: flags |= O_APPEND; break;
		case TruncateFile: flags |= O_TRUNC; break;
	}

	*fd = open(path.c_str(), flags, 0644);
}

OutputFileStream::~OutputFileStream()
{
	auto fd = reinterpret_cast<int*>(mOsFileHandle);
	close(*fd);
}

static IoResult::ErrorKind MapErrnoToIoResult(int err)
{
	switch (err) {
		// TODO
		case EFAULT: return IoResult::ERR_UnexpectedEof;
		case EPERM: return IoResult::ERR_PermissionDenied;
		case ENOSPC: return IoResult::ERR_OutOfSpace;
		case EIO: return IoResult::ERR_Other;

		default:
			std::cerr << "Unimplemented POSIX errno " << err << ", report bug immediately.\n";
			std::abort();
	}
}

static IoResult ReadBytesDirect(const char* osFileHandle, size_t byteCount, std::byte* bytes)
{
	int fd = *reinterpret_cast<const int*>(osFileHandle);
	int status = read(fd, bytes, byteCount);

	if (status == -1) {
		int err = errno;
		return IoResult{
			.Error = ::MapErrnoToIoResult(err),
			.SystemError = (uint32_t)err,
			.BytesMoved = 0,
		};
	} else {
		return IoResult{
			.Error = IoResult::ERR_None,
			.SystemError = 0,
			.BytesMoved = (size_t)status, // Equal to number of bytes read
		};
	}
}

static IoResult WriteBytesDirect(const char* osFileHandle, size_t byteCount, const std::byte* bytes)
{
	int fd = *reinterpret_cast<const int*>(osFileHandle);
	int status = write(fd, bytes, byteCount);

	if (status == -1) {
		int err = errno;
		return IoResult{
			.Error = ::MapErrnoToIoResult(err),
			.SystemError = (uint32_t)err,
			.BytesMoved = 0,
		};
	} else {
		return IoResult{
			.Error = IoResult::ERR_None,
			.SystemError = 0,
			.BytesMoved = (size_t)status, // Equal to number of bytes read
		};
	}
}

#else
#	error "Unsupported target platform."
#endif

int InputFileStream::GetReadInSize() const
{
	return mReadInSize;
}

void InputFileStream::SetReadInSize(int size)
{
	if (size > mReadInSize) {
		mReadInSize = size;
		mBuffer = std::make_unique<std::byte[]>(size);
	}
}

bool InputFileStream::IsEof() const
{
	return mEof;
}

IoResult InputFileStream::ReadBytes(size_t bufferLength, std::byte* buffer)
{
	// TODO reduce duplicated code

	auto bytesMoved = std::min<size_t>(mAvailableBytes, bufferLength);

	// On first call after construction, mFirstByteIdx will equal to mReadInSize, i.e. bytesAvailable == 0
	// and this call to std::memcpy will be no-op
	std::memcpy(buffer, &mBuffer[mFirstByteIdx], bytesMoved);
	mFirstByteIdx += (int)bytesMoved;
	mAvailableBytes -= (int)bytesMoved;
	buffer += bytesMoved;

	size_t bytesLeft = bufferLength - bytesMoved;
	if (bytesLeft > mReadInSize) {
		// Our buffer can't handle rest of the request, just skip the buffering step

		// Read rest of the data into buffer
		{
			auto result = ::ReadBytesDirect(mOsFileHandle, bytesLeft, buffer);
			bytesMoved += result.BytesMoved;

			if (result.Error == IoResult::ERR_None) {
				if (result.BytesMoved < mReadInSize) {
					mEof = true;
				}
			} else {
				goto end;
			}
		}

		// Refill our buffer
		{
			auto result = ::ReadBytesDirect(mOsFileHandle, mReadInSize, mBuffer.get());
			mFirstByteIdx = 0;
			mAvailableBytes = (int)result.BytesMoved;

			if (result.Error == IoResult::ERR_None) {
				if (result.BytesMoved < mReadInSize) {
					mEof = true;
				}
			} else {
				goto end;
			}
		}
	} else if (bytesLeft > 0) {
		// Our buffer can handle rest of the request, first buffer than supply the requested data

		// Refill our buffer
		{
			auto result = ::ReadBytesDirect(mOsFileHandle, mReadInSize, mBuffer.get());
			mFirstByteIdx = 0;
			mAvailableBytes = (int)result.BytesMoved;

			if (result.Error == IoResult::ERR_None) {
				if (result.BytesMoved < mReadInSize) {
					mEof = true;
				}
			} else {
				goto end;
			}
		}

		// Copy data into buffer
		{
			std::memcpy(buffer, &mBuffer[mFirstByteIdx], bytesLeft);
			mFirstByteIdx += (int)bytesLeft;
			bytesMoved += bytesLeft;
			buffer += bytesLeft;
		}
	} else {
		// Request completed already
	}

end:
	return IoResult{
		.Error = IoResult::ERR_None,
		.SystemError = 0,
		.BytesMoved = bytesMoved,
	};
}

int OutputFileStream::GetMaxBufferSize() const
{
	return mMaxBufferSize;
}

void OutputFileStream::SetMaxBufferSize(int maxSize)
{
	FlushBuffer();
	if (maxSize > mMaxBufferSize) {
		mMaxBufferSize = maxSize;
		mBuffer = std::make_unique<std::byte[]>(maxSize);
	}
}

IoResult OutputFileStream::WriteBytes(size_t bufferLength, const std::byte* buffer)
{
	if (bufferLength + mCurrentBufferSize > mMaxBufferSize) {
		FlushBuffer();

		if (bufferLength > mMaxBufferSize) {
			return ::WriteBytesDirect(mOsFileHandle, bufferLength, buffer);
		}
	}

	std::memcpy(mBuffer.get() + mCurrentBufferSize, buffer, bufferLength);
	mCurrentBufferSize += (int)bufferLength;

	return IoResult{
		.Error = IoResult::ERR_None,
		.SystemError = 0,
		.BytesMoved = bufferLength,
	};
}

void OutputFileStream::FlushBuffer()
{
	::WriteBytesDirect(mOsFileHandle, mCurrentBufferSize, mBuffer.get());
	mCurrentBufferSize = 0;
}