1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 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.
6 #ifndef BITCOIN_STREAMS_H
7 #define BITCOIN_STREAMS_H
9 #include "support/allocators/zeroafterfree.h"
10 #include "serialize.h"
25 template<typename Stream>
34 OverrideStream(Stream* stream_, int nType_, int nVersion_) : stream(stream_), nType(nType_), nVersion(nVersion_) {}
37 OverrideStream<Stream>& operator<<(const T& obj)
39 // Serialize to this stream
40 ::Serialize(*this, obj);
45 OverrideStream<Stream>& operator>>(T&& obj)
47 // Unserialize from this stream
48 ::Unserialize(*this, obj);
52 void write(const char* pch, size_t nSize)
54 stream->write(pch, nSize);
57 void read(char* pch, size_t nSize)
59 stream->read(pch, nSize);
62 int GetVersion() const { return nVersion; }
63 int GetType() const { return nType; }
67 OverrideStream<S> WithVersion(S* s, int nVersion)
69 return OverrideStream<S>(s, s->GetType(), nVersion);
72 /** Double ended buffer combining vector and stream-like interfaces.
74 * >> and << read and write unformatted data using the above serialization templates.
75 * Fills with data in linear time; some stringstream implementations take N^2 time.
77 template<typename SerializeType>
81 typedef SerializeType vector_type;
83 unsigned int nReadPos;
89 typedef typename vector_type::allocator_type allocator_type;
90 typedef typename vector_type::size_type size_type;
91 typedef typename vector_type::difference_type difference_type;
92 typedef typename vector_type::reference reference;
93 typedef typename vector_type::const_reference const_reference;
94 typedef typename vector_type::value_type value_type;
95 typedef typename vector_type::iterator iterator;
96 typedef typename vector_type::const_iterator const_iterator;
97 typedef typename vector_type::reverse_iterator reverse_iterator;
99 explicit CBaseDataStream(int nTypeIn, int nVersionIn)
101 Init(nTypeIn, nVersionIn);
104 CBaseDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
106 Init(nTypeIn, nVersionIn);
109 #if !defined(_MSC_VER) || _MSC_VER >= 1300
110 CBaseDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
112 Init(nTypeIn, nVersionIn);
116 CBaseDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
118 Init(nTypeIn, nVersionIn);
121 CBaseDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
123 Init(nTypeIn, nVersionIn);
126 CBaseDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
128 Init(nTypeIn, nVersionIn);
131 template <typename... Args>
132 CBaseDataStream(int nTypeIn, int nVersionIn, Args&&... args)
134 Init(nTypeIn, nVersionIn);
135 ::SerializeMany(*this, std::forward<Args>(args)...);
138 void Init(int nTypeIn, int nVersionIn)
142 nVersion = nVersionIn;
145 CBaseDataStream& operator+=(const CBaseDataStream& b)
147 vch.insert(vch.end(), b.begin(), b.end());
151 friend CBaseDataStream operator+(const CBaseDataStream& a, const CBaseDataStream& b)
153 CBaseDataStream ret = a;
158 std::string str() const
160 return (std::string(begin(), end()));
167 const_iterator begin() const { return vch.begin() + nReadPos; }
168 iterator begin() { return vch.begin() + nReadPos; }
169 const_iterator end() const { return vch.end(); }
170 iterator end() { return vch.end(); }
171 size_type size() const { return vch.size() - nReadPos; }
172 bool empty() const { return vch.size() == nReadPos; }
173 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
174 void reserve(size_type n) { vch.reserve(n + nReadPos); }
175 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
176 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
177 void clear() { vch.clear(); nReadPos = 0; }
178 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
179 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
181 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
183 if (last == first) return;
184 assert(last - first > 0);
185 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
187 // special case for inserting at the front when there's room
188 nReadPos -= (last - first);
189 memcpy(&vch[nReadPos], &first[0], last - first);
192 vch.insert(it, first, last);
195 #if !defined(_MSC_VER) || _MSC_VER >= 1300
196 void insert(iterator it, const char* first, const char* last)
198 if (last == first) return;
199 assert(last - first > 0);
200 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
202 // special case for inserting at the front when there's room
203 nReadPos -= (last - first);
204 memcpy(&vch[nReadPos], &first[0], last - first);
207 vch.insert(it, first, last);
211 iterator erase(iterator it)
213 if (it == vch.begin() + nReadPos)
215 // special case for erasing from the front
216 if (++nReadPos >= vch.size())
218 // whenever we reach the end, we take the opportunity to clear the buffer
220 return vch.erase(vch.begin(), vch.end());
222 return vch.begin() + nReadPos;
225 return vch.erase(it);
228 iterator erase(iterator first, iterator last)
230 if (first == vch.begin() + nReadPos)
232 // special case for erasing from the front
233 if (last == vch.end())
236 return vch.erase(vch.begin(), vch.end());
240 nReadPos = (last - vch.begin());
245 return vch.erase(first, last);
248 inline void Compact()
250 vch.erase(vch.begin(), vch.begin() + nReadPos);
254 bool Rewind(size_type n)
256 // Rewind by n characters if the buffer hasn't been compacted yet
267 bool eof() const { return size() == 0; }
268 CBaseDataStream* rdbuf() { return this; }
269 int in_avail() { return size(); }
271 void SetType(int n) { nType = n; }
272 int GetType() const { return nType; }
273 void SetVersion(int n) { nVersion = n; }
274 int GetVersion() const { return nVersion; }
276 void read(char* pch, size_t nSize)
278 if (nSize == 0) return;
280 if (pch == nullptr) {
281 throw std::ios_base::failure("CBaseDataStream::read(): cannot read from null pointer");
284 // Read from the beginning of the buffer
285 unsigned int nReadPosNext = nReadPos + nSize;
286 if (nReadPosNext >= vch.size())
288 if (nReadPosNext > vch.size())
290 throw std::ios_base::failure("CBaseDataStream::read(): end of data");
292 memcpy(pch, &vch[nReadPos], nSize);
297 memcpy(pch, &vch[nReadPos], nSize);
298 nReadPos = nReadPosNext;
301 void ignore(int nSize)
303 // Ignore from the beginning of the buffer
305 throw std::ios_base::failure("CDataStream::ignore(): nSize negative");
307 unsigned int nReadPosNext = nReadPos + nSize;
308 if (nReadPosNext >= vch.size())
310 if (nReadPosNext > vch.size())
311 throw std::ios_base::failure("CBaseDataStream::ignore(): end of data");
316 nReadPos = nReadPosNext;
319 void write(const char* pch, size_t nSize)
321 // Write to the end of the buffer
322 vch.insert(vch.end(), pch, pch + nSize);
325 template<typename Stream>
326 void Serialize(Stream& s) const
328 // Special case: stream << stream concatenates like stream += stream
330 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
334 CBaseDataStream& operator<<(const T& obj)
336 // Serialize to this stream
337 ::Serialize(*this, obj);
342 CBaseDataStream& operator>>(T& obj)
344 // Unserialize from this stream
345 ::Unserialize(*this, obj);
349 void GetAndClear(CSerializeData &d) {
350 d.insert(d.end(), begin(), end());
355 class CDataStream : public CBaseDataStream<CSerializeData>
358 explicit CDataStream(int nTypeIn, int nVersionIn) : CBaseDataStream(nTypeIn, nVersionIn) { }
360 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) :
361 CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
363 #if !defined(_MSC_VER) || _MSC_VER >= 1300
364 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) :
365 CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
368 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) :
369 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
371 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) :
372 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
374 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) :
375 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
377 template <typename... Args>
378 CDataStream(int nTypeIn, int nVersionIn, Args&&... args) :
379 CBaseDataStream(nTypeIn, nVersionIn, args...) { }
392 /** Non-refcounted RAII wrapper for FILE*
394 * Will automatically close the file when it goes out of scope if not null.
395 * If you're returning the file pointer, return file.release().
396 * If you need to close the file early, use file.fclose() instead of fclose(file).
402 CAutoFile(const CAutoFile&);
403 CAutoFile& operator=(const CAutoFile&);
411 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn)
429 /** Get wrapped FILE* with transfer of ownership.
430 * @note This will invalidate the CAutoFile object, and makes it the responsibility of the caller
431 * of this function to clean up the returned FILE*.
433 FILE* release() { FILE* ret = file; file = NULL; return ret; }
435 /** Get wrapped FILE* without transfer of ownership.
436 * @note Ownership of the FILE* will remain with this class. Use this only if the scope of the
437 * CAutoFile outlives use of the passed pointer.
439 FILE* Get() const { return file; }
441 /** Return true if the wrapped FILE* is NULL, false otherwise.
443 bool IsNull() const { return (file == NULL); }
448 int GetType() const { return nType; }
449 int GetVersion() const { return nVersion; }
451 void read(char* pch, size_t nSize)
454 throw std::ios_base::failure("CAutoFile::read: file handle is NULL");
455 if (fread(pch, 1, nSize, file) != nSize)
456 throw std::ios_base::failure(feof(file) ? "CAutoFile::read: end of file" : "CAutoFile::read: fread failed");
459 void ignore(size_t nSize)
462 throw std::ios_base::failure("CAutoFile::ignore: file handle is NULL");
463 unsigned char data[4096];
465 size_t nNow = std::min<size_t>(nSize, sizeof(data));
466 if (fread(data, 1, nNow, file) != nNow)
467 throw std::ios_base::failure(feof(file) ? "CAutoFile::ignore: end of file" : "CAutoFile::read: fread failed");
472 void write(const char* pch, size_t nSize)
475 throw std::ios_base::failure("CAutoFile::write: file handle is NULL");
476 if (fwrite(pch, 1, nSize, file) != nSize)
477 throw std::ios_base::failure("CAutoFile::write: write failed");
481 CAutoFile& operator<<(const T& obj)
483 // Serialize to this stream
485 throw std::ios_base::failure("CAutoFile::operator<<: file handle is NULL");
486 ::Serialize(*this, obj);
491 CAutoFile& operator>>(T& obj)
493 // Unserialize from this stream
495 throw std::ios_base::failure("CAutoFile::operator>>: file handle is NULL");
496 ::Unserialize(*this, obj);
501 /** Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to
502 * deserialize from. It guarantees the ability to rewind a given number of bytes.
504 * Will automatically close the file when it goes out of scope if not null.
505 * If you need to close the file early, use file.fclose() instead of fclose(file).
511 CBufferedFile(const CBufferedFile&);
512 CBufferedFile& operator=(const CBufferedFile&);
517 FILE *src; // source file
518 uint64_t nSrcPos; // how many bytes have been read from source
519 uint64_t nReadPos; // how many bytes have been read from this
520 uint64_t nReadLimit; // up to which position we're allowed to read
521 uint64_t nRewind; // how many bytes we guarantee to rewind
522 std::vector<char> vchBuf; // the buffer
525 // read data from the source to fill the buffer
527 unsigned int pos = nSrcPos % vchBuf.size();
528 unsigned int readNow = vchBuf.size() - pos;
529 unsigned int nAvail = vchBuf.size() - (nSrcPos - nReadPos) - nRewind;
530 if (nAvail < readNow)
534 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
536 throw std::ios_base::failure(feof(src) ? "CBufferedFile::Fill: end of file" : "CBufferedFile::Fill: fread failed");
544 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
545 nType(nTypeIn), nVersion(nVersionIn), nSrcPos(0), nReadPos(0), nReadLimit((uint64_t)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0)
555 int GetVersion() const { return nVersion; }
556 int GetType() const { return nType; }
566 // check whether we're at the end of the source file
568 return nReadPos == nSrcPos && feof(src);
571 // read a number of bytes
572 void read(char *pch, size_t nSize) {
573 if (nSize == 0) return;
575 if (pch == nullptr) {
576 throw std::ios_base::failure("CBufferedFile::read(): cannot read from null pointer");
579 if (nSize + nReadPos > nReadLimit)
580 throw std::ios_base::failure("Read attempted past buffer limit");
581 if (nSize + nRewind > vchBuf.size())
582 throw std::ios_base::failure("Read larger than buffer size");
584 if (nReadPos == nSrcPos)
586 unsigned int pos = nReadPos % vchBuf.size();
588 if (nNow + pos > vchBuf.size())
589 nNow = vchBuf.size() - pos;
590 if (nNow + nReadPos > nSrcPos)
591 nNow = nSrcPos - nReadPos;
592 memcpy(pch, &vchBuf[pos], nNow);
599 // return the current reading position
604 // rewind to a given reading position
605 bool SetPos(uint64_t nPos) {
607 if (nReadPos + nRewind < nSrcPos) {
608 nReadPos = nSrcPos - nRewind;
610 } else if (nReadPos > nSrcPos) {
618 bool Seek(uint64_t nPos) {
619 long nLongPos = nPos;
620 if (nPos != (uint64_t)nLongPos)
622 if (fseek(src, nLongPos, SEEK_SET))
624 nLongPos = ftell(src);
630 // prevent reading beyond a certain position
631 // no argument removes the limit
632 bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
640 CBufferedFile& operator>>(T& obj) {
641 // Unserialize from this stream
642 ::Unserialize(*this, obj);
646 // search for a given byte in the stream, and remain positioned on it
647 void FindByte(char ch) {
649 if (nReadPos == nSrcPos)
651 if (vchBuf[nReadPos % vchBuf.size()] == ch)
658 #endif // BITCOIN_STREAMS_H