1 #include "ReadVarint.h"
6 // 'varint' is a way to encode integer in a variable number of byte. Using for serializing for example.
7 // Partial implementation of https://developers.google.com/protocol-buffers/docs/encoding
11 void readUInt(const uint8_t*& p
, uint32_t res
, uint32_t& result
)
13 for (uint32_t i
= 2; i
< 5; i
++)
15 uint32_t byte
= static_cast<uint8_t>(p
[i
]);
16 res
+= (byte
- 1) << (7 * i
);
25 for (uint32_t i
= 5; i
< 10; i
++)
27 uint32_t byte
= static_cast<uint8_t>(p
[i
]);
39 void readUInt(const uint8_t*& p
, uint32_t res32
, uint64_t& result
)
42 for (uint32_t i
= 2; i
< 10; i
++)
44 uint64_t byte
= static_cast<uint8_t>(p
[i
]);
45 res
+= (byte
- 1) << (7 * i
);
58 T
readUInt(const uint8_t*& p
)
60 p
+= 1; // Skip the first byte (type + field n°)
70 res
+= (byte
- 1) << 7;
78 readUInt(p
, res
, result
);
83 void ReadVarint::tests()
85 const uint8_t bytes
[] = {
86 0x08, 0x03, // v1 = 3.
87 0x10, 0xdf, 0xd0, 0x03, // v2 = 59487.
89 0x1a, 0x0a, // v3 = 10.
91 0x20, 0xb7, 0xac, 0xe5, 0x85, 0x08, 0x28, // v4 = 2159629879
93 0xb4, 0xdb, 0x9b, 0xf0, 0xe6, 0x97, 0xb8, 0xc1, 0x59, 0x38 // v5 = 6449964724842327476
96 const uint8_t* p
= bytes
; // Pointer on const bytes.
98 auto v1
= readUInt
<uint32_t>(p
);
99 auto v2
= readUInt
<uint32_t>(p
);
100 auto v3
= readUInt
<uint32_t>(p
);
101 auto v4
= readUInt
<uint64_t>(p
);
102 auto v5
= readUInt
<uint64_t>(p
);
104 cout
<< "p = " << hex
<< (int)(*p
) << dec
<< endl
;
106 cout
<< "v1 = " << v1
<< ", v2 = " << v2
<< ", v3 = " << v3
<< ", v4 = " << v4
<< ", v5 = " << v5
<< endl
;