]> Git Repo - VerusCoin.git/blame - src/streams.h
Fix exception
[VerusCoin.git] / src / streams.h
CommitLineData
fa736190 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2013 The Bitcoin Core developers
78253fcb 3// Distributed under the MIT software license, see the accompanying
fa736190
CF
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef BITCOIN_STREAMS_H
7#define BITCOIN_STREAMS_H
8
d7d187e8 9#include "support/allocators/zeroafterfree.h"
fa736190
CF
10#include "serialize.h"
11
12#include <algorithm>
13#include <assert.h>
14#include <ios>
15#include <limits>
16#include <map>
17#include <set>
18#include <stdint.h>
1630219d 19#include <stdio.h>
fa736190
CF
20#include <string>
21#include <string.h>
22#include <utility>
23#include <vector>
24
25/** Double ended buffer combining vector and stream-like interfaces.
26 *
27 * >> and << read and write unformatted data using the above serialization templates.
28 * Fills with data in linear time; some stringstream implementations take N^2 time.
29 */
6bffc46a
JG
30template<typename SerializeType>
31class CBaseDataStream
fa736190
CF
32{
33protected:
6bffc46a 34 typedef SerializeType vector_type;
fa736190
CF
35 vector_type vch;
36 unsigned int nReadPos;
37public:
38 int nType;
39 int nVersion;
40
6bffc46a
JG
41 typedef typename vector_type::allocator_type allocator_type;
42 typedef typename vector_type::size_type size_type;
43 typedef typename vector_type::difference_type difference_type;
44 typedef typename vector_type::reference reference;
45 typedef typename vector_type::const_reference const_reference;
46 typedef typename vector_type::value_type value_type;
47 typedef typename vector_type::iterator iterator;
48 typedef typename vector_type::const_iterator const_iterator;
49 typedef typename vector_type::reverse_iterator reverse_iterator;
50
51 explicit CBaseDataStream(int nTypeIn, int nVersionIn)
fa736190
CF
52 {
53 Init(nTypeIn, nVersionIn);
54 }
55
6bffc46a 56 CBaseDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
fa736190
CF
57 {
58 Init(nTypeIn, nVersionIn);
59 }
60
61#if !defined(_MSC_VER) || _MSC_VER >= 1300
6bffc46a 62 CBaseDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
fa736190
CF
63 {
64 Init(nTypeIn, nVersionIn);
65 }
66#endif
67
6bffc46a 68 CBaseDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
fa736190
CF
69 {
70 Init(nTypeIn, nVersionIn);
71 }
72
6bffc46a 73 CBaseDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
fa736190
CF
74 {
75 Init(nTypeIn, nVersionIn);
76 }
77
6bffc46a 78 CBaseDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
fa736190
CF
79 {
80 Init(nTypeIn, nVersionIn);
81 }
82
83 void Init(int nTypeIn, int nVersionIn)
84 {
85 nReadPos = 0;
86 nType = nTypeIn;
87 nVersion = nVersionIn;
88 }
89
6bffc46a 90 CBaseDataStream& operator+=(const CBaseDataStream& b)
fa736190
CF
91 {
92 vch.insert(vch.end(), b.begin(), b.end());
93 return *this;
94 }
95
6bffc46a 96 friend CBaseDataStream operator+(const CBaseDataStream& a, const CBaseDataStream& b)
fa736190 97 {
6bffc46a 98 CBaseDataStream ret = a;
fa736190
CF
99 ret += b;
100 return (ret);
101 }
102
103 std::string str() const
104 {
105 return (std::string(begin(), end()));
106 }
107
108
109 //
110 // Vector subset
111 //
112 const_iterator begin() const { return vch.begin() + nReadPos; }
113 iterator begin() { return vch.begin() + nReadPos; }
114 const_iterator end() const { return vch.end(); }
115 iterator end() { return vch.end(); }
116 size_type size() const { return vch.size() - nReadPos; }
117 bool empty() const { return vch.size() == nReadPos; }
118 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
119 void reserve(size_type n) { vch.reserve(n + nReadPos); }
120 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
121 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
122 void clear() { vch.clear(); nReadPos = 0; }
123 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
124 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
125
126 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
127 {
128 assert(last - first >= 0);
129 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
130 {
131 // special case for inserting at the front when there's room
132 nReadPos -= (last - first);
133 memcpy(&vch[nReadPos], &first[0], last - first);
134 }
135 else
136 vch.insert(it, first, last);
137 }
138
139#if !defined(_MSC_VER) || _MSC_VER >= 1300
140 void insert(iterator it, const char* first, const char* last)
141 {
142 assert(last - first >= 0);
143 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
144 {
145 // special case for inserting at the front when there's room
146 nReadPos -= (last - first);
147 memcpy(&vch[nReadPos], &first[0], last - first);
148 }
149 else
150 vch.insert(it, first, last);
151 }
152#endif
153
154 iterator erase(iterator it)
155 {
156 if (it == vch.begin() + nReadPos)
157 {
158 // special case for erasing from the front
159 if (++nReadPos >= vch.size())
160 {
161 // whenever we reach the end, we take the opportunity to clear the buffer
162 nReadPos = 0;
163 return vch.erase(vch.begin(), vch.end());
164 }
165 return vch.begin() + nReadPos;
166 }
167 else
168 return vch.erase(it);
169 }
170
171 iterator erase(iterator first, iterator last)
172 {
173 if (first == vch.begin() + nReadPos)
174 {
175 // special case for erasing from the front
176 if (last == vch.end())
177 {
178 nReadPos = 0;
179 return vch.erase(vch.begin(), vch.end());
180 }
181 else
182 {
183 nReadPos = (last - vch.begin());
184 return last;
185 }
186 }
187 else
188 return vch.erase(first, last);
189 }
190
191 inline void Compact()
192 {
193 vch.erase(vch.begin(), vch.begin() + nReadPos);
194 nReadPos = 0;
195 }
196
197 bool Rewind(size_type n)
198 {
199 // Rewind by n characters if the buffer hasn't been compacted yet
200 if (n > nReadPos)
201 return false;
202 nReadPos -= n;
203 return true;
204 }
205
206
207 //
208 // Stream subset
209 //
210 bool eof() const { return size() == 0; }
6bffc46a 211 CBaseDataStream* rdbuf() { return this; }
fa736190
CF
212 int in_avail() { return size(); }
213
214 void SetType(int n) { nType = n; }
215 int GetType() { return nType; }
216 void SetVersion(int n) { nVersion = n; }
217 int GetVersion() { return nVersion; }
218 void ReadVersion() { *this >> nVersion; }
219 void WriteVersion() { *this << nVersion; }
220
6bffc46a 221 CBaseDataStream& read(char* pch, size_t nSize)
fa736190
CF
222 {
223 // Read from the beginning of the buffer
224 unsigned int nReadPosNext = nReadPos + nSize;
225 if (nReadPosNext >= vch.size())
226 {
227 if (nReadPosNext > vch.size())
228 {
6bffc46a 229 throw std::ios_base::failure("CBaseDataStream::read(): end of data");
fa736190
CF
230 }
231 memcpy(pch, &vch[nReadPos], nSize);
232 nReadPos = 0;
233 vch.clear();
234 return (*this);
235 }
236 memcpy(pch, &vch[nReadPos], nSize);
237 nReadPos = nReadPosNext;
238 return (*this);
239 }
240
6bffc46a 241 CBaseDataStream& ignore(int nSize)
fa736190
CF
242 {
243 // Ignore from the beginning of the buffer
e9d221e7
PS
244 if (nSize < 0) {
245 throw std::ios_base::failure("CDataStream::ignore(): nSize negative");
246 }
fa736190
CF
247 unsigned int nReadPosNext = nReadPos + nSize;
248 if (nReadPosNext >= vch.size())
249 {
250 if (nReadPosNext > vch.size())
6bffc46a 251 throw std::ios_base::failure("CBaseDataStream::ignore(): end of data");
fa736190
CF
252 nReadPos = 0;
253 vch.clear();
254 return (*this);
255 }
256 nReadPos = nReadPosNext;
257 return (*this);
258 }
259
6bffc46a 260 CBaseDataStream& write(const char* pch, size_t nSize)
fa736190
CF
261 {
262 // Write to the end of the buffer
263 vch.insert(vch.end(), pch, pch + nSize);
264 return (*this);
265 }
266
267 template<typename Stream>
268 void Serialize(Stream& s, int nType, int nVersion) const
269 {
270 // Special case: stream << stream concatenates like stream += stream
271 if (!vch.empty())
272 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
273 }
274
275 template<typename T>
276 unsigned int GetSerializeSize(const T& obj)
277 {
278 // Tells the size of the object if serialized to this stream
279 return ::GetSerializeSize(obj, nType, nVersion);
280 }
281
282 template<typename T>
6bffc46a 283 CBaseDataStream& operator<<(const T& obj)
fa736190
CF
284 {
285 // Serialize to this stream
286 ::Serialize(*this, obj, nType, nVersion);
287 return (*this);
288 }
289
290 template<typename T>
6bffc46a 291 CBaseDataStream& operator>>(T& obj)
fa736190
CF
292 {
293 // Unserialize from this stream
294 ::Unserialize(*this, obj, nType, nVersion);
295 return (*this);
296 }
297
f0e90192
PJ
298 void GetAndClear(CSerializeData &d) {
299 d.insert(d.end(), begin(), end());
fa736190
CF
300 clear();
301 }
302};
303
6bffc46a
JG
304class CDataStream : public CBaseDataStream<CSerializeData>
305{
306public:
307 explicit CDataStream(int nTypeIn, int nVersionIn) : CBaseDataStream(nTypeIn, nVersionIn) { }
308
309 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) :
310 CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
311
312#if !defined(_MSC_VER) || _MSC_VER >= 1300
313 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) :
314 CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
315#endif
316
317 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) :
318 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
319
320 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) :
321 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
322
323 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) :
324 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
325
326};
327
fa736190
CF
328
329
330
331
332
333
334
335
336
337/** Non-refcounted RAII wrapper for FILE*
338 *
339 * Will automatically close the file when it goes out of scope if not null.
340 * If you're returning the file pointer, return file.release().
341 * If you need to close the file early, use file.fclose() instead of fclose(file).
342 */
343class CAutoFile
344{
345private:
346 // Disallow copies
347 CAutoFile(const CAutoFile&);
348 CAutoFile& operator=(const CAutoFile&);
349
350 int nType;
351 int nVersion;
352
353 FILE* file;
354
355public:
356 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
357 {
358 file = filenew;
359 nType = nTypeIn;
360 nVersion = nVersionIn;
361 }
362
363 ~CAutoFile()
364 {
365 fclose();
366 }
367
368 void fclose()
369 {
370 if (file) {
371 ::fclose(file);
372 file = NULL;
373 }
374 }
375
376 /** Get wrapped FILE* with transfer of ownership.
377 * @note This will invalidate the CAutoFile object, and makes it the responsibility of the caller
378 * of this function to clean up the returned FILE*.
379 */
380 FILE* release() { FILE* ret = file; file = NULL; return ret; }
381
382 /** Get wrapped FILE* without transfer of ownership.
383 * @note Ownership of the FILE* will remain with this class. Use this only if the scope of the
384 * CAutoFile outlives use of the passed pointer.
385 */
386 FILE* Get() const { return file; }
387
388 /** Return true if the wrapped FILE* is NULL, false otherwise.
389 */
390 bool IsNull() const { return (file == NULL); }
391
392 //
393 // Stream subset
394 //
395 void SetType(int n) { nType = n; }
396 int GetType() { return nType; }
397 void SetVersion(int n) { nVersion = n; }
398 int GetVersion() { return nVersion; }
399 void ReadVersion() { *this >> nVersion; }
400 void WriteVersion() { *this << nVersion; }
401
402 CAutoFile& read(char* pch, size_t nSize)
403 {
404 if (!file)
5262fde0 405 throw std::ios_base::failure("CAutoFile::read: file handle is NULL");
fa736190 406 if (fread(pch, 1, nSize, file) != nSize)
5262fde0 407 throw std::ios_base::failure(feof(file) ? "CAutoFile::read: end of file" : "CAutoFile::read: fread failed");
fa736190
CF
408 return (*this);
409 }
410
f588c5ed
PW
411 CAutoFile& ignore(size_t nSize)
412 {
413 if (!file)
414 throw std::ios_base::failure("CAutoFile::ignore: file handle is NULL");
415 unsigned char data[4096];
416 while (nSize > 0) {
417 size_t nNow = std::min<size_t>(nSize, sizeof(data));
418 if (fread(data, 1, nNow, file) != nNow)
419 throw std::ios_base::failure(feof(file) ? "CAutoFile::ignore: end of file" : "CAutoFile::read: fread failed");
420 nSize -= nNow;
421 }
422 return (*this);
423 }
424
fa736190
CF
425 CAutoFile& write(const char* pch, size_t nSize)
426 {
427 if (!file)
5262fde0 428 throw std::ios_base::failure("CAutoFile::write: file handle is NULL");
fa736190 429 if (fwrite(pch, 1, nSize, file) != nSize)
5262fde0 430 throw std::ios_base::failure("CAutoFile::write: write failed");
fa736190
CF
431 return (*this);
432 }
433
434 template<typename T>
435 unsigned int GetSerializeSize(const T& obj)
436 {
437 // Tells the size of the object if serialized to this stream
438 return ::GetSerializeSize(obj, nType, nVersion);
439 }
440
441 template<typename T>
442 CAutoFile& operator<<(const T& obj)
443 {
444 // Serialize to this stream
445 if (!file)
5262fde0 446 throw std::ios_base::failure("CAutoFile::operator<<: file handle is NULL");
fa736190
CF
447 ::Serialize(*this, obj, nType, nVersion);
448 return (*this);
449 }
450
451 template<typename T>
452 CAutoFile& operator>>(T& obj)
453 {
454 // Unserialize from this stream
455 if (!file)
5262fde0 456 throw std::ios_base::failure("CAutoFile::operator>>: file handle is NULL");
fa736190
CF
457 ::Unserialize(*this, obj, nType, nVersion);
458 return (*this);
459 }
460};
461
462/** Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to
463 * deserialize from. It guarantees the ability to rewind a given number of bytes.
464 *
465 * Will automatically close the file when it goes out of scope if not null.
466 * If you need to close the file early, use file.fclose() instead of fclose(file).
467 */
468class CBufferedFile
469{
470private:
471 // Disallow copies
472 CBufferedFile(const CBufferedFile&);
473 CBufferedFile& operator=(const CBufferedFile&);
474
475 int nType;
476 int nVersion;
477
478 FILE *src; // source file
479 uint64_t nSrcPos; // how many bytes have been read from source
480 uint64_t nReadPos; // how many bytes have been read from this
481 uint64_t nReadLimit; // up to which position we're allowed to read
482 uint64_t nRewind; // how many bytes we guarantee to rewind
483 std::vector<char> vchBuf; // the buffer
484
485protected:
486 // read data from the source to fill the buffer
487 bool Fill() {
488 unsigned int pos = nSrcPos % vchBuf.size();
489 unsigned int readNow = vchBuf.size() - pos;
490 unsigned int nAvail = vchBuf.size() - (nSrcPos - nReadPos) - nRewind;
491 if (nAvail < readNow)
492 readNow = nAvail;
493 if (readNow == 0)
494 return false;
495 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
496 if (read == 0) {
5262fde0 497 throw std::ios_base::failure(feof(src) ? "CBufferedFile::Fill: end of file" : "CBufferedFile::Fill: fread failed");
fa736190
CF
498 } else {
499 nSrcPos += read;
500 return true;
501 }
502 }
503
504public:
505 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
506 nSrcPos(0), nReadPos(0), nReadLimit((uint64_t)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0)
507 {
508 src = fileIn;
509 nType = nTypeIn;
510 nVersion = nVersionIn;
511 }
512
513 ~CBufferedFile()
514 {
515 fclose();
516 }
517
518 void fclose()
519 {
520 if (src) {
521 ::fclose(src);
522 src = NULL;
523 }
524 }
525
526 // check whether we're at the end of the source file
527 bool eof() const {
528 return nReadPos == nSrcPos && feof(src);
529 }
530
531 // read a number of bytes
532 CBufferedFile& read(char *pch, size_t nSize) {
533 if (nSize + nReadPos > nReadLimit)
534 throw std::ios_base::failure("Read attempted past buffer limit");
535 if (nSize + nRewind > vchBuf.size())
536 throw std::ios_base::failure("Read larger than buffer size");
537 while (nSize > 0) {
538 if (nReadPos == nSrcPos)
539 Fill();
540 unsigned int pos = nReadPos % vchBuf.size();
541 size_t nNow = nSize;
542 if (nNow + pos > vchBuf.size())
543 nNow = vchBuf.size() - pos;
544 if (nNow + nReadPos > nSrcPos)
545 nNow = nSrcPos - nReadPos;
546 memcpy(pch, &vchBuf[pos], nNow);
547 nReadPos += nNow;
548 pch += nNow;
549 nSize -= nNow;
550 }
551 return (*this);
552 }
553
554 // return the current reading position
555 uint64_t GetPos() {
556 return nReadPos;
557 }
558
559 // rewind to a given reading position
560 bool SetPos(uint64_t nPos) {
561 nReadPos = nPos;
562 if (nReadPos + nRewind < nSrcPos) {
563 nReadPos = nSrcPos - nRewind;
564 return false;
565 } else if (nReadPos > nSrcPos) {
566 nReadPos = nSrcPos;
567 return false;
568 } else {
569 return true;
570 }
571 }
572
573 bool Seek(uint64_t nPos) {
574 long nLongPos = nPos;
575 if (nPos != (uint64_t)nLongPos)
576 return false;
577 if (fseek(src, nLongPos, SEEK_SET))
578 return false;
579 nLongPos = ftell(src);
580 nSrcPos = nLongPos;
581 nReadPos = nLongPos;
582 return true;
583 }
584
585 // prevent reading beyond a certain position
586 // no argument removes the limit
587 bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
588 if (nPos < nReadPos)
589 return false;
590 nReadLimit = nPos;
591 return true;
592 }
593
594 template<typename T>
595 CBufferedFile& operator>>(T& obj) {
596 // Unserialize from this stream
597 ::Unserialize(*this, obj, nType, nVersion);
598 return (*this);
599 }
600
601 // search for a given byte in the stream, and remain positioned on it
602 void FindByte(char ch) {
603 while (true) {
604 if (nReadPos == nSrcPos)
605 Fill();
606 if (vchBuf[nReadPos % vchBuf.size()] == ch)
607 break;
608 nReadPos++;
609 }
610 }
611};
612
613#endif // BITCOIN_STREAMS_H
This page took 0.233676 seconds and 4 git commands to generate.