summaryrefslogtreecommitdiffhomepage
path: root/FoundationEx/src/reader/file.cpp
blob: f9e9ae2287d3ea440217d869df003d6fc8a6fa0e (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
/*  Starshatter: The Open Source Project
    Copyright (c) 2021-2024, Starshatter: The Open Source Project Contributors
    Copyright (c) 2011-2012, Starshatter OpenSource Distribution Contributors
    Copyright (c) 1997-2006, Destroyer Studios LLC.
*/

#include "file.h"

#include <algorithm>
#include <fstream>
#include <ios>
#include <limits>
#include <utility>
#include <vector>

#include <Text.h>


namespace starshatter
{
namespace foundation
{


FileReader::FileReader(std::fstream src) :
	file {std::move(src)}
{
	file.seekg(0);
	file.ignore(std::numeric_limits<std::streamsize>::max());
	size = file.gcount();
	file.clear();
	file.seekg(0);
	position = 0;
}


bool
FileReader::valid() const
{
	return static_cast<bool>(file) && file.is_open();
}


Count
FileReader::available() const
{
	return size - position;
}


Count
FileReader::seek(Count pos)
{
	position = pos;
	if (position > size)
		position = size;
	file.seekg(position);
	return position;
}


Count
FileReader::seek(Offset offset, Direction dir)
{
	switch (dir) {
	case Direction::Start:
		break;  // no-op
	case Direction::End:
		offset = size + offset;
		break;
	case Direction::Current:
		offset = position + offset;
		break;
	}
	if (offset < 0)
		offset = 0;
	return seek(static_cast<Count>(offset));
}


Count
FileReader::read(char* dest)
{
	return read(dest, available());
}


Count
FileReader::read(char* dest, Count bytes)
{
	bytes = std::min(bytes, available());
	file.read(dest, bytes);
	position += bytes;
	return bytes;
}


Count
FileReader::peek(char* dest) const
{
	return peek(dest, available());
}


Count
FileReader::peek(char* dest, Count bytes) const
{
	bytes = std::min(bytes, available());
	const auto before = file.tellg();
	file.read(dest, bytes);
	file.seekg(before);
	return bytes;
}


Text
FileReader::more()
{
	const auto size = available();
	if (size < 1)
		return Text();
	std::vector<char> tmp(size);
	read(tmp.data(), size);
	return Text(tmp.data(), size);
}


}  // namespace foundation
}  // namespace starshatter