~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/serialize/binlog_encoding.h

  • Committer: Brian Aker
  • Date: 2008-10-06 06:47:29 UTC
  • Revision ID: brian@tangent.org-20081006064729-2i9mhjkzyvow9xsm
RemoveĀ uint.

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