]> Git Repo - VerusCoin.git/blob - src/streams.h
Merge pull request #5675
[VerusCoin.git] / src / streams.h
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.
5
6 #ifndef BITCOIN_STREAMS_H
7 #define BITCOIN_STREAMS_H
8
9 #include "allocators.h"
10 #include "serialize.h"
11
12 #include <algorithm>
13 #include <assert.h>
14 #include <ios>
15 #include <limits>
16 #include <map>
17 #include <set>
18 #include <stdint.h>
19 #include <string>
20 #include <string.h>
21 #include <utility>
22 #include <vector>
23
24 /** Double ended buffer combining vector and stream-like interfaces.
25  *
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.
28  */
29 class CDataStream
30 {
31 protected:
32     typedef CSerializeData vector_type;
33     vector_type vch;
34     unsigned int nReadPos;
35 public:
36     int nType;
37     int nVersion;
38
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;
48
49     explicit CDataStream(int nTypeIn, int nVersionIn)
50     {
51         Init(nTypeIn, nVersionIn);
52     }
53
54     CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
55     {
56         Init(nTypeIn, nVersionIn);
57     }
58
59 #if !defined(_MSC_VER) || _MSC_VER >= 1300
60     CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
61     {
62         Init(nTypeIn, nVersionIn);
63     }
64 #endif
65
66     CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
67     {
68         Init(nTypeIn, nVersionIn);
69     }
70
71     CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
72     {
73         Init(nTypeIn, nVersionIn);
74     }
75
76     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
77     {
78         Init(nTypeIn, nVersionIn);
79     }
80
81     void Init(int nTypeIn, int nVersionIn)
82     {
83         nReadPos = 0;
84         nType = nTypeIn;
85         nVersion = nVersionIn;
86     }
87
88     CDataStream& operator+=(const CDataStream& b)
89     {
90         vch.insert(vch.end(), b.begin(), b.end());
91         return *this;
92     }
93
94     friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
95     {
96         CDataStream ret = a;
97         ret += b;
98         return (ret);
99     }
100
101     std::string str() const
102     {
103         return (std::string(begin(), end()));
104     }
105
106
107     //
108     // Vector subset
109     //
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); }
123
124     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
125     {
126         assert(last - first >= 0);
127         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
128         {
129             // special case for inserting at the front when there's room
130             nReadPos -= (last - first);
131             memcpy(&vch[nReadPos], &first[0], last - first);
132         }
133         else
134             vch.insert(it, first, last);
135     }
136
137 #if !defined(_MSC_VER) || _MSC_VER >= 1300
138     void insert(iterator it, const char* first, const char* last)
139     {
140         assert(last - first >= 0);
141         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
142         {
143             // special case for inserting at the front when there's room
144             nReadPos -= (last - first);
145             memcpy(&vch[nReadPos], &first[0], last - first);
146         }
147         else
148             vch.insert(it, first, last);
149     }
150 #endif
151
152     iterator erase(iterator it)
153     {
154         if (it == vch.begin() + nReadPos)
155         {
156             // special case for erasing from the front
157             if (++nReadPos >= vch.size())
158             {
159                 // whenever we reach the end, we take the opportunity to clear the buffer
160                 nReadPos = 0;
161                 return vch.erase(vch.begin(), vch.end());
162             }
163             return vch.begin() + nReadPos;
164         }
165         else
166             return vch.erase(it);
167     }
168
169     iterator erase(iterator first, iterator last)
170     {
171         if (first == vch.begin() + nReadPos)
172         {
173             // special case for erasing from the front
174             if (last == vch.end())
175             {
176                 nReadPos = 0;
177                 return vch.erase(vch.begin(), vch.end());
178             }
179             else
180             {
181                 nReadPos = (last - vch.begin());
182                 return last;
183             }
184         }
185         else
186             return vch.erase(first, last);
187     }
188
189     inline void Compact()
190     {
191         vch.erase(vch.begin(), vch.begin() + nReadPos);
192         nReadPos = 0;
193     }
194
195     bool Rewind(size_type n)
196     {
197         // Rewind by n characters if the buffer hasn't been compacted yet
198         if (n > nReadPos)
199             return false;
200         nReadPos -= n;
201         return true;
202     }
203
204
205     //
206     // Stream subset
207     //
208     bool eof() const             { return size() == 0; }
209     CDataStream* rdbuf()         { return this; }
210     int in_avail()               { return size(); }
211
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; }
218
219     CDataStream& read(char* pch, size_t nSize)
220     {
221         // Read from the beginning of the buffer
222         unsigned int nReadPosNext = nReadPos + nSize;
223         if (nReadPosNext >= vch.size())
224         {
225             if (nReadPosNext > vch.size())
226             {
227                 throw std::ios_base::failure("CDataStream::read(): end of data");
228             }
229             memcpy(pch, &vch[nReadPos], nSize);
230             nReadPos = 0;
231             vch.clear();
232             return (*this);
233         }
234         memcpy(pch, &vch[nReadPos], nSize);
235         nReadPos = nReadPosNext;
236         return (*this);
237     }
238
239     CDataStream& ignore(int nSize)
240     {
241         // Ignore from the beginning of the buffer
242         assert(nSize >= 0);
243         unsigned int nReadPosNext = nReadPos + nSize;
244         if (nReadPosNext >= vch.size())
245         {
246             if (nReadPosNext > vch.size())
247                 throw std::ios_base::failure("CDataStream::ignore(): end of data");
248             nReadPos = 0;
249             vch.clear();
250             return (*this);
251         }
252         nReadPos = nReadPosNext;
253         return (*this);
254     }
255
256     CDataStream& write(const char* pch, size_t nSize)
257     {
258         // Write to the end of the buffer
259         vch.insert(vch.end(), pch, pch + nSize);
260         return (*this);
261     }
262
263     template<typename Stream>
264     void Serialize(Stream& s, int nType, int nVersion) const
265     {
266         // Special case: stream << stream concatenates like stream += stream
267         if (!vch.empty())
268             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
269     }
270
271     template<typename T>
272     unsigned int GetSerializeSize(const T& obj)
273     {
274         // Tells the size of the object if serialized to this stream
275         return ::GetSerializeSize(obj, nType, nVersion);
276     }
277
278     template<typename T>
279     CDataStream& operator<<(const T& obj)
280     {
281         // Serialize to this stream
282         ::Serialize(*this, obj, nType, nVersion);
283         return (*this);
284     }
285
286     template<typename T>
287     CDataStream& operator>>(T& obj)
288     {
289         // Unserialize from this stream
290         ::Unserialize(*this, obj, nType, nVersion);
291         return (*this);
292     }
293
294     void GetAndClear(CSerializeData &data) {
295         data.insert(data.end(), begin(), end());
296         clear();
297     }
298 };
299
300
301
302
303
304
305
306
307
308
309 /** Non-refcounted RAII wrapper for FILE*
310  *
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).
314  */
315 class CAutoFile
316 {
317 private:
318     // Disallow copies
319     CAutoFile(const CAutoFile&);
320     CAutoFile& operator=(const CAutoFile&);
321
322     int nType;
323     int nVersion;
324         
325     FILE* file; 
326
327 public:
328     CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
329     {
330         file = filenew;
331         nType = nTypeIn;
332         nVersion = nVersionIn;
333     }
334
335     ~CAutoFile()
336     {
337         fclose();
338     }
339
340     void fclose()
341     {
342         if (file) {
343             ::fclose(file);
344             file = NULL;
345         }
346     }
347
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*.
351      */
352     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
353
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.
357      */
358     FILE* Get() const           { return file; }
359
360     /** Return true if the wrapped FILE* is NULL, false otherwise.
361      */
362     bool IsNull() const         { return (file == NULL); }
363
364     //
365     // Stream subset
366     //
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; }
373
374     CAutoFile& read(char* pch, size_t nSize)
375     {
376         if (!file)
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");
380         return (*this);
381     }
382
383     CAutoFile& write(const char* pch, size_t nSize)
384     {
385         if (!file)
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");
389         return (*this);
390     }
391
392     template<typename T>
393     unsigned int GetSerializeSize(const T& obj)
394     {
395         // Tells the size of the object if serialized to this stream
396         return ::GetSerializeSize(obj, nType, nVersion);
397     }
398
399     template<typename T>
400     CAutoFile& operator<<(const T& obj)
401     {
402         // Serialize to this stream
403         if (!file)
404             throw std::ios_base::failure("CAutoFile::operator<<: file handle is NULL");
405         ::Serialize(*this, obj, nType, nVersion);
406         return (*this);
407     }
408
409     template<typename T>
410     CAutoFile& operator>>(T& obj)
411     {
412         // Unserialize from this stream
413         if (!file)
414             throw std::ios_base::failure("CAutoFile::operator>>: file handle is NULL");
415         ::Unserialize(*this, obj, nType, nVersion);
416         return (*this);
417     }
418 };
419
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.
422  *
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).
425  */
426 class CBufferedFile
427 {
428 private:
429     // Disallow copies
430     CBufferedFile(const CBufferedFile&);
431     CBufferedFile& operator=(const CBufferedFile&);
432
433     int nType;
434     int nVersion;
435
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
442
443 protected:
444     // read data from the source to fill the buffer
445     bool Fill() {
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)
450             readNow = nAvail;
451         if (readNow == 0)
452             return false;
453         size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
454         if (read == 0) {
455             throw std::ios_base::failure(feof(src) ? "CBufferedFile::Fill: end of file" : "CBufferedFile::Fill: fread failed");
456         } else {
457             nSrcPos += read;
458             return true;
459         }
460     }
461
462 public:
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)
465     {
466         src = fileIn;
467         nType = nTypeIn;
468         nVersion = nVersionIn;
469     }
470
471     ~CBufferedFile()
472     {
473         fclose();
474     }
475
476     void fclose()
477     {
478         if (src) {
479             ::fclose(src);
480             src = NULL;
481         }
482     }
483
484     // check whether we're at the end of the source file
485     bool eof() const {
486         return nReadPos == nSrcPos && feof(src);
487     }
488
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");
495         while (nSize > 0) {
496             if (nReadPos == nSrcPos)
497                 Fill();
498             unsigned int pos = nReadPos % vchBuf.size();
499             size_t nNow = nSize;
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);
505             nReadPos += nNow;
506             pch += nNow;
507             nSize -= nNow;
508         }
509         return (*this);
510     }
511
512     // return the current reading position
513     uint64_t GetPos() {
514         return nReadPos;
515     }
516
517     // rewind to a given reading position
518     bool SetPos(uint64_t nPos) {
519         nReadPos = nPos;
520         if (nReadPos + nRewind < nSrcPos) {
521             nReadPos = nSrcPos - nRewind;
522             return false;
523         } else if (nReadPos > nSrcPos) {
524             nReadPos = nSrcPos;
525             return false;
526         } else {
527             return true;
528         }
529     }
530
531     bool Seek(uint64_t nPos) {
532         long nLongPos = nPos;
533         if (nPos != (uint64_t)nLongPos)
534             return false;
535         if (fseek(src, nLongPos, SEEK_SET))
536             return false;
537         nLongPos = ftell(src);
538         nSrcPos = nLongPos;
539         nReadPos = nLongPos;
540         return true;
541     }
542
543     // prevent reading beyond a certain position
544     // no argument removes the limit
545     bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
546         if (nPos < nReadPos)
547             return false;
548         nReadLimit = nPos;
549         return true;
550     }
551
552     template<typename T>
553     CBufferedFile& operator>>(T& obj) {
554         // Unserialize from this stream
555         ::Unserialize(*this, obj, nType, nVersion);
556         return (*this);
557     }
558
559     // search for a given byte in the stream, and remain positioned on it
560     void FindByte(char ch) {
561         while (true) {
562             if (nReadPos == nSrcPos)
563                 Fill();
564             if (vchBuf[nReadPos % vchBuf.size()] == ch)
565                 break;
566             nReadPos++;
567         }
568     }
569 };
570
571 #endif // BITCOIN_STREAMS_H
This page took 0.055027 seconds and 4 git commands to generate.