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
|
#include "reader.h"
#include "debug.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iostream>
namespace TehImage
{
Reader::Reader(std::string filename, FileEndianness fileEndianness)
{
file = fopen(filename.c_str(), "rb");
refreshBuffer();
ready = true;
this->fileEndianness = fileEndianness;
}
Reader::~Reader()
{
if(ready)
fclose(file);
}
char Reader::readByte()
{
if(pos == BUFFER_SIZE)
refreshBuffer();
return buffer[pos++];
}
void Reader::refreshBuffer()
{
fread(buffer, sizeof(buffer), 1, file);
pos = 0;
}
void Reader::convertEndian(uint8_t* out, size_t bytes)
{
constexpr bool LE = std::endian::native == std::endian::little;
constexpr bool BE = !LE;
if(fileEndianness == NO_CONVERT || (fileEndianness == BIG && BE) || (fileEndianness == LITTLE && LE))
{
for(int i = 0; i < bytes; i++)
{
out[i] = readByte();
}
return;
}
for(int i = 0; i < bytes; i++)
{
out[bytes - 1 - i] = readByte();
}
}
template<> uint8_t Reader::readData<uint8_t>()
{
return readByte();
}
template<> uint16_t Reader::readData<uint16_t>()
{
uint16_t num = 0;
convertEndian((uint8_t*)&num, 2);
// for(int i = 0; i < 2; i++)
// {
// num += readByte() << (8 * (1-i));
// }
return num;
}
template<> uint32_t Reader::readData<uint32_t>()
{
uint32_t num = 0;
convertEndian((uint8_t*)&num, 4);
// for(int i = 0; i < 4; i++)
// {
// // uint8_t byte = readByte();
// // debug(std::cout << std::hex << 0+byte << " ");
// num += ((uint8_t) readByte()) << (8 * (3-i));
// }
// // debug(std::cout << std::dec << std::endl);
return num;
}
template<> uint64_t Reader::readData<uint64_t>()
{
uint64_t num = 0;
convertEndian((uint8_t*)&num, 8);
// for(int i = 0; i < 8; i++)
// {
// num += readByte() << (8 * (7-i));
// }
return num;
}
void Reader::readBytes(char* out, size_t len)
{
while(len > 0)
{
size_t bytesToRead = std::min(len, BUFFER_SIZE - pos);
if(bytesToRead == 0)
{
refreshBuffer();
continue;
}
memcpy(out, buffer + pos, bytesToRead);
out += bytesToRead;
len -= bytesToRead;
pos += bytesToRead;
}
}
void Reader::skipBytes(size_t len)
{
while(len > 0)
{
size_t bytesToRead = std::min(len, BUFFER_SIZE - pos);
if(bytesToRead == 0)
{
refreshBuffer();
continue;
}
len -= bytesToRead;
pos += bytesToRead;
}
}
void Reader::close()
{
fclose(file);
ready = false;
}
}
|