Update CMakeLists.txt - play with openssl
[novacoin.git] / src / streams.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 The Bitcoin developers
3 // Distributed under the MIT/X11 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 <ios>
14 #include <utility>
15
16 /** Double ended buffer combining vector and stream-like interfaces.
17  *
18  * >> and << read and write unformatted data using the above serialization templates.
19  * Fills with data in linear time; some stringstream implementations take N^2 time.
20  */
21 class CDataStream
22 {
23 protected:
24     typedef CSerializeData vector_type;
25     vector_type vch;
26     unsigned int nReadPos;
27     short state;
28     short exceptmask;
29 public:
30     int nType;
31     int nVersion;
32
33     typedef vector_type::allocator_type   allocator_type;
34     typedef vector_type::size_type        size_type;
35     typedef vector_type::difference_type  difference_type;
36     typedef vector_type::reference        reference;
37     typedef vector_type::const_reference  const_reference;
38     typedef vector_type::value_type       value_type;
39     typedef vector_type::iterator         iterator;
40     typedef vector_type::const_iterator   const_iterator;
41     typedef vector_type::reverse_iterator reverse_iterator;
42
43     explicit CDataStream(int nTypeIn, int nVersionIn);
44
45     CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn);
46     CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn);
47     CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn);
48     CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn);
49     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn);
50
51     void Init(int nTypeIn, int nVersionIn);
52
53     CDataStream& operator+=(const CDataStream& b);
54
55     friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
56     {
57         CDataStream ret = a;
58         ret += b;
59         return (ret);
60     }
61
62     std::string str() const;
63
64     //
65     // Vector subset
66     //
67     const_iterator begin() const                     { return vch.begin() + nReadPos; }
68     iterator begin()                                 { return vch.begin() + nReadPos; }
69     const_iterator end() const                       { return vch.end(); }
70     iterator end()                                   { return vch.end(); }
71     size_type size() const                           { return vch.size() - nReadPos; }
72     bool empty() const                               { return vch.size() == nReadPos; }
73     void resize(size_type n, value_type c=0)         { vch.resize(n + nReadPos, c); }
74     void reserve(size_type n)                        { vch.reserve(n + nReadPos); }
75     const_reference operator[](size_type pos) const  { return vch[pos + nReadPos]; }
76     reference operator[](size_type pos)              { return vch[pos + nReadPos]; }
77     void clear()                                     { vch.clear(); nReadPos = 0; }
78     iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
79     void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
80
81     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
82     {
83         assert(last - first >= 0);
84         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
85         {
86             // special case for inserting at the front when there's room
87             nReadPos -= (last - first);
88             memcpy(&vch[nReadPos], &first[0], last - first);
89         }
90         else
91             vch.insert(it, first, last);
92     }
93
94     void insert(iterator it, const char* first, const char* last)
95     {
96         assert(last - first >= 0);
97         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
98         {
99             // special case for inserting at the front when there's room
100             nReadPos -= (unsigned int)(last - first);
101             memcpy(&vch[nReadPos], &first[0], last - first);
102         }
103         else
104             vch.insert(it, first, last);
105     }
106
107     iterator erase(iterator it)
108     {
109         if (it == vch.begin() + nReadPos)
110         {
111             // special case for erasing from the front
112             if (++nReadPos >= vch.size())
113             {
114                 // whenever we reach the end, we take the opportunity to clear the buffer
115                 nReadPos = 0;
116                 return vch.erase(vch.begin(), vch.end());
117             }
118             return vch.begin() + nReadPos;
119         }
120         else
121             return vch.erase(it);
122     }
123
124     iterator erase(iterator first, iterator last)
125     {
126         if (first == vch.begin() + nReadPos)
127         {
128             // special case for erasing from the front
129             if (last == vch.end())
130             {
131                 nReadPos = 0;
132                 return vch.erase(vch.begin(), vch.end());
133             }
134             else
135             {
136                 nReadPos = (unsigned int)(last - vch.begin());
137                 return last;
138             }
139         }
140         else
141             return vch.erase(first, last);
142     }
143
144     inline void Compact()
145     {
146         vch.erase(vch.begin(), vch.begin() + nReadPos);
147         nReadPos = 0;
148     }
149
150     bool Rewind(size_type n);
151
152     //
153     // Stream subset
154     //
155     void setstate(short bits, const char* psz);
156
157     bool eof() const             { return size() == 0; }
158     bool fail() const            { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
159     bool good() const            { return !eof() && (state == 0); }
160     void clear(short n)          { state = n; }  // name conflict with vector clear()
161     short exceptions()           { return exceptmask; }
162     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
163     CDataStream* rdbuf()         { return this; }
164     int in_avail()               { return (int)(size()); }
165
166     void SetType(int n)          { nType = n; }
167     int GetType()                { return nType; }
168     void SetVersion(int n)       { nVersion = n; }
169     int GetVersion()             { return nVersion; }
170     void ReadVersion()           { *this >> nVersion; }
171     void WriteVersion()          { *this << nVersion; }
172
173     CDataStream& read(char* pch, int nSize);
174     CDataStream& ignore(int nSize);
175     CDataStream& write(const char* pch, int nSize);
176
177     template<typename Stream>
178     void Serialize(Stream& s, int nType, int nVersion) const
179     {
180         // Special case: stream << stream concatenates like stream += stream
181         if (!vch.empty())
182             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
183     }
184
185     template<typename T>
186     unsigned int GetSerializeSize(const T& obj)
187     {
188         // Tells the size of the object if serialized to this stream
189         return ::GetSerializeSize(obj, nType, nVersion);
190     }
191
192     template<typename T>
193     CDataStream& operator<<(const T& obj)
194     {
195         // Serialize to this stream
196         ::Serialize(*this, obj, nType, nVersion);
197         return (*this);
198     }
199
200     template<typename T>
201     CDataStream& operator>>(T& obj)
202     {
203         // Unserialize from this stream
204         ::Unserialize(*this, obj, nType, nVersion);
205         return (*this);
206     }
207
208     void GetAndClear(CSerializeData &data);
209 };
210
211
212 /** RAII wrapper for FILE*.
213  *
214  * Will automatically close the file when it goes out of scope if not null.
215  * If you're returning the file pointer, return file.release().
216  * If you need to close the file early, use file.fclose() instead of fclose(file).
217  */
218 class CAutoFile
219 {
220 protected:
221     FILE* file;
222     short state;
223     short exceptmask;
224 public:
225     int nType;
226     int nVersion;
227
228     CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn);
229     ~CAutoFile();
230     void fclose();
231
232     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
233     operator FILE*()            { return file; }
234     FILE* operator->()          { return file; }
235     FILE& operator*()           { return *file; }
236     FILE** operator&()          { return &file; }
237     FILE* operator=(FILE* pnew) { return file = pnew; }
238     bool operator!()            { return (file == NULL); }
239
240
241     //
242     // Stream subset
243     //
244     void setstate(short bits, const char* psz);
245     bool fail() const            { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
246     bool good() const            { return state == 0; }
247     void clear(short n = 0)      { state = n; }
248     short exceptions()           { return exceptmask; }
249     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
250
251     void SetType(int n)          { nType = n; }
252     int GetType()                { return nType; }
253     void SetVersion(int n)       { nVersion = n; }
254     int GetVersion()             { return nVersion; }
255     void ReadVersion()           { *this >> nVersion; }
256     void WriteVersion()          { *this << nVersion; }
257
258     CAutoFile& read(char* pch, size_t nSize);
259     CAutoFile& write(const char* pch, size_t nSize);
260
261     template<typename T>
262     unsigned int GetSerializeSize(const T& obj)
263     {
264         // Tells the size of the object if serialized to this stream
265         return ::GetSerializeSize(obj, nType, nVersion);
266     }
267
268     template<typename T>
269     CAutoFile& operator<<(const T& obj)
270     {
271         // Serialize to this stream
272         if (!file)
273             throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
274         ::Serialize(*this, obj, nType, nVersion);
275         return (*this);
276     }
277
278     template<typename T>
279     CAutoFile& operator>>(T& obj)
280     {
281         // Unserialize from this stream
282         if (!file)
283             throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
284         ::Unserialize(*this, obj, nType, nVersion);
285         return (*this);
286     }
287 };
288
289 /** Wrapper around a FILE* that implements a ring buffer to
290  *  deserialize from. It guarantees the ability to rewind
291  *  a given number of bytes. */
292 class CBufferedFile
293 {
294 private:
295     FILE *src;          // source file
296     uint64_t nSrcPos;     // how many bytes have been read from source
297     uint64_t nReadPos;    // how many bytes have been read from this
298     uint64_t nReadLimit;  // up to which position we're allowed to read
299     uint64_t nRewind;     // how many bytes we guarantee to rewind
300     std::vector<char> vchBuf; // the buffer
301
302     short state;
303     short exceptmask;
304
305 protected:
306     void setstate(short bits, const char *psz);
307
308     // read data from the source to fill the buffer
309     bool Fill();
310
311 public:
312     int nType;
313     int nVersion;
314
315     CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
316         src(fileIn), nSrcPos(0), nReadPos(0), nReadLimit(std::numeric_limits<uint64_t>::max()), nRewind(nRewindIn), vchBuf(nBufSize, 0),
317         state(0), exceptmask(std::ios_base::badbit | std::ios_base::failbit), nType(nTypeIn), nVersion(nVersionIn) {
318     }
319
320     // check whether no error occurred
321     bool good() const {
322         return state == 0;
323     }
324
325     // check whether we're at the end of the source file
326     bool eof() const {
327         return nReadPos == nSrcPos && feof(src);
328     }
329
330     // read a number of bytes
331     CBufferedFile& read(char *pch, size_t nSize);
332
333     // return the current reading position
334     uint64_t GetPos() {
335         return nReadPos;
336     }
337
338     // rewind to a given reading position
339     bool SetPos(uint64_t nPos);
340     bool Seek(uint64_t nPos);
341
342     // prevent reading beyond a certain position
343     // no argument removes the limit
344     bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max());
345
346     template<typename T>
347     CBufferedFile& operator>>(T& obj) {
348         // Unserialize from this stream
349         ::Unserialize(*this, obj, nType, nVersion);
350         return (*this);
351     }
352
353     // search for a given byte in the stream, and remain positioned on it
354     void FindByte(char ch);
355 };
356
357 #endif // BITCOIN_STREAMS_H