aboutsummaryrefslogtreecommitdiff
path: root/src/reader.cpp
blob: f8b053f16cc3680b33bc56794780d5f142f7acdc (plain) (blame)
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
#include "reader.h"

#include "debug.h"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iostream>

namespace TehImage
{

	Reader::Reader(std::string filename)
	{
		file = fopen(filename.c_str(), "rb");
		refreshBuffer();
		ready = true;
	}
	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;
	}

	template<> uint8_t Reader::readData<uint8_t>()
	{
		return readByte();
	}

	template<> uint16_t Reader::readData<uint16_t>()
	{
		uint16_t num = 0;
		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;
		for(int i = 0; i < 4; i++)
		{
			uint8_t byte = readByte();
			debug(std::cout << std::hex << 0+byte << " ");
			num += byte << (8 * (3-i));
		}
		debug(std::cout << std::dec << std::endl);
		return num;
	}

	template<> uint64_t Reader::readData<uint64_t>()
	{
		uint64_t num = 0;
		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;
	}

}