aboutsummaryrefslogtreecommitdiff
path: root/app/source/Cplt/Utils/IO/FileStream.hpp
blob: 37b2a3657e3971c21afacb3dd6eb76a8ad779e5f (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
#pragma once

#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>

// TODO switch to custom when unit tests are ready and bugs are fixed
#define CPLT_FILESTREAM_USE_CSTDIO

struct IoResult {
	enum ErrorKind {
		ERR_None,
		ERR_PermissionDenied,
		ERR_UnexpectedEof,
		ERR_Unsupported,
		ERR_OutOfSpace,
		ERR_Other,
	};

	ErrorKind Error;
	uint32_t SystemError;
	size_t BytesMoved;
};

class InputFileStream {
private:
#if defined(CPLT_FILESTREAM_USE_CSTDIO)
	FILE* mFile;
#else
	alignas(void*) char mOsFileHandle[sizeof(void*)];

	// mBuffer is always mReadInSize size
	std::unique_ptr<std::byte[]> mBuffer;
	int mReadInSize = 1024;

	int mFirstByteIdx = 0;
	int mAvailableBytes = 0;

	bool mEof = false;
#endif

public:
	InputFileStream(const std::filesystem::path& path);
	~InputFileStream();

	InputFileStream(const InputFileStream&) = delete;
	InputFileStream& operator=(const InputFileStream&) = delete;
	InputFileStream(InputFileStream&&);
	InputFileStream& operator=(InputFileStream&&);

	int GetReadInSize() const;
	void SetReadInSize(int size);

	bool IsEof() const;

	IoResult ReadBytes(size_t bufferLength, std::byte* buffer);
};

class OutputFileStream {
public:
	enum WriteMode {
		AppendFile,
		TruncateFile,
	};

private:
#if defined(CPLT_FILESTREAM_USE_CSTDIO)
	FILE* mFile;
#else
	alignas(void*) char mOsFileHandle[sizeof(void*)];
	std::unique_ptr<std::byte[]> mBuffer;
	int mMaxBufferSize = 1024;
	int mCurrentBufferSize = 0;
#endif

public:
	OutputFileStream(const std::filesystem::path& path, WriteMode mode);
	~OutputFileStream();

	OutputFileStream(const OutputFileStream&) = delete;
	OutputFileStream& operator=(const OutputFileStream&) = delete;
	OutputFileStream(OutputFileStream&&);
	OutputFileStream& operator=(OutputFileStream&&);

	int GetMaxBufferSize() const;
	void SetMaxBufferSize(int maxSize);

	IoResult WriteBytes(size_t bufferLength, const std::byte* buffer);

	void FlushBuffer();
};