aboutsummaryrefslogtreecommitdiff
path: root/core/src/Utils/IO/FileStream.cpp
blob: bc95b7ec7239e360bc8596e9ea64ed2c53bbef7c (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
#include "FileStream.hpp"

#include <cstring>
#include <iostream>

#if PLATFORM_WIN32

// TODO

#elif PLATFORM_MACOS || PLATFORM_LINUX
#	include <fcntl.h>
#	include <sys/stat.h>
#	include <sys/types.h>
#	include <unistd.h>

InputFileStream::InputFileStream(const std::filesystem::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 std::filesystem::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 = 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 = 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;
}