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 "allocators.h"
10 #include "serialize.h"
24 /** Double ended buffer combining vector and stream-like interfaces.
26 * >> and << read and write unformatted data using the above serialization templates.
27 * Fills with data in linear time; some stringstream implementations take N^2 time.
32 typedef CSerializeData vector_type;
34 unsigned int nReadPos;
39 typedef vector_type::allocator_type allocator_type;
40 typedef vector_type::size_type size_type;
41 typedef vector_type::difference_type difference_type;
42 typedef vector_type::reference reference;
43 typedef vector_type::const_reference const_reference;
44 typedef vector_type::value_type value_type;
45 typedef vector_type::iterator iterator;
46 typedef vector_type::const_iterator const_iterator;
47 typedef vector_type::reverse_iterator reverse_iterator;
49 explicit CDataStream(int nTypeIn, int nVersionIn)
51 Init(nTypeIn, nVersionIn);
54 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
56 Init(nTypeIn, nVersionIn);
59 #if !defined(_MSC_VER) || _MSC_VER >= 1300
60 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
62 Init(nTypeIn, nVersionIn);
66 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
68 Init(nTypeIn, nVersionIn);
71 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
73 Init(nTypeIn, nVersionIn);
76 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
78 Init(nTypeIn, nVersionIn);
81 void Init(int nTypeIn, int nVersionIn)
85 nVersion = nVersionIn;
88 CDataStream& operator+=(const CDataStream& b)
90 vch.insert(vch.end(), b.begin(), b.end());
94 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
101 std::string str() const
103 return (std::string(begin(), end()));
110 const_iterator begin() const { return vch.begin() + nReadPos; }
111 iterator begin() { return vch.begin() + nReadPos; }
112 const_iterator end() const { return vch.end(); }
113 iterator end() { return vch.end(); }
114 size_type size() const { return vch.size() - nReadPos; }
115 bool empty() const { return vch.size() == nReadPos; }
116 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
117 void reserve(size_type n) { vch.reserve(n + nReadPos); }
118 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
119 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
120 void clear() { vch.clear(); nReadPos = 0; }
121 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
122 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
124 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
126 assert(last - first >= 0);
127 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
129 // special case for inserting at the front when there's room
130 nReadPos -= (last - first);
131 memcpy(&vch[nReadPos], &first[0], last - first);
134 vch.insert(it, first, last);
137 #if !defined(_MSC_VER) || _MSC_VER >= 1300
138 void insert(iterator it, const char* first, const char* last)
140 assert(last - first >= 0);
141 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
143 // special case for inserting at the front when there's room
144 nReadPos -= (last - first);
145 memcpy(&vch[nReadPos], &first[0], last - first);
148 vch.insert(it, first, last);
152 iterator erase(iterator it)
154 if (it == vch.begin() + nReadPos)
156 // special case for erasing from the front
157 if (++nReadPos >= vch.size())
159 // whenever we reach the end, we take the opportunity to clear the buffer
161 return vch.erase(vch.begin(), vch.end());
163 return vch.begin() + nReadPos;
166 return vch.erase(it);
169 iterator erase(iterator first, iterator last)
171 if (first == vch.begin() + nReadPos)
173 // special case for erasing from the front
174 if (last == vch.end())
177 return vch.erase(vch.begin(), vch.end());
181 nReadPos = (last - vch.begin());
186 return vch.erase(first, last);
189 inline void Compact()
191 vch.erase(vch.begin(), vch.begin() + nReadPos);
195 bool Rewind(size_type n)
197 // Rewind by n characters if the buffer hasn't been compacted yet
208 bool eof() const { return size() == 0; }
209 CDataStream* rdbuf() { return this; }
210 int in_avail() { return size(); }
212 void SetType(int n) { nType = n; }
213 int GetType() { return nType; }
214 void SetVersion(int n) { nVersion = n; }
215 int GetVersion() { return nVersion; }
216 void ReadVersion() { *this >> nVersion; }
217 void WriteVersion() { *this << nVersion; }
219 CDataStream& read(char* pch, size_t nSize)
221 // Read from the beginning of the buffer
222 unsigned int nReadPosNext = nReadPos + nSize;
223 if (nReadPosNext >= vch.size())
225 if (nReadPosNext > vch.size())
227 throw std::ios_base::failure("CDataStream::read(): end of data");
229 memcpy(pch, &vch[nReadPos], nSize);
234 memcpy(pch, &vch[nReadPos], nSize);
235 nReadPos = nReadPosNext;
239 CDataStream& ignore(int nSize)
241 // Ignore from the beginning of the buffer
243 unsigned int nReadPosNext = nReadPos + nSize;
244 if (nReadPosNext >= vch.size())
246 if (nReadPosNext > vch.size())
247 throw std::ios_base::failure("CDataStream::ignore(): end of data");
252 nReadPos = nReadPosNext;
256 CDataStream& write(const char* pch, size_t nSize)
258 // Write to the end of the buffer
259 vch.insert(vch.end(), pch, pch + nSize);
263 template<typename Stream>
264 void Serialize(Stream& s, int nType, int nVersion) const
266 // Special case: stream << stream concatenates like stream += stream
268 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
272 unsigned int GetSerializeSize(const T& obj)
274 // Tells the size of the object if serialized to this stream
275 return ::GetSerializeSize(obj, nType, nVersion);
279 CDataStream& operator<<(const T& obj)
281 // Serialize to this stream
282 ::Serialize(*this, obj, nType, nVersion);
287 CDataStream& operator>>(T& obj)
289 // Unserialize from this stream
290 ::Unserialize(*this, obj, nType, nVersion);
294 void GetAndClear(CSerializeData &data) {
295 data.insert(data.end(), begin(), end());
309 /** Non-refcounted RAII wrapper for FILE*
311 * Will automatically close the file when it goes out of scope if not null.
312 * If you're returning the file pointer, return file.release().
313 * If you need to close the file early, use file.fclose() instead of fclose(file).
319 CAutoFile(const CAutoFile&);
320 CAutoFile& operator=(const CAutoFile&);
328 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
332 nVersion = nVersionIn;
348 /** Get wrapped FILE* with transfer of ownership.
349 * @note This will invalidate the CAutoFile object, and makes it the responsibility of the caller
350 * of this function to clean up the returned FILE*.
352 FILE* release() { FILE* ret = file; file = NULL; return ret; }
354 /** Get wrapped FILE* without transfer of ownership.
355 * @note Ownership of the FILE* will remain with this class. Use this only if the scope of the
356 * CAutoFile outlives use of the passed pointer.
358 FILE* Get() const { return file; }
360 /** Return true if the wrapped FILE* is NULL, false otherwise.
362 bool IsNull() const { return (file == NULL); }
367 void SetType(int n) { nType = n; }
368 int GetType() { return nType; }
369 void SetVersion(int n) { nVersion = n; }
370 int GetVersion() { return nVersion; }
371 void ReadVersion() { *this >> nVersion; }
372 void WriteVersion() { *this << nVersion; }
374 CAutoFile& read(char* pch, size_t nSize)
377 throw std::ios_base::failure("CAutoFile::read: file handle is NULL");
378 if (fread(pch, 1, nSize, file) != nSize)
379 throw std::ios_base::failure(feof(file) ? "CAutoFile::read: end of file" : "CAutoFile::read: fread failed");
383 CAutoFile& write(const char* pch, size_t nSize)
386 throw std::ios_base::failure("CAutoFile::write: file handle is NULL");
387 if (fwrite(pch, 1, nSize, file) != nSize)
388 throw std::ios_base::failure("CAutoFile::write: write failed");
393 unsigned int GetSerializeSize(const T& obj)
395 // Tells the size of the object if serialized to this stream
396 return ::GetSerializeSize(obj, nType, nVersion);
400 CAutoFile& operator<<(const T& obj)
402 // Serialize to this stream
404 throw std::ios_base::failure("CAutoFile::operator<<: file handle is NULL");
405 ::Serialize(*this, obj, nType, nVersion);
410 CAutoFile& operator>>(T& obj)
412 // Unserialize from this stream
414 throw std::ios_base::failure("CAutoFile::operator>>: file handle is NULL");
415 ::Unserialize(*this, obj, nType, nVersion);
420 /** Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to
421 * deserialize from. It guarantees the ability to rewind a given number of bytes.
423 * Will automatically close the file when it goes out of scope if not null.
424 * If you need to close the file early, use file.fclose() instead of fclose(file).
430 CBufferedFile(const CBufferedFile&);
431 CBufferedFile& operator=(const CBufferedFile&);
436 FILE *src; // source file
437 uint64_t nSrcPos; // how many bytes have been read from source
438 uint64_t nReadPos; // how many bytes have been read from this
439 uint64_t nReadLimit; // up to which position we're allowed to read
440 uint64_t nRewind; // how many bytes we guarantee to rewind
441 std::vector<char> vchBuf; // the buffer
444 // read data from the source to fill the buffer
446 unsigned int pos = nSrcPos % vchBuf.size();
447 unsigned int readNow = vchBuf.size() - pos;
448 unsigned int nAvail = vchBuf.size() - (nSrcPos - nReadPos) - nRewind;
449 if (nAvail < readNow)
453 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
455 throw std::ios_base::failure(feof(src) ? "CBufferedFile::Fill: end of file" : "CBufferedFile::Fill: fread failed");
463 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
464 nSrcPos(0), nReadPos(0), nReadLimit((uint64_t)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0)
468 nVersion = nVersionIn;
484 // check whether we're at the end of the source file
486 return nReadPos == nSrcPos && feof(src);
489 // read a number of bytes
490 CBufferedFile& read(char *pch, size_t nSize) {
491 if (nSize + nReadPos > nReadLimit)
492 throw std::ios_base::failure("Read attempted past buffer limit");
493 if (nSize + nRewind > vchBuf.size())
494 throw std::ios_base::failure("Read larger than buffer size");
496 if (nReadPos == nSrcPos)
498 unsigned int pos = nReadPos % vchBuf.size();
500 if (nNow + pos > vchBuf.size())
501 nNow = vchBuf.size() - pos;
502 if (nNow + nReadPos > nSrcPos)
503 nNow = nSrcPos - nReadPos;
504 memcpy(pch, &vchBuf[pos], nNow);
512 // return the current reading position
517 // rewind to a given reading position
518 bool SetPos(uint64_t nPos) {
520 if (nReadPos + nRewind < nSrcPos) {
521 nReadPos = nSrcPos - nRewind;
523 } else if (nReadPos > nSrcPos) {
531 bool Seek(uint64_t nPos) {
532 long nLongPos = nPos;
533 if (nPos != (uint64_t)nLongPos)
535 if (fseek(src, nLongPos, SEEK_SET))
537 nLongPos = ftell(src);
543 // prevent reading beyond a certain position
544 // no argument removes the limit
545 bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
553 CBufferedFile& operator>>(T& obj) {
554 // Unserialize from this stream
555 ::Unserialize(*this, obj, nType, nVersion);
559 // search for a given byte in the stream, and remain positioned on it
560 void FindByte(char ch) {
562 if (nReadPos == nSrcPos)
564 if (vchBuf[nReadPos % vchBuf.size()] == ch)
571 #endif // BITCOIN_STREAMS_H