OpenTTD Source 20250331-master-g3c15e0c889
newgrf_bytereader.h
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#ifndef NEWGRF_BYTEREADER_H
11#define NEWGRF_BYTEREADER_H
12
14
17public:
18 ByteReader(const uint8_t *data, const uint8_t *end) : data(data), end(end) { }
19
20 const uint8_t *ReadBytes(size_t size)
21 {
22 if (this->data + size >= this->end) {
23 /* Put data at the end, as would happen if every byte had been individually read. */
24 this->data = this->end;
26 }
27
28 const uint8_t *ret = this->data;
29 this->data += size;
30 return ret;
31 }
32
37 uint8_t ReadByte()
38 {
39 if (this->data < this->end) return *this->data++;
41 }
42
47 uint16_t ReadWord()
48 {
49 uint16_t val = this->ReadByte();
50 return val | (this->ReadByte() << 8);
51 }
52
58 {
59 uint16_t val = this->ReadByte();
60 return val == 0xFF ? this->ReadWord() : val;
61 }
62
67 uint32_t ReadDWord()
68 {
69 uint32_t val = this->ReadWord();
70 return val | (this->ReadWord() << 16);
71 }
72
73 uint32_t PeekDWord();
74 uint32_t ReadVarSize(uint8_t size);
75 std::string_view ReadString();
76
77 size_t Remaining() const
78 {
79 return this->end - this->data;
80 }
81
82 bool HasData(size_t count = 1) const
83 {
84 return this->data + count <= this->end;
85 }
86
87 void Skip(size_t len)
88 {
89 this->data += len;
90 /* It is valid to move the buffer to exactly the end of the data,
91 * as there may not be any more data read. */
92 if (this->data > this->end) throw OTTDByteReaderSignal();
93 }
94
95private:
96 const uint8_t *data;
97 const uint8_t *end;
98};
99
100#endif /* NEWGRF_BYTEREADER_H */
Class to read from a NewGRF file.
const uint8_t * data
Current position within data.
uint32_t PeekDWord()
Read a single DWord (32 bits).
uint32_t ReadDWord()
Read a single DWord (32 bits).
uint16_t ReadWord()
Read a single Word (16 bits).
std::string_view ReadString()
Read a string.
uint16_t ReadExtendedByte()
Read a single Extended Byte (8 or 16 bits).
uint32_t ReadVarSize(uint8_t size)
Read a value of the given number of bytes.
uint8_t ReadByte()
Read a single byte (8 bits).
const uint8_t * end
Last position of data.