Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-2022 The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #ifndef BITCOIN_STREAMS_H
7 : : #define BITCOIN_STREAMS_H
8 : :
9 : : #include <serialize.h>
10 : : #include <span.h>
11 : : #include <support/allocators/zeroafterfree.h>
12 : : #include <util/overflow.h>
13 : :
14 : : #include <algorithm>
15 : : #include <assert.h>
16 : : #include <cstddef>
17 : : #include <cstdio>
18 : : #include <ios>
19 : : #include <limits>
20 : : #include <optional>
21 : : #include <stdint.h>
22 : : #include <string.h>
23 : : #include <string>
24 : : #include <utility>
25 : : #include <vector>
26 : :
27 : : namespace util {
28 : 0 : inline void Xor(Span<std::byte> write, Span<const std::byte> key, size_t key_offset = 0)
29 : : {
30 [ # # ]: 0 : if (key.size() == 0) {
31 : : return;
32 : : }
33 : 0 : key_offset %= key.size();
34 : :
35 [ # # ]: 0 : for (size_t i = 0, j = key_offset; i != write.size(); i++) {
36 [ # # ]: 0 : write[i] ^= key[j++];
37 : :
38 : : // This potentially acts on very many bytes of data, so it's
39 : : // important that we calculate `j`, i.e. the `key` index in this
40 : : // way instead of doing a %, which would effectively be a division
41 : : // for each byte Xor'd -- much slower than need be.
42 [ # # ]: 0 : if (j == key.size())
43 : 0 : j = 0;
44 : : }
45 : : }
46 : : } // namespace util
47 : :
48 : : /* Minimal stream for overwriting and/or appending to an existing byte vector
49 : : *
50 : : * The referenced vector will grow as necessary
51 : : */
52 : : class VectorWriter
53 : : {
54 : : public:
55 : : /*
56 : : * @param[in] vchDataIn Referenced byte vector to overwrite/append
57 : : * @param[in] nPosIn Starting position. Vector index where writes should start. The vector will initially
58 : : * grow as necessary to max(nPosIn, vec.size()). So to append, use vec.size().
59 : : */
60 : 0 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn) : vchData{vchDataIn}, nPos{nPosIn}
61 : : {
62 [ # # ]: 0 : if(nPos > vchData.size())
63 : 0 : vchData.resize(nPos);
64 : 0 : }
65 : : /*
66 : : * (other params same as above)
67 : : * @param[in] args A list of items to serialize starting at nPosIn.
68 : : */
69 : : template <typename... Args>
70 [ # # ][ # # : 0 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : VectorWriter{vchDataIn, nPosIn}
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ]
71 : : {
72 [ # # ][ # # : 0 : ::SerializeMany(*this, std::forward<Args>(args)...);
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ]
73 : 0 : }
74 : 0 : void write(Span<const std::byte> src)
75 : : {
76 [ # # ]: 0 : assert(nPos <= vchData.size());
77 [ # # ]: 0 : size_t nOverwrite = std::min(src.size(), vchData.size() - nPos);
78 [ # # ]: 0 : if (nOverwrite) {
79 : 0 : memcpy(vchData.data() + nPos, src.data(), nOverwrite);
80 : : }
81 [ # # ]: 0 : if (nOverwrite < src.size()) {
82 : 0 : vchData.insert(vchData.end(), UCharCast(src.data()) + nOverwrite, UCharCast(src.end()));
83 : : }
84 : 0 : nPos += src.size();
85 : 0 : }
86 : : template <typename T>
87 [ # # # # ]: 0 : VectorWriter& operator<<(const T& obj)
[ # # ]
88 : : {
89 [ # # # # : 0 : ::Serialize(*this, obj);
# # # # #
# ][ # # #
# # # # #
# # # # #
# ][ # # #
# # # #
# ]
90 : 0 : return (*this);
91 : : }
92 : :
93 : : private:
94 : : std::vector<unsigned char>& vchData;
95 : : size_t nPos;
96 : : };
97 : :
98 : : /** Minimal stream for reading from an existing byte array by Span.
99 : : */
100 : : class SpanReader
101 : : {
102 : : private:
103 : : Span<const unsigned char> m_data;
104 : :
105 : : public:
106 : : /**
107 : : * @param[in] data Referenced byte vector to overwrite/append
108 : : */
109 [ # # # # : 0 : explicit SpanReader(Span<const unsigned char> data) : m_data{data} {}
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ]
[ # # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ]
110 : :
111 : : template<typename T>
112 [ # # # # : 0 : SpanReader& operator>>(T&& obj)
# # ][ # #
# # # # #
# # # # #
# # # # ]
113 : : {
114 [ # # # # : 0 : ::Unserialize(*this, obj);
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
115 : 0 : return (*this);
116 : : }
117 : :
118 : : size_t size() const { return m_data.size(); }
119 [ # # # # ]: 0 : bool empty() const { return m_data.empty(); }
[ # # ]
120 : :
121 : 0 : void read(Span<std::byte> dst)
122 : : {
123 [ # # ]: 0 : if (dst.size() == 0) {
124 : : return;
125 : : }
126 : :
127 : : // Read from the beginning of the buffer
128 [ # # ]: 0 : if (dst.size() > m_data.size()) {
129 [ # # ]: 0 : throw std::ios_base::failure("SpanReader::read(): end of data");
130 : : }
131 : 0 : memcpy(dst.data(), m_data.data(), dst.size());
132 : 0 : m_data = m_data.subspan(dst.size());
133 : : }
134 : :
135 : : void ignore(size_t n)
136 : : {
137 : : m_data = m_data.subspan(n);
138 : : }
139 : : };
140 : :
141 : : /** Double ended buffer combining vector and stream-like interfaces.
142 : : *
143 : : * >> and << read and write unformatted data using the above serialization templates.
144 : : * Fills with data in linear time; some stringstream implementations take N^2 time.
145 : : */
146 [ - - # # : 123476 : class DataStream
# # ][ - -
# # # # ]
[ # # # # ]
147 : : {
148 : : protected:
149 : : using vector_type = SerializeData;
150 : : vector_type vch;
151 : : vector_type::size_type m_read_pos{0};
152 : :
153 : : public:
154 : : typedef vector_type::allocator_type allocator_type;
155 : : typedef vector_type::size_type size_type;
156 : : typedef vector_type::difference_type difference_type;
157 : : typedef vector_type::reference reference;
158 : : typedef vector_type::const_reference const_reference;
159 : : typedef vector_type::value_type value_type;
160 : : typedef vector_type::iterator iterator;
161 : : typedef vector_type::const_iterator const_iterator;
162 : : typedef vector_type::reverse_iterator reverse_iterator;
163 : :
164 [ # # ]: 0 : explicit DataStream() = default;
165 : 57400 : explicit DataStream(Span<const uint8_t> sp) : DataStream{AsBytes(sp)} {}
166 : 57400 : explicit DataStream(Span<const value_type> sp) : vch(sp.data(), sp.data() + sp.size()) {}
167 : :
168 : 0 : std::string str() const
169 : : {
170 : 0 : return std::string{UCharCast(data()), UCharCast(data() + size())};
171 : : }
172 : :
173 : :
174 : : //
175 : : // Vector subset
176 : : //
177 : : const_iterator begin() const { return vch.begin() + m_read_pos; }
178 : 0 : iterator begin() { return vch.begin() + m_read_pos; }
179 : : const_iterator end() const { return vch.end(); }
180 [ # # # # ]: 0 : iterator end() { return vch.end(); }
[ # # ]
181 [ # # # # : 66076 : size_type size() const { return vch.size() - m_read_pos; }
# # # # #
# ]
[ # # # # ]
[ # # ][ # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # ]
182 [ - - - - ]: 0 : bool empty() const { return vch.size() == m_read_pos; }
[ # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # ]
[ # # # #
# # # # ]
183 : 0 : void resize(size_type n, value_type c = value_type{}) { vch.resize(n + m_read_pos, c); }
184 [ # # # # : 0 : void reserve(size_type n) { vch.reserve(n + m_read_pos); }
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# ]
185 : : const_reference operator[](size_type pos) const { return vch[pos + m_read_pos]; }
186 [ # # ]: 0 : reference operator[](size_type pos) { return vch[pos + m_read_pos]; }
187 [ # # # # : 0 : void clear() { vch.clear(); m_read_pos = 0; }
# # ][ # #
# # # # ]
[ # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # ]
188 [ # # # # : 66076 : value_type* data() { return vch.data() + m_read_pos; }
# # # # #
# ]
[ # # # # ]
[ # # ][ # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # #
# ]
189 : 0 : const value_type* data() const { return vch.data() + m_read_pos; }
190 : :
191 : : inline void Compact()
192 : : {
193 : : vch.erase(vch.begin(), vch.begin() + m_read_pos);
194 : : m_read_pos = 0;
195 : : }
196 : :
197 : : bool Rewind(std::optional<size_type> n = std::nullopt)
198 : : {
199 : : // Total rewind if no size is passed
200 : : if (!n) {
201 : : m_read_pos = 0;
202 : : return true;
203 : : }
204 : : // Rewind by n characters if the buffer hasn't been compacted yet
205 : : if (*n > m_read_pos)
206 : : return false;
207 : : m_read_pos -= *n;
208 : : return true;
209 : : }
210 : :
211 : :
212 : : //
213 : : // Stream subset
214 : : //
215 [ # # ]: 0 : bool eof() const { return size() == 0; }
216 [ # # ]: 0 : int in_avail() const { return size(); }
217 : :
218 : 4385769 : void read(Span<value_type> dst)
219 : : {
220 [ + - ]: 4385769 : if (dst.size() == 0) return;
221 : :
222 : : // Read from the beginning of the buffer
223 : 4385769 : auto next_read_pos{CheckedAdd(m_read_pos, dst.size())};
224 [ + - + + ]: 4385769 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
225 [ + - ]: 203 : throw std::ios_base::failure("DataStream::read(): end of data");
226 : : }
227 [ + + ]: 4385566 : memcpy(dst.data(), &vch[m_read_pos], dst.size());
228 [ + + ]: 4385566 : if (next_read_pos.value() == vch.size()) {
229 : 3105 : m_read_pos = 0;
230 [ + - ]: 3105 : vch.clear();
231 : 3105 : return;
232 : : }
233 : 4382461 : m_read_pos = next_read_pos.value();
234 : : }
235 : :
236 : 0 : void ignore(size_t num_ignore)
237 : : {
238 : : // Ignore from the beginning of the buffer
239 : 0 : auto next_read_pos{CheckedAdd(m_read_pos, num_ignore)};
240 [ # # # # ]: 0 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
241 [ # # ]: 0 : throw std::ios_base::failure("DataStream::ignore(): end of data");
242 : : }
243 [ # # ]: 0 : if (next_read_pos.value() == vch.size()) {
244 : 0 : m_read_pos = 0;
245 [ # # ]: 0 : vch.clear();
246 : 0 : return;
247 : : }
248 : 0 : m_read_pos = next_read_pos.value();
249 : : }
250 : :
251 : 132152 : void write(Span<const value_type> src)
252 : : {
253 : : // Write to the end of the buffer
254 : 132152 : vch.insert(vch.end(), src.begin(), src.end());
255 : 132152 : }
256 : :
257 : : template<typename T>
258 [ # # # # : 66076 : DataStream& operator<<(const T& obj)
# # # # ]
[ # # # # ]
259 : : {
260 [ # # # # : 132152 : ::Serialize(*this, obj);
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ + - +
- # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - -
- ][ # # #
# # # # #
# # # # #
# # # # #
# # ][ # # ]
[ # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # # # ]
261 : 66076 : return (*this);
262 : : }
263 : :
264 : : template<typename T>
265 [ # # # # : 57400 : DataStream& operator>>(T&& obj)
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # # ]
[ # # # # ]
[ # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ]
266 : : {
267 [ # # # # : 57400 : ::Unserialize(*this, obj);
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ - - - -
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ + + +
+ + + ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # ]
268 : 57136 : return (*this);
269 : : }
270 : :
271 : : /**
272 : : * XOR the contents of this stream with a certain key.
273 : : *
274 : : * @param[in] key The key used to XOR the data in this stream.
275 : : */
276 : 0 : void Xor(const std::vector<unsigned char>& key)
277 : : {
278 : 0 : util::Xor(MakeWritableByteSpan(*this), MakeByteSpan(key));
279 : 0 : }
280 : :
281 : : /** Compute total memory usage of this object (own memory + any dynamic memory). */
282 : : size_t GetMemoryUsage() const noexcept;
283 : : };
284 : :
285 : : template <typename IStream>
286 : : class BitStreamReader
287 : : {
288 : : private:
289 : : IStream& m_istream;
290 : :
291 : : /// Buffered byte read in from the input stream. A new byte is read into the
292 : : /// buffer when m_offset reaches 8.
293 : : uint8_t m_buffer{0};
294 : :
295 : : /// Number of high order bits in m_buffer already returned by previous
296 : : /// Read() calls. The next bit to be returned is at this offset from the
297 : : /// most significant bit position.
298 : : int m_offset{8};
299 : :
300 : : public:
301 [ # # ]: 0 : explicit BitStreamReader(IStream& istream) : m_istream(istream) {}
302 : :
303 : : /** Read the specified number of bits from the stream. The data is returned
304 : : * in the nbits least significant bits of a 64-bit uint.
305 : : */
306 : 0 : uint64_t Read(int nbits) {
307 [ # # ]: 0 : if (nbits < 0 || nbits > 64) {
308 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
309 : : }
310 : :
311 : : uint64_t data = 0;
312 [ # # ]: 0 : while (nbits > 0) {
313 [ # # ]: 0 : if (m_offset == 8) {
314 : 0 : m_istream >> m_buffer;
315 : 0 : m_offset = 0;
316 : : }
317 : :
318 [ # # ]: 0 : int bits = std::min(8 - m_offset, nbits);
319 : 0 : data <<= bits;
320 : 0 : data |= static_cast<uint8_t>(m_buffer << m_offset) >> (8 - bits);
321 : 0 : m_offset += bits;
322 : 0 : nbits -= bits;
323 : : }
324 : 0 : return data;
325 : : }
326 : : };
327 : :
328 : : template <typename OStream>
329 : : class BitStreamWriter
330 : : {
331 : : private:
332 : : OStream& m_ostream;
333 : :
334 : : /// Buffered byte waiting to be written to the output stream. The byte is
335 : : /// written buffer when m_offset reaches 8 or Flush() is called.
336 : : uint8_t m_buffer{0};
337 : :
338 : : /// Number of high order bits in m_buffer already written by previous
339 : : /// Write() calls and not yet flushed to the stream. The next bit to be
340 : : /// written to is at this offset from the most significant bit position.
341 : : int m_offset{0};
342 : :
343 : : public:
344 [ # # ]: 0 : explicit BitStreamWriter(OStream& ostream) : m_ostream(ostream) {}
345 : :
346 : 0 : ~BitStreamWriter()
347 : : {
348 : 0 : Flush();
349 : 0 : }
350 : :
351 : : /** Write the nbits least significant bits of a 64-bit int to the output
352 : : * stream. Data is buffered until it completes an octet.
353 : : */
354 : 0 : void Write(uint64_t data, int nbits) {
355 [ # # ]: 0 : if (nbits < 0 || nbits > 64) {
356 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
357 : : }
358 : :
359 [ # # ]: 0 : while (nbits > 0) {
360 [ # # ]: 0 : int bits = std::min(8 - m_offset, nbits);
361 : 0 : m_buffer |= (data << (64 - nbits)) >> (64 - 8 + m_offset);
362 : 0 : m_offset += bits;
363 : 0 : nbits -= bits;
364 : :
365 [ # # ]: 0 : if (m_offset == 8) {
366 : 0 : Flush();
367 : : }
368 : : }
369 : 0 : }
370 : :
371 : : /** Flush any unwritten bits to the output stream, padding with 0's to the
372 : : * next byte boundary.
373 : : */
374 : 0 : void Flush() {
375 [ # # ]: 0 : if (m_offset == 0) {
376 : : return;
377 : : }
378 : :
379 : 0 : m_ostream << m_buffer;
380 : 0 : m_buffer = 0;
381 : 0 : m_offset = 0;
382 : : }
383 : : };
384 : :
385 : : /** Non-refcounted RAII wrapper for FILE*
386 : : *
387 : : * Will automatically close the file when it goes out of scope if not null.
388 : : * If you're returning the file pointer, return file.release().
389 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
390 : : */
391 : : class AutoFile
392 : : {
393 : : protected:
394 : : std::FILE* m_file;
395 : : std::vector<std::byte> m_xor;
396 : : std::optional<int64_t> m_position;
397 : :
398 : : public:
399 : : explicit AutoFile(std::FILE* file, std::vector<std::byte> data_xor={});
400 : :
401 [ # # ]: 0 : ~AutoFile() { fclose(); }
402 : :
403 : : // Disallow copies
404 : : AutoFile(const AutoFile&) = delete;
405 : : AutoFile& operator=(const AutoFile&) = delete;
406 : :
407 : 0 : bool feof() const { return std::feof(m_file); }
408 : :
409 : 0 : int fclose()
410 : : {
411 [ # # ]: 0 : if (auto rel{release()}) return std::fclose(rel);
412 : : return 0;
413 : : }
414 : :
415 : : /** Get wrapped FILE* with transfer of ownership.
416 : : * @note This will invalidate the AutoFile object, and makes it the responsibility of the caller
417 : : * of this function to clean up the returned FILE*.
418 : : */
419 : 0 : std::FILE* release()
420 : : {
421 : 0 : std::FILE* ret{m_file};
422 : 0 : m_file = nullptr;
423 [ # # ]: 0 : return ret;
[ # # # # ]
424 : : }
425 : :
426 : : /** Return true if the wrapped FILE* is nullptr, false otherwise.
427 : : */
428 [ # # ][ # # : 0 : bool IsNull() const { return m_file == nullptr; }
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# ]
429 : :
430 : : /** Continue with a different XOR key */
431 [ # # # # ]: 0 : void SetXor(std::vector<std::byte> data_xor) { m_xor = data_xor; }
432 : :
433 : : /** Implementation detail, only used internally. */
434 : : std::size_t detail_fread(Span<std::byte> dst);
435 : :
436 : : /** Wrapper around fseek(). Will throw if seeking is not possible. */
437 : : void seek(int64_t offset, int origin);
438 : :
439 : : /** Find position within the file. Will throw if unknown. */
440 : : int64_t tell();
441 : :
442 : : /** Wrapper around FileCommit(). */
443 : : bool Commit();
444 : :
445 : : /** Wrapper around TruncateFile(). */
446 : : bool Truncate(unsigned size);
447 : :
448 : : //
449 : : // Stream subset
450 : : //
451 : : void read(Span<std::byte> dst);
452 : : void ignore(size_t nSize);
453 : : void write(Span<const std::byte> src);
454 : :
455 : : template <typename T>
456 [ # # ][ # # : 0 : AutoFile& operator<<(const T& obj)
# # # # #
# # # ]
457 : : {
458 [ # # ][ # # : 0 : ::Serialize(*this, obj);
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # #
# # # #
# ][ # # #
# # # #
# ]
459 : 0 : return *this;
460 : : }
461 : :
462 : : template <typename T>
463 [ # # # # ]: 0 : AutoFile& operator>>(T&& obj)
[ # # # #
# # # # ]
[ # # # #
# # # # ]
[ # # # #
# # # # #
# ]
464 : : {
465 [ # # # # : 0 : ::Unserialize(*this, obj);
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # # ]
[ # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # ]
[ # # # #
# # # # #
# # # #
# ]
466 : 0 : return *this;
467 : : }
468 : : };
469 : :
470 : : /** Wrapper around an AutoFile& that implements a ring buffer to
471 : : * deserialize from. It guarantees the ability to rewind a given number of bytes.
472 : : *
473 : : * Will automatically close the file when it goes out of scope if not null.
474 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
475 : : */
476 : 0 : class BufferedFile
477 : : {
478 : : private:
479 : : AutoFile& m_src;
480 : : uint64_t nSrcPos{0}; //!< how many bytes have been read from source
481 : : uint64_t m_read_pos{0}; //!< how many bytes have been read from this
482 : : uint64_t nReadLimit; //!< up to which position we're allowed to read
483 : : uint64_t nRewind; //!< how many bytes we guarantee to rewind
484 : : std::vector<std::byte> vchBuf; //!< the buffer
485 : :
486 : : //! read data from the source to fill the buffer
487 : 0 : bool Fill() {
488 [ # # ]: 0 : unsigned int pos = nSrcPos % vchBuf.size();
489 : 0 : unsigned int readNow = vchBuf.size() - pos;
490 : 0 : unsigned int nAvail = vchBuf.size() - (nSrcPos - m_read_pos) - nRewind;
491 [ # # ]: 0 : if (nAvail < readNow)
492 : 0 : readNow = nAvail;
493 [ # # ]: 0 : if (readNow == 0)
494 : : return false;
495 : 0 : size_t nBytes{m_src.detail_fread(Span{vchBuf}.subspan(pos, readNow))};
496 [ # # ]: 0 : if (nBytes == 0) {
497 [ # # # # ]: 0 : throw std::ios_base::failure{m_src.feof() ? "BufferedFile::Fill: end of file" : "BufferedFile::Fill: fread failed"};
498 : : }
499 : 0 : nSrcPos += nBytes;
500 : 0 : return true;
501 : : }
502 : :
503 : : //! Advance the stream's read pointer (m_read_pos) by up to 'length' bytes,
504 : : //! filling the buffer from the file so that at least one byte is available.
505 : : //! Return a pointer to the available buffer data and the number of bytes
506 : : //! (which may be less than the requested length) that may be accessed
507 : : //! beginning at that pointer.
508 : 0 : std::pair<std::byte*, size_t> AdvanceStream(size_t length)
509 : : {
510 [ # # ]: 0 : assert(m_read_pos <= nSrcPos);
511 [ # # ]: 0 : if (m_read_pos + length > nReadLimit) {
512 [ # # ]: 0 : throw std::ios_base::failure("Attempt to position past buffer limit");
513 : : }
514 : : // If there are no bytes available, read from the file.
515 [ # # # # ]: 0 : if (m_read_pos == nSrcPos && length > 0) Fill();
516 : :
517 : 0 : size_t buffer_offset{static_cast<size_t>(m_read_pos % vchBuf.size())};
518 : 0 : size_t buffer_available{static_cast<size_t>(vchBuf.size() - buffer_offset)};
519 : 0 : size_t bytes_until_source_pos{static_cast<size_t>(nSrcPos - m_read_pos)};
520 : 0 : size_t advance{std::min({length, buffer_available, bytes_until_source_pos})};
521 : 0 : m_read_pos += advance;
522 : 0 : return std::make_pair(&vchBuf[buffer_offset], advance);
523 : : }
524 : :
525 : : public:
526 : 0 : BufferedFile(AutoFile& file, uint64_t nBufSize, uint64_t nRewindIn)
527 : 0 : : m_src{file}, nReadLimit{std::numeric_limits<uint64_t>::max()}, nRewind{nRewindIn}, vchBuf(nBufSize, std::byte{0})
528 : : {
529 [ # # ]: 0 : if (nRewindIn >= nBufSize)
530 [ # # ]: 0 : throw std::ios_base::failure("Rewind limit must be less than buffer size");
531 : 0 : }
532 : :
533 : : //! check whether we're at the end of the source file
534 : 0 : bool eof() const {
535 [ # # # # ]: 0 : return m_read_pos == nSrcPos && m_src.feof();
536 : : }
537 : :
538 : : //! read a number of bytes
539 : 0 : void read(Span<std::byte> dst)
540 : : {
541 [ # # ]: 0 : while (dst.size() > 0) {
542 : 0 : auto [buffer_pointer, length]{AdvanceStream(dst.size())};
543 : 0 : memcpy(dst.data(), buffer_pointer, length);
544 : 0 : dst = dst.subspan(length);
545 : : }
546 : 0 : }
547 : :
548 : : //! Move the read position ahead in the stream to the given position.
549 : : //! Use SetPos() to back up in the stream, not SkipTo().
550 : 0 : void SkipTo(const uint64_t file_pos)
551 : : {
552 [ # # ]: 0 : assert(file_pos >= m_read_pos);
553 [ # # ]: 0 : while (m_read_pos < file_pos) AdvanceStream(file_pos - m_read_pos);
554 : 0 : }
555 : :
556 : : //! return the current reading position
557 : 0 : uint64_t GetPos() const {
558 [ # # # # : 0 : return m_read_pos;
# # ]
559 : : }
560 : :
561 : : //! rewind to a given reading position
562 : 0 : bool SetPos(uint64_t nPos) {
563 [ # # ]: 0 : size_t bufsize = vchBuf.size();
564 [ # # ]: 0 : if (nPos + bufsize < nSrcPos) {
565 : : // rewinding too far, rewind as far as possible
566 : 0 : m_read_pos = nSrcPos - bufsize;
567 : 0 : return false;
568 : : }
569 [ # # ]: 0 : if (nPos > nSrcPos) {
570 : : // can't go this far forward, go as far as possible
571 : 0 : m_read_pos = nSrcPos;
572 : 0 : return false;
573 : : }
574 : 0 : m_read_pos = nPos;
575 : 0 : return true;
576 : : }
577 : :
578 : : //! prevent reading beyond a certain position
579 : : //! no argument removes the limit
580 : 0 : bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
581 [ # # ]: 0 : if (nPos < m_read_pos)
582 : : return false;
583 : 0 : nReadLimit = nPos;
584 [ # # ]: 0 : return true;
585 : : }
586 : :
587 : : template<typename T>
588 [ # # ]: 0 : BufferedFile& operator>>(T&& obj) {
589 [ # # # # ]: 0 : ::Unserialize(*this, obj);
[ # # # #
# # # # ]
590 : 0 : return (*this);
591 : : }
592 : :
593 : : //! search for a given byte in the stream, and remain positioned on it
594 : 0 : void FindByte(std::byte byte)
595 : : {
596 : : // For best performance, avoid mod operation within the loop.
597 : 0 : size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
598 : 0 : while (true) {
599 [ # # ]: 0 : if (m_read_pos == nSrcPos) {
600 : : // No more bytes available; read from the file into the buffer,
601 : : // setting nSrcPos to one beyond the end of the new data.
602 : : // Throws exception if end-of-file reached.
603 : 0 : Fill();
604 : : }
605 [ # # ]: 0 : const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
606 [ # # ]: 0 : const auto it_start{vchBuf.begin() + buf_offset};
607 : 0 : const auto it_find{std::find(it_start, it_start + len, byte)};
608 [ # # ]: 0 : const size_t inc{size_t(std::distance(it_start, it_find))};
609 : 0 : m_read_pos += inc;
610 [ # # ]: 0 : if (inc < len) break;
611 : 0 : buf_offset += inc;
612 [ # # ]: 0 : if (buf_offset >= vchBuf.size()) buf_offset = 0;
613 : : }
614 : 0 : }
615 : : };
616 : :
617 : : #endif // BITCOIN_STREAMS_H
|