mySQL 5.0.11 sources for tomato
[tomato.git] / release / src / router / mysql / mysys / my_vle.c
blob2e1e4b69dab5c9f74f5e78a3a77bc0da16c245b1
1 /* Copyright (c) 2005-2007 MySQL AB
3 This program is free software; you can redistribute it and/or
4 modify it under the terms of the GNU General Public License as
5 published by the Free Software Foundation; version 2 of the License.
7 This program is distributed in the hope that it will be useful, but
8 WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 General Public License for more details.
12 You should have received a copy of the GNU General Public License
13 along with this program; if not, write to the Free Software
14 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
17 Variable length encoding.
19 A method to store an arbitrary-size non-negative integer. We let the
20 most significant bit of the number indicate that the next byte
21 should be contatenated to form the real number.
24 #include "my_vle.h"
27 Function to encode an unsigned long as VLE. The bytes for the VLE
28 will be written to the location pointed to by 'out'. The maximum
29 number of bytes written will be 'max'.
31 PARAMETERS
33 out Pointer to beginning of where to store VLE bytes.
34 max Maximum number of bytes to write.
35 n Number to encode.
37 RETURN VALUE
38 On success, one past the end of the array containing the VLE
39 bytes. On failure, the 'out' pointer is returned.
42 uchar*
43 my_vle_encode(uchar* out, size_t max, ulong n)
45 uchar buf[my_vle_sizeof(n)];
46 uchar *ptr= buf;
47 size_t len;
51 *ptr++= (uchar) (n & 0x7F);
52 n>>= 7;
54 while (n > 0);
56 len= ptr - buf;
58 if (len <= max)
61 The bytes are stored in reverse order in 'buf'. Let's write them
62 in correct order to the output buffer and set the MSB at the
63 same time.
65 while (ptr-- > buf)
67 uchar v= *ptr;
68 if (ptr > buf)
69 v|= 0x80;
70 *out++= v;
74 return out;
78 Function to decode a VLE representation of an integral value.
81 PARAMETERS
83 result_ptr Pointer to an unsigned long where the value will be written.
84 vle Pointer to the VLE bytes.
86 RETURN VALUE
88 One-past the end of the VLE bytes. The routine will never read
89 more than sizeof(*result_ptr) + 1 bytes.
92 uchar const*
93 my_vle_decode(ulong *result_ptr, uchar const *vle)
95 ulong result= 0;
96 size_t cnt= 1;
100 result<<= 7;
101 result|= (*vle & 0x7F);
103 while ((*vle++ & 0x80) && ++cnt <= sizeof(*result_ptr) + 1);
105 if (cnt <= sizeof(*result_ptr) + 1)
106 *result_ptr= result;
108 return vle;