~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/serialize/binlog_encoding.h

  • Committer: Monty Taylor
  • Date: 2008-11-07 00:15:51 UTC
  • mto: This revision was merged to the branch mainline in revision 579.
  • Revision ID: monty@inaugust.com-20081107001551-8vxb6sf1ti0i5p09
Cleaned up some headers for PCH.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#ifndef BINLOG_ENCODE_H_INCLUDED
 
2
#define BINLOG_ENCODE_H_INCLUDED
 
3
 
 
4
#include <cstdlib>
 
5
#include <cassert>
 
6
#include <cstring>
 
7
#include CSTDINT_H
 
8
 
 
9
#define LENGTH_ENCODE_MAX_BYTES (sizeof(size_t) + 1)
 
10
 
 
11
using std::size_t;
 
12
 
 
13
inline unsigned char *
 
14
length_encode(std::size_t length, unsigned char *buf)
 
15
{
 
16
  unsigned char *ptr= buf;
 
17
  assert(length > 1);
 
18
  if (length < 256)
 
19
    *ptr++= length & 0xFF;
 
20
  else {
 
21
    int_fast8_t log2m1= -1;        // ceil(log2(ptr - buf)) - 1
 
22
    uint_fast8_t pow2= 1;          // pow2(log2m1 + 1)
 
23
    while (length > 0) {
 
24
      // Check the invariants
 
25
      assert(pow2 == (1 << (log2m1 + 1)));
 
26
      assert((ptr - buf) <= (1 << (log2m1 + 1)));
 
27
 
 
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;
 
32
      length >>= 8;
 
33
 
 
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) {
 
38
        ++log2m1;
 
39
        pow2 <<= 1;
 
40
      }
 
41
    }
 
42
    // Clear the remaining bytes up to the next power of two
 
43
    std::memset(ptr + 1, 0, pow2 - (ptr - buf));
 
44
    *buf= log2m1;
 
45
    ptr= buf + pow2 + 1;
 
46
  }
 
47
  return ptr;
 
48
}
 
49
 
 
50
inline unsigned char *
 
51
length_decode(unsigned char *buf, size_t *plen)
 
52
{
 
53
  if (*buf > 1) {
 
54
    *plen = *buf;
 
55
    return buf + 1;
 
56
  }
 
57
 
 
58
  size_t bytes= 1 << (*buf + 1);
 
59
  unsigned char *ptr= buf + 1;
 
60
  size_t length= 0;
 
61
  for (unsigned int i = 0 ; i < bytes ; ++i)
 
62
    length |= *ptr++ << (8 * i);
 
63
  *plen= length;
 
64
  return ptr;
 
65
}
 
66
 
 
67
/**
 
68
   Compute how many bytes are use for the length.
 
69
 
 
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
 
73
   computed.
 
74
 
 
75
 */
 
76
inline size_t
 
77
length_decode_bytes(int peek)
 
78
{
 
79
  return (peek < 2) ? (1 << (peek + 1)) + 1 : 1;
 
80
}
 
81
 
 
82
#endif /* BINLOG_ENCODE_H_INCLUDED */