1
#ifndef BINLOG_ENCODE_H_INCLUDED
2
#define BINLOG_ENCODE_H_INCLUDED
9
#define LENGTH_ENCODE_MAX_BYTES (sizeof(size_t) + 1)
13
inline unsigned char *
14
length_encode(std::size_t length, unsigned char *buf)
16
unsigned char *ptr= buf;
19
*ptr++= length & 0xFF;
21
int_fast8_t log2m1= -1; // ceil(log2(ptr - buf)) - 1
22
uint_fast8_t pow2= 1; // pow2(log2m1 + 1)
24
// Check the invariants
25
assert(pow2 == (1 << (log2m1 + 1)));
26
assert((ptr - buf) <= (1 << (log2m1 + 1)));
28
// Write the least significant byte of the current
29
// length. Prefix increment is used to make space for the first
30
// byte that will hold log2m1.
31
*++ptr= length & 0xFF;
34
// Ensure the invariant holds by correcting it if it doesn't,
35
// that is, the number of bytes written is greater than the
36
// nearest power of two.
37
if (ptr - buf > pow2) {
42
// Clear the remaining bytes up to the next power of two
43
std::memset(ptr + 1, 0, pow2 - (ptr - buf));
50
inline unsigned char *
51
length_decode(unsigned char *buf, size_t *plen)
58
size_t bytes= 1 << (*buf + 1);
59
unsigned char *ptr= buf + 1;
61
for (unsigned int i = 0 ; i < bytes ; ++i)
62
length |= *ptr++ << (8 * i);
68
Compute how many bytes are use for the length.
70
The number of bytes that make up th length can be computed based on
71
the first byte of the length field. By supplying this byte to the
72
function, the number of bytes that is needed for the length is
77
length_decode_bytes(int peek)
79
return (peek < 2) ? (1 << (peek + 1)) + 1 : 1;
82
#endif /* BINLOG_ENCODE_H_INCLUDED */