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 throw std::ios_base::failure("CDataStream::ignore(): nSize negative");
247 unsigned int nReadPosNext = nReadPos + nSize;
248 if (nReadPosNext >= vch.size())
250 if (nReadPosNext > vch.size())
251 throw std::ios_base::failure("CBaseDataStream::ignore(): end of data");
256 nReadPos = nReadPosNext;
260 CBaseDataStream& write(const char* pch, size_t nSize)
262 // Write to the end of the buffer
263 vch.insert(vch.end(), pch, pch + nSize);
267 template<typename Stream>
268 void Serialize(Stream& s, int nType, int nVersion) const
270 // Special case: stream << stream concatenates like stream += stream
272 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
276 unsigned int GetSerializeSize(const T& obj)
278 // Tells the size of the object if serialized to this stream
279 return ::GetSerializeSize(obj, nType, nVersion);
283 CBaseDataStream& operator<<(const T& obj)
285 // Serialize to this stream
286 ::Serialize(*this, obj, nType, nVersion);
291 CBaseDataStream& operator>>(T& obj)
293 // Unserialize from this stream
294 ::Unserialize(*this, obj, nType, nVersion);
298 void GetAndClear(CSerializeData &data) {
299 data.insert(data.end(), begin(), end());
304 class CDataStream : public CBaseDataStream<CSerializeData>
307 explicit CDataStream(int nTypeIn, int nVersionIn) : CBaseDataStream(nTypeIn, nVersionIn) { }
309 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) :
310 CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
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) { }
317 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) :
318 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
320 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) :
321 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
323 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) :
324 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
337 /** Non-refcounted RAII wrapper for FILE*
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).
347 CAutoFile(const CAutoFile&);
348 CAutoFile& operator=(const CAutoFile&);
356 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
360 nVersion = nVersionIn;
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*.
380 FILE* release() { FILE* ret = file; file = NULL; return ret; }
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.
386 FILE* Get() const { return file; }
388 /** Return true if the wrapped FILE* is NULL, false otherwise.
390 bool IsNull() const { return (file == NULL); }
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; }
402 CAutoFile& read(char* pch, size_t nSize)
405 throw std::ios_base::failure("CAutoFile::read: file handle is NULL");
406 if (fread(pch, 1, nSize, file) != nSize)
407 throw std::ios_base::failure(feof(file) ? "CAutoFile::read: end of file" : "CAutoFile::read: fread failed");
411 CAutoFile& ignore(size_t nSize)
414 throw std::ios_base::failure("CAutoFile::ignore: file handle is NULL");
415 unsigned char data[4096];
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");
425 CAutoFile& write(const char* pch, size_t nSize)
428 throw std::ios_base::failure("CAutoFile::write: file handle is NULL");
429 if (fwrite(pch, 1, nSize, file) != nSize)
430 throw std::ios_base::failure("CAutoFile::write: write failed");
435 unsigned int GetSerializeSize(const T& obj)
437 // Tells the size of the object if serialized to this stream
438 return ::GetSerializeSize(obj, nType, nVersion);
442 CAutoFile& operator<<(const T& obj)
444 // Serialize to this stream
446 throw std::ios_base::failure("CAutoFile::operator<<: file handle is NULL");
447 ::Serialize(*this, obj, nType, nVersion);
452 CAutoFile& operator>>(T& obj)
454 // Unserialize from this stream
456 throw std::ios_base::failure("CAutoFile::operator>>: file handle is NULL");
457 ::Unserialize(*this, obj, nType, nVersion);
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.
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).
472 CBufferedFile(const CBufferedFile&);
473 CBufferedFile& operator=(const CBufferedFile&);
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
486 // read data from the source to fill the buffer
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)
495 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
497 throw std::ios_base::failure(feof(src) ? "CBufferedFile::Fill: end of file" : "CBufferedFile::Fill: fread failed");
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)
510 nVersion = nVersionIn;
526 // check whether we're at the end of the source file
528 return nReadPos == nSrcPos && feof(src);
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");
538 if (nReadPos == nSrcPos)
540 unsigned int pos = nReadPos % vchBuf.size();
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);
554 // return the current reading position
559 // rewind to a given reading position
560 bool SetPos(uint64_t nPos) {
562 if (nReadPos + nRewind < nSrcPos) {
563 nReadPos = nSrcPos - nRewind;
565 } else if (nReadPos > nSrcPos) {
573 bool Seek(uint64_t nPos) {
574 long nLongPos = nPos;
575 if (nPos != (uint64_t)nLongPos)
577 if (fseek(src, nLongPos, SEEK_SET))
579 nLongPos = ftell(src);
585 // prevent reading beyond a certain position
586 // no argument removes the limit
587 bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
595 CBufferedFile& operator>>(T& obj) {
596 // Unserialize from this stream
597 ::Unserialize(*this, obj, nType, nVersion);
601 // search for a given byte in the stream, and remain positioned on it
602 void FindByte(char ch) {
604 if (nReadPos == nSrcPos)
606 if (vchBuf[nReadPos % vchBuf.size()] == ch)
613 #endif // BITCOIN_STREAMS_H