1
#ifndef BINLOG_ENCODE_H_INCLUDED
2
#define BINLOG_ENCODE_H_INCLUDED
9
#define LENGTH_ENCODE_MAX_BYTES (sizeof(size_t) + 1)
11
inline unsigned char *
12
length_encode(size_t length, unsigned char *buf)
14
unsigned char *ptr= buf;
17
*ptr++= length & 0xFF;
19
int_fast8_t log2m1= -1; // ceil(log2(ptr - buf)) - 1
20
uint_fast8_t pow2= 1; // pow2(log2m1 + 1)
22
// Check the invariants
23
assert(pow2 == (1 << (log2m1 + 1)));
24
assert((ptr - buf) <= (1 << (log2m1 + 1)));
26
// Write the least significant byte of the current
27
// length. Prefix increment is used to make space for the first
28
// byte that will hold log2m1.
29
*++ptr= length & 0xFF;
32
// Ensure the invariant holds by correcting it if it doesn't,
33
// that is, the number of bytes written is greater than the
34
// nearest power of two.
35
if (ptr - buf > pow2) {
40
// Clear the remaining bytes up to the next power of two
41
memset(ptr + 1, 0, pow2 - (ptr - buf));
48
inline unsigned char *
49
length_decode(unsigned char *buf, size_t *plen)
56
size_t bytes= 1 << (*buf + 1);
57
unsigned char *ptr= buf + 1;
59
for (unsigned int i = 0 ; i < bytes ; ++i)
60
length |= *ptr++ << (8 * i);
66
Compute how many bytes are use for the length.
68
The number of bytes that make up th length can be computed based on
69
the first byte of the length field. By supplying this byte to the
70
function, the number of bytes that is needed for the length is
75
length_decode_bytes(int peek)
77
return (peek < 2) ? (1 << (peek + 1)) + 1 : 1;
80
#endif /* BINLOG_ENCODE_H_INCLUDED */