Move WriteCompactSize and ReadCompactSize to serialize.cpp
[novacoin.git] / src / serialize.cpp
1 #include "serialize.h"
2 #include "hash.h"
3
4 template<typename Stream>
5 void WriteCompactSize(Stream& os, uint64_t nSize)
6 {
7     if (nSize < 253)
8     {
9         unsigned char chSize = (unsigned char)nSize;
10         WRITEDATA(os, chSize);
11     }
12     else if (nSize <= std::numeric_limits<unsigned short>::max())
13     {
14         unsigned char chSize = 253;
15         unsigned short xSize = (unsigned short)nSize;
16         WRITEDATA(os, chSize);
17         WRITEDATA(os, xSize);
18     }
19     else if (nSize <= std::numeric_limits<unsigned int>::max())
20     {
21         unsigned char chSize = 254;
22         unsigned int xSize = (unsigned int)nSize;
23         WRITEDATA(os, chSize);
24         WRITEDATA(os, xSize);
25     }
26     else
27     {
28         unsigned char chSize = 255;
29         uint64_t xSize = nSize;
30         WRITEDATA(os, chSize);
31         WRITEDATA(os, xSize);
32     }
33     return;
34 }
35
36
37 template<typename Stream>
38 uint64_t ReadCompactSize(Stream& is)
39 {
40     unsigned char chSize;
41     READDATA(is, chSize);
42     uint64_t nSizeRet = 0;
43     if (chSize < 253)
44     {
45         nSizeRet = chSize;
46     }
47     else if (chSize == 253)
48     {
49         unsigned short xSize;
50         READDATA(is, xSize);
51         nSizeRet = xSize;
52     }
53     else if (chSize == 254)
54     {
55         unsigned int xSize;
56         READDATA(is, xSize);
57         nSizeRet = xSize;
58     }
59     else
60     {
61         uint64_t xSize;
62         READDATA(is, xSize);
63         nSizeRet = xSize;
64     }
65     if (nSizeRet > (uint64_t)MAX_SIZE)
66         throw std::ios_base::failure("ReadCompactSize() : size too large");
67     return nSizeRet;
68 }
69
70
71
72 // Template instantiation
73
74 template void WriteCompactSize<CAutoFile>(CAutoFile&, uint64_t);
75 template void WriteCompactSize<CDataStream>(CDataStream&, uint64_t);
76 template void WriteCompactSize<CHashWriter>(CHashWriter&, uint64_t);
77
78 template uint64_t ReadCompactSize<CAutoFile>(CAutoFile&);
79 template uint64_t ReadCompactSize<CDataStream>(CDataStream&);