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;
42 typedef typename vector_type::allocator_type allocator_type;
43 typedef typename vector_type::size_type size_type;
44 typedef typename vector_type::difference_type difference_type;
45 typedef typename vector_type::reference reference;
46 typedef typename vector_type::const_reference const_reference;
47 typedef typename vector_type::value_type value_type;
48 typedef typename vector_type::iterator iterator;
49 typedef typename vector_type::const_iterator const_iterator;
50 typedef typename vector_type::reverse_iterator reverse_iterator;
52 explicit CBaseDataStream(int nTypeIn, int nVersionIn)
54 Init(nTypeIn, nVersionIn);
57 CBaseDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
59 Init(nTypeIn, nVersionIn);
62 #if !defined(_MSC_VER) || _MSC_VER >= 1300
63 CBaseDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
65 Init(nTypeIn, nVersionIn);
69 CBaseDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
71 Init(nTypeIn, nVersionIn);
74 CBaseDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
76 Init(nTypeIn, nVersionIn);
79 CBaseDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
81 Init(nTypeIn, nVersionIn);
84 template <typename... Args>
85 CBaseDataStream(int nTypeIn, int nVersionIn, Args&&... args)
87 Init(nTypeIn, nVersionIn);
88 ::SerializeMany(*this, nType, nVersion, std::forward<Args>(args)...);
91 void Init(int nTypeIn, int nVersionIn)
95 nVersion = nVersionIn;
98 CBaseDataStream& operator+=(const CBaseDataStream& b)
100 vch.insert(vch.end(), b.begin(), b.end());
104 friend CBaseDataStream operator+(const CBaseDataStream& a, const CBaseDataStream& b)
106 CBaseDataStream ret = a;
111 std::string str() const
113 return (std::string(begin(), end()));
120 const_iterator begin() const { return vch.begin() + nReadPos; }
121 iterator begin() { return vch.begin() + nReadPos; }
122 const_iterator end() const { return vch.end(); }
123 iterator end() { return vch.end(); }
124 size_type size() const { return vch.size() - nReadPos; }
125 bool empty() const { return vch.size() == nReadPos; }
126 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
127 void reserve(size_type n) { vch.reserve(n + nReadPos); }
128 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
129 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
130 void clear() { vch.clear(); nReadPos = 0; }
131 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
132 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
134 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
136 assert(last - first >= 0);
137 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
139 // special case for inserting at the front when there's room
140 nReadPos -= (last - first);
141 memcpy(&vch[nReadPos], &first[0], last - first);
144 vch.insert(it, first, last);
147 #if !defined(_MSC_VER) || _MSC_VER >= 1300
148 void insert(iterator it, const char* first, const char* last)
150 assert(last - first >= 0);
151 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
153 // special case for inserting at the front when there's room
154 nReadPos -= (last - first);
155 memcpy(&vch[nReadPos], &first[0], last - first);
158 vch.insert(it, first, last);
162 iterator erase(iterator it)
164 if (it == vch.begin() + nReadPos)
166 // special case for erasing from the front
167 if (++nReadPos >= vch.size())
169 // whenever we reach the end, we take the opportunity to clear the buffer
171 return vch.erase(vch.begin(), vch.end());
173 return vch.begin() + nReadPos;
176 return vch.erase(it);
179 iterator erase(iterator first, iterator last)
181 if (first == vch.begin() + nReadPos)
183 // special case for erasing from the front
184 if (last == vch.end())
187 return vch.erase(vch.begin(), vch.end());
191 nReadPos = (last - vch.begin());
196 return vch.erase(first, last);
199 inline void Compact()
201 vch.erase(vch.begin(), vch.begin() + nReadPos);
205 bool Rewind(size_type n)
207 // Rewind by n characters if the buffer hasn't been compacted yet
218 bool eof() const { return size() == 0; }
219 CBaseDataStream* rdbuf() { return this; }
220 int in_avail() { return size(); }
222 void SetType(int n) { nType = n; }
223 int GetType() const { return nType; }
224 void SetVersion(int n) { nVersion = n; }
225 int GetVersion() const { return nVersion; }
227 void read(char* pch, size_t nSize)
229 // Read from the beginning of the buffer
230 unsigned int nReadPosNext = nReadPos + nSize;
231 if (nReadPosNext >= vch.size())
233 if (nReadPosNext > vch.size())
235 throw std::ios_base::failure("CBaseDataStream::read(): end of data");
237 memcpy(pch, &vch[nReadPos], nSize);
242 memcpy(pch, &vch[nReadPos], nSize);
243 nReadPos = nReadPosNext;
246 void ignore(int nSize)
248 // Ignore from the beginning of the buffer
250 throw std::ios_base::failure("CDataStream::ignore(): nSize negative");
252 unsigned int nReadPosNext = nReadPos + nSize;
253 if (nReadPosNext >= vch.size())
255 if (nReadPosNext > vch.size())
256 throw std::ios_base::failure("CBaseDataStream::ignore(): end of data");
261 nReadPos = nReadPosNext;
264 void write(const char* pch, size_t nSize)
266 // Write to the end of the buffer
267 vch.insert(vch.end(), pch, pch + nSize);
270 template<typename Stream>
271 void Serialize(Stream& s, int nType, int nVersion) const
273 // Special case: stream << stream concatenates like stream += stream
275 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
279 CBaseDataStream& operator<<(const T& obj)
281 // Serialize to this stream
282 ::Serialize(*this, obj, nType, nVersion);
287 CBaseDataStream& operator>>(T& obj)
289 // Unserialize from this stream
290 ::Unserialize(*this, obj, nType, nVersion);
294 void GetAndClear(CSerializeData &d) {
295 d.insert(d.end(), begin(), end());
300 class CDataStream : public CBaseDataStream<CSerializeData>
303 explicit CDataStream(int nTypeIn, int nVersionIn) : CBaseDataStream(nTypeIn, nVersionIn) { }
305 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) :
306 CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
308 #if !defined(_MSC_VER) || _MSC_VER >= 1300
309 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) :
310 CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
313 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) :
314 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
316 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) :
317 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
319 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) :
320 CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
322 template <typename... Args>
323 CDataStream(int nTypeIn, int nVersionIn, Args&&... args) :
324 CBaseDataStream(nTypeIn, nVersionIn, args...) { }
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) : nType(nTypeIn), 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 int GetType() const { return nType; }
394 int GetVersion() const { return nVersion; }
396 void read(char* pch, size_t nSize)
399 throw std::ios_base::failure("CAutoFile::read: file handle is NULL");
400 if (fread(pch, 1, nSize, file) != nSize)
401 throw std::ios_base::failure(feof(file) ? "CAutoFile::read: end of file" : "CAutoFile::read: fread failed");
404 void ignore(size_t nSize)
407 throw std::ios_base::failure("CAutoFile::ignore: file handle is NULL");
408 unsigned char data[4096];
410 size_t nNow = std::min<size_t>(nSize, sizeof(data));
411 if (fread(data, 1, nNow, file) != nNow)
412 throw std::ios_base::failure(feof(file) ? "CAutoFile::ignore: end of file" : "CAutoFile::read: fread failed");
417 void write(const char* pch, size_t nSize)
420 throw std::ios_base::failure("CAutoFile::write: file handle is NULL");
421 if (fwrite(pch, 1, nSize, file) != nSize)
422 throw std::ios_base::failure("CAutoFile::write: write failed");
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 nType(nTypeIn), nVersion(nVersionIn), nSrcPos(0), nReadPos(0), nReadLimit((uint64_t)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0)
508 // check whether we're at the end of the source file
510 return nReadPos == nSrcPos && feof(src);
513 // read a number of bytes
514 void read(char *pch, size_t nSize) {
515 if (nSize + nReadPos > nReadLimit)
516 throw std::ios_base::failure("Read attempted past buffer limit");
517 if (nSize + nRewind > vchBuf.size())
518 throw std::ios_base::failure("Read larger than buffer size");
520 if (nReadPos == nSrcPos)
522 unsigned int pos = nReadPos % vchBuf.size();
524 if (nNow + pos > vchBuf.size())
525 nNow = vchBuf.size() - pos;
526 if (nNow + nReadPos > nSrcPos)
527 nNow = nSrcPos - nReadPos;
528 memcpy(pch, &vchBuf[pos], nNow);
535 // return the current reading position
540 // rewind to a given reading position
541 bool SetPos(uint64_t nPos) {
543 if (nReadPos + nRewind < nSrcPos) {
544 nReadPos = nSrcPos - nRewind;
546 } else if (nReadPos > nSrcPos) {
554 bool Seek(uint64_t nPos) {
555 long nLongPos = nPos;
556 if (nPos != (uint64_t)nLongPos)
558 if (fseek(src, nLongPos, SEEK_SET))
560 nLongPos = ftell(src);
566 // prevent reading beyond a certain position
567 // no argument removes the limit
568 bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
576 CBufferedFile& operator>>(T& obj) {
577 // Unserialize from this stream
578 ::Unserialize(*this, obj, nType, nVersion);
582 // search for a given byte in the stream, and remain positioned on it
583 void FindByte(char ch) {
585 if (nReadPos == nSrcPos)
587 if (vchBuf[nReadPos % vchBuf.size()] == ch)
594 #endif // BITCOIN_STREAMS_H