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 /** Double ended buffer combining vector and stream-like interfaces.
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.
30 template<typename SerializeType>
34 typedef SerializeType vector_type;
36 unsigned int nReadPos;
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;
51 explicit CBaseDataStream(int nTypeIn, int nVersionIn)
53 Init(nTypeIn, nVersionIn);
56 CBaseDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
58 Init(nTypeIn, nVersionIn);
61 #if !defined(_MSC_VER) || _MSC_VER >= 1300
62 CBaseDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
64 Init(nTypeIn, nVersionIn);
68 CBaseDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
70 Init(nTypeIn, nVersionIn);
73 CBaseDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
75 Init(nTypeIn, nVersionIn);
78 CBaseDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
80 Init(nTypeIn, nVersionIn);
83 void Init(int nTypeIn, int nVersionIn)
87 nVersion = nVersionIn;
90 CBaseDataStream& operator+=(const CBaseDataStream& b)
92 vch.insert(vch.end(), b.begin(), b.end());
96 friend CBaseDataStream operator+(const CBaseDataStream& a, const CBaseDataStream& b)
98 CBaseDataStream ret = a;
103 std::string str() const
105 return (std::string(begin(), end()));
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); }
126 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
128 assert(last - first >= 0);
129 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
131 // special case for inserting at the front when there's room
132 nReadPos -= (last - first);
133 memcpy(&vch[nReadPos], &first[0], last - first);
136 vch.insert(it, first, last);
139 #if !defined(_MSC_VER) || _MSC_VER >= 1300
140 void insert(iterator it, const char* first, const char* last)
142 assert(last - first >= 0);
143 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
145 // special case for inserting at the front when there's room
146 nReadPos -= (last - first);
147 memcpy(&vch[nReadPos], &first[0], last - first);
150 vch.insert(it, first, last);
154 iterator erase(iterator it)
156 if (it == vch.begin() + nReadPos)
158 // special case for erasing from the front
159 if (++nReadPos >= vch.size())
161 // whenever we reach the end, we take the opportunity to clear the buffer
163 return vch.erase(vch.begin(), vch.end());
165 return vch.begin() + nReadPos;
168 return vch.erase(it);
171 iterator erase(iterator first, iterator last)
173 if (first == vch.begin() + nReadPos)
175 // special case for erasing from the front
176 if (last == vch.end())
179 return vch.erase(vch.begin(), vch.end());
183 nReadPos = (last - vch.begin());
188 return vch.erase(first, last);
191 inline void Compact()
193 vch.erase(vch.begin(), vch.begin() + nReadPos);
197 bool Rewind(size_type n)
199 // Rewind by n characters if the buffer hasn't been compacted yet
210 bool eof() const { return size() == 0; }
211 CBaseDataStream* rdbuf() { return this; }
212 int in_avail() { return size(); }
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; }
221 CBaseDataStream& read(char* pch, size_t nSize)
223 // Read from the beginning of the buffer
224 unsigned int nReadPosNext = nReadPos + nSize;
225 if (nReadPosNext >= vch.size())
227 if (nReadPosNext > vch.size())
229 throw std::ios_base::failure("CBaseDataStream::read(): end of data");
231 memcpy(pch, &vch[nReadPos], nSize);
236 memcpy(pch, &vch[nReadPos], nSize);
237 nReadPos = nReadPosNext;
241 CBaseDataStream& ignore(int nSize)
243 // Ignore from the beginning of the buffer
245 unsigned int nReadPosNext = nReadPos + nSize;
246 if (nReadPosNext >= vch.size())
248 if (nReadPosNext > vch.size())
249 throw std::ios_base::failure("CBaseDataStream::ignore(): end of data");
254 nReadPos = nReadPosNext;
258 CBaseDataStream& write(const char* pch, size_t nSize)
260 // Write to the end of the buffer
261 vch.insert(vch.end(), pch, pch + nSize);
265 template<typename Stream>
266 void Serialize(Stream& s, int nType, int nVersion) const
268 // Special case: stream << stream concatenates like stream += stream
270 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
274 unsigned int GetSerializeSize(const T& obj)
276 // Tells the size of the object if serialized to this stream
277 return ::GetSerializeSize(obj, nType, nVersion);
281 CBaseDataStream& operator<<(const T& obj)
283 // Serialize to this stream
284 ::Serialize(*this, obj, nType, nVersion);
289 CBaseDataStream& operator>>(T& obj)
291 // Unserialize from this stream
292 ::Unserialize(*this, obj, nType, nVersion);
296 void GetAndClear(CSerializeData &data) {
297 data.insert(data.end(), begin(), end());
302 class CDataStream : public CBaseDataStream<CSerializeData>
305 explicit CDataStream(int nTypeIn, int nVersionIn) : CBaseDataStream(nTypeIn, nVersionIn) { }
307 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) :
308 CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
310 #if !defined(_MSC_VER) || _MSC_VER >= 1300
311 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) :
312 CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
315 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) :
316 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
318 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) :
319 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
321 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) :
322 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
335 /** Non-refcounted RAII wrapper for FILE*
337 * Will automatically close the file when it goes out of scope if not null.
338 * If you're returning the file pointer, return file.release().
339 * If you need to close the file early, use file.fclose() instead of fclose(file).
345 CAutoFile(const CAutoFile&);
346 CAutoFile& operator=(const CAutoFile&);
354 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
358 nVersion = nVersionIn;
374 /** Get wrapped FILE* with transfer of ownership.
375 * @note This will invalidate the CAutoFile object, and makes it the responsibility of the caller
376 * of this function to clean up the returned FILE*.
378 FILE* release() { FILE* ret = file; file = NULL; return ret; }
380 /** Get wrapped FILE* without transfer of ownership.
381 * @note Ownership of the FILE* will remain with this class. Use this only if the scope of the
382 * CAutoFile outlives use of the passed pointer.
384 FILE* Get() const { return file; }
386 /** Return true if the wrapped FILE* is NULL, false otherwise.
388 bool IsNull() const { return (file == NULL); }
393 void SetType(int n) { nType = n; }
394 int GetType() { return nType; }
395 void SetVersion(int n) { nVersion = n; }
396 int GetVersion() { return nVersion; }
397 void ReadVersion() { *this >> nVersion; }
398 void WriteVersion() { *this << nVersion; }
400 CAutoFile& read(char* pch, size_t nSize)
403 throw std::ios_base::failure("CAutoFile::read: file handle is NULL");
404 if (fread(pch, 1, nSize, file) != nSize)
405 throw std::ios_base::failure(feof(file) ? "CAutoFile::read: end of file" : "CAutoFile::read: fread failed");
409 CAutoFile& write(const char* pch, size_t nSize)
412 throw std::ios_base::failure("CAutoFile::write: file handle is NULL");
413 if (fwrite(pch, 1, nSize, file) != nSize)
414 throw std::ios_base::failure("CAutoFile::write: write failed");
419 unsigned int GetSerializeSize(const T& obj)
421 // Tells the size of the object if serialized to this stream
422 return ::GetSerializeSize(obj, nType, nVersion);
426 CAutoFile& operator<<(const T& obj)
428 // Serialize to this stream
430 throw std::ios_base::failure("CAutoFile::operator<<: file handle is NULL");
431 ::Serialize(*this, obj, nType, nVersion);
436 CAutoFile& operator>>(T& obj)
438 // Unserialize from this stream
440 throw std::ios_base::failure("CAutoFile::operator>>: file handle is NULL");
441 ::Unserialize(*this, obj, nType, nVersion);
446 /** Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to
447 * deserialize from. It guarantees the ability to rewind a given number of bytes.
449 * Will automatically close the file when it goes out of scope if not null.
450 * If you need to close the file early, use file.fclose() instead of fclose(file).
456 CBufferedFile(const CBufferedFile&);
457 CBufferedFile& operator=(const CBufferedFile&);
462 FILE *src; // source file
463 uint64_t nSrcPos; // how many bytes have been read from source
464 uint64_t nReadPos; // how many bytes have been read from this
465 uint64_t nReadLimit; // up to which position we're allowed to read
466 uint64_t nRewind; // how many bytes we guarantee to rewind
467 std::vector<char> vchBuf; // the buffer
470 // read data from the source to fill the buffer
472 unsigned int pos = nSrcPos % vchBuf.size();
473 unsigned int readNow = vchBuf.size() - pos;
474 unsigned int nAvail = vchBuf.size() - (nSrcPos - nReadPos) - nRewind;
475 if (nAvail < readNow)
479 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
481 throw std::ios_base::failure(feof(src) ? "CBufferedFile::Fill: end of file" : "CBufferedFile::Fill: fread failed");
489 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
490 nSrcPos(0), nReadPos(0), nReadLimit((uint64_t)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0)
494 nVersion = nVersionIn;
510 // check whether we're at the end of the source file
512 return nReadPos == nSrcPos && feof(src);
515 // read a number of bytes
516 CBufferedFile& read(char *pch, size_t nSize) {
517 if (nSize + nReadPos > nReadLimit)
518 throw std::ios_base::failure("Read attempted past buffer limit");
519 if (nSize + nRewind > vchBuf.size())
520 throw std::ios_base::failure("Read larger than buffer size");
522 if (nReadPos == nSrcPos)
524 unsigned int pos = nReadPos % vchBuf.size();
526 if (nNow + pos > vchBuf.size())
527 nNow = vchBuf.size() - pos;
528 if (nNow + nReadPos > nSrcPos)
529 nNow = nSrcPos - nReadPos;
530 memcpy(pch, &vchBuf[pos], nNow);
538 // return the current reading position
543 // rewind to a given reading position
544 bool SetPos(uint64_t nPos) {
546 if (nReadPos + nRewind < nSrcPos) {
547 nReadPos = nSrcPos - nRewind;
549 } else if (nReadPos > nSrcPos) {
557 bool Seek(uint64_t nPos) {
558 long nLongPos = nPos;
559 if (nPos != (uint64_t)nLongPos)
561 if (fseek(src, nLongPos, SEEK_SET))
563 nLongPos = ftell(src);
569 // prevent reading beyond a certain position
570 // no argument removes the limit
571 bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
579 CBufferedFile& operator>>(T& obj) {
580 // Unserialize from this stream
581 ::Unserialize(*this, obj, nType, nVersion);
585 // search for a given byte in the stream, and remain positioned on it
586 void FindByte(char ch) {
588 if (nReadPos == nSrcPos)
590 if (vchBuf[nReadPos % vchBuf.size()] == ch)
597 #endif // BITCOIN_STREAMS_H