xref: /illumos-gate/usr/src/lib/libsqlite/src/encode.c (revision c5c4113d)
1 
2 #pragma ident	"%Z%%M%	%I%	%E% SMI"
3 
4 /*
5 ** 2002 April 25
6 **
7 ** The author disclaims copyright to this source code.  In place of
8 ** a legal notice, here is a blessing:
9 **
10 **    May you do good and not evil.
11 **    May you find forgiveness for yourself and forgive others.
12 **    May you share freely, never taking more than you give.
13 **
14 *************************************************************************
15 ** This file contains helper routines used to translate binary data into
16 ** a null-terminated string (suitable for use in SQLite) and back again.
17 ** These are convenience routines for use by people who want to store binary
18 ** data in an SQLite database.  The code in this file is not used by any other
19 ** part of the SQLite library.
20 **
21 ** $Id: encode.c,v 1.12 2004/03/17 18:44:46 drh Exp $
22 */
23 #include <string.h>
24 #include <assert.h>
25 
26 /*
27 ** How This Encoder Works
28 **
29 ** The output is allowed to contain any character except 0x27 (') and
30 ** 0x00.  This is accomplished by using an escape character to encode
31 ** 0x27 and 0x00 as a two-byte sequence.  The escape character is always
32 ** 0x01.  An 0x00 is encoded as the two byte sequence 0x01 0x01.  The
33 ** 0x27 character is encoded as the two byte sequence 0x01 0x28.  Finally,
34 ** the escape character itself is encoded as the two-character sequence
35 ** 0x01 0x02.
36 **
37 ** To summarize, the encoder works by using an escape sequences as follows:
38 **
39 **       0x00  ->  0x01 0x01
40 **       0x01  ->  0x01 0x02
41 **       0x27  ->  0x01 0x28
42 **
43 ** If that were all the encoder did, it would work, but in certain cases
44 ** it could double the size of the encoded string.  For example, to
45 ** encode a string of 100 0x27 characters would require 100 instances of
46 ** the 0x01 0x03 escape sequence resulting in a 200-character output.
47 ** We would prefer to keep the size of the encoded string smaller than
48 ** this.
49 **
50 ** To minimize the encoding size, we first add a fixed offset value to each
51 ** byte in the sequence.  The addition is modulo 256.  (That is to say, if
52 ** the sum of the original character value and the offset exceeds 256, then
53 ** the higher order bits are truncated.)  The offset is chosen to minimize
54 ** the number of characters in the string that need to be escaped.  For
55 ** example, in the case above where the string was composed of 100 0x27
56 ** characters, the offset might be 0x01.  Each of the 0x27 characters would
57 ** then be converted into an 0x28 character which would not need to be
58 ** escaped at all and so the 100 character input string would be converted
59 ** into just 100 characters of output.  Actually 101 characters of output -
60 ** we have to record the offset used as the first byte in the sequence so
61 ** that the string can be decoded.  Since the offset value is stored as
62 ** part of the output string and the output string is not allowed to contain
63 ** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
64 **
65 ** Here, then, are the encoding steps:
66 **
67 **     (1)   Choose an offset value and make it the first character of
68 **           output.
69 **
70 **     (2)   Copy each input character into the output buffer, one by
71 **           one, adding the offset value as you copy.
72 **
73 **     (3)   If the value of an input character plus offset is 0x00, replace
74 **           that one character by the two-character sequence 0x01 0x01.
75 **           If the sum is 0x01, replace it with 0x01 0x02.  If the sum
76 **           is 0x27, replace it with 0x01 0x03.
77 **
78 **     (4)   Put a 0x00 terminator at the end of the output.
79 **
80 ** Decoding is obvious:
81 **
82 **     (5)   Copy encoded characters except the first into the decode
83 **           buffer.  Set the first encoded character aside for use as
84 **           the offset in step 7 below.
85 **
86 **     (6)   Convert each 0x01 0x01 sequence into a single character 0x00.
87 **           Convert 0x01 0x02 into 0x01.  Convert 0x01 0x28 into 0x27.
88 **
89 **     (7)   Subtract the offset value that was the first character of
90 **           the encoded buffer from all characters in the output buffer.
91 **
92 ** The only tricky part is step (1) - how to compute an offset value to
93 ** minimize the size of the output buffer.  This is accomplished by testing
94 ** all offset values and picking the one that results in the fewest number
95 ** of escapes.  To do that, we first scan the entire input and count the
96 ** number of occurances of each character value in the input.  Suppose
97 ** the number of 0x00 characters is N(0), the number of occurances of 0x01
98 ** is N(1), and so forth up to the number of occurances of 0xff is N(255).
99 ** An offset of 0 is not allowed so we don't have to test it.  The number
100 ** of escapes required for an offset of 1 is N(1)+N(2)+N(40).  The number
101 ** of escapes required for an offset of 2 is N(2)+N(3)+N(41).  And so forth.
102 ** In this way we find the offset that gives the minimum number of escapes,
103 ** and thus minimizes the length of the output string.
104 */
105 
106 /*
107 ** Encode a binary buffer "in" of size n bytes so that it contains
108 ** no instances of characters '\'' or '\000'.  The output is
109 ** null-terminated and can be used as a string value in an INSERT
110 ** or UPDATE statement.  Use sqlite_decode_binary() to convert the
111 ** string back into its original binary.
112 **
113 ** The result is written into a preallocated output buffer "out".
114 ** "out" must be able to hold at least 2 +(257*n)/254 bytes.
115 ** In other words, the output will be expanded by as much as 3
116 ** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
117 ** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
118 **
119 ** The return value is the number of characters in the encoded
120 ** string, excluding the "\000" terminator.
121 **
122 ** If out==NULL then no output is generated but the routine still returns
123 ** the number of characters that would have been generated if out had
124 ** not been NULL.
125 */
sqlite_encode_binary(const unsigned char * in,int n,unsigned char * out)126 int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out){
127   int i, j, e, m;
128   unsigned char x;
129   int cnt[256];
130   if( n<=0 ){
131     if( out ){
132       out[0] = 'x';
133       out[1] = 0;
134     }
135     return 1;
136   }
137   memset(cnt, 0, sizeof(cnt));
138   for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
139   m = n;
140   for(i=1; i<256; i++){
141     int sum;
142     if( i=='\'' ) continue;
143     sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
144     if( sum<m ){
145       m = sum;
146       e = i;
147       if( m==0 ) break;
148     }
149   }
150   if( out==0 ){
151     return n+m+1;
152   }
153   out[0] = e;
154   j = 1;
155   for(i=0; i<n; i++){
156     x = in[i] - e;
157     if( x==0 || x==1 || x=='\''){
158       out[j++] = 1;
159       x++;
160     }
161     out[j++] = x;
162   }
163   out[j] = 0;
164   assert( j==n+m+1 );
165   return j;
166 }
167 
168 /*
169 ** Decode the string "in" into binary data and write it into "out".
170 ** This routine reverses the encoding created by sqlite_encode_binary().
171 ** The output will always be a few bytes less than the input.  The number
172 ** of bytes of output is returned.  If the input is not a well-formed
173 ** encoding, -1 is returned.
174 **
175 ** The "in" and "out" parameters may point to the same buffer in order
176 ** to decode a string in place.
177 */
sqlite_decode_binary(const unsigned char * in,unsigned char * out)178 int sqlite_decode_binary(const unsigned char *in, unsigned char *out){
179   int i, e;
180   unsigned char c;
181   e = *(in++);
182   i = 0;
183   while( (c = *(in++))!=0 ){
184     if( c==1 ){
185       c = *(in++) - 1;
186     }
187     out[i++] = c + e;
188   }
189   return i;
190 }
191 
192 #ifdef ENCODER_TEST
193 #include <stdio.h>
194 /*
195 ** The subroutines above are not tested by the usual test suite.  To test
196 ** these routines, compile just this one file with a -DENCODER_TEST=1 option
197 ** and run the result.
198 */
main(int argc,char ** argv)199 int main(int argc, char **argv){
200   int i, j, n, m, nOut, nByteIn, nByteOut;
201   unsigned char in[30000];
202   unsigned char out[33000];
203 
204   nByteIn = nByteOut = 0;
205   for(i=0; i<sizeof(in); i++){
206     printf("Test %d: ", i+1);
207     n = rand() % (i+1);
208     if( i%100==0 ){
209       int k;
210       for(j=k=0; j<n; j++){
211         /* if( k==0 || k=='\'' ) k++; */
212         in[j] = k;
213         k = (k+1)&0xff;
214       }
215     }else{
216       for(j=0; j<n; j++) in[j] = rand() & 0xff;
217     }
218     nByteIn += n;
219     nOut = sqlite_encode_binary(in, n, out);
220     nByteOut += nOut;
221     if( nOut!=strlen(out) ){
222       printf(" ERROR return value is %d instead of %d\n", nOut, strlen(out));
223       exit(1);
224     }
225     if( nOut!=sqlite_encode_binary(in, n, 0) ){
226       printf(" ERROR actual output size disagrees with predicted size\n");
227       exit(1);
228     }
229     m = (256*n + 1262)/253;
230     printf("size %d->%d (max %d)", n, strlen(out)+1, m);
231     if( strlen(out)+1>m ){
232       printf(" ERROR output too big\n");
233       exit(1);
234     }
235     for(j=0; out[j]; j++){
236       if( out[j]=='\'' ){
237         printf(" ERROR contains (')\n");
238         exit(1);
239       }
240     }
241     j = sqlite_decode_binary(out, out);
242     if( j!=n ){
243       printf(" ERROR decode size %d\n", j);
244       exit(1);
245     }
246     if( memcmp(in, out, n)!=0 ){
247       printf(" ERROR decode mismatch\n");
248       exit(1);
249     }
250     printf(" OK\n");
251   }
252   fprintf(stderr,"Finished.  Total encoding: %d->%d bytes\n",
253           nByteIn, nByteOut);
254   fprintf(stderr,"Avg size increase: %.3f%%\n",
255     (nByteOut-nByteIn)*100.0/(double)nByteIn);
256 }
257 #endif /* ENCODER_TEST */
258