4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 ******************************************************************************
13 ** This SQLite extension implements SQL compression functions
14 ** compress() and uncompress() using ZLIB.
16 #include "sqlite3ext.h"
17 SQLITE_EXTENSION_INIT1
21 ** Implementation of the "compress(X)" SQL function. The input X is
22 ** compressed using zLib and the output is returned.
24 ** The output is a BLOB that begins with a variable-length integer that
25 ** is the input size in bytes (the size of X before compression). The
26 ** variable-length integer is implemented as 1 to 5 bytes. There are
27 ** seven bits per integer stored in the lower seven bits of each byte.
28 ** More significant bits occur first. The most significant bit (0x80)
29 ** is a flag to indicate the end of the integer.
31 static void compressFunc(
32 sqlite3_context
*context
,
36 const unsigned char *pIn
;
39 unsigned long int nOut
;
43 pIn
= sqlite3_value_blob(argv
[0]);
44 nIn
= sqlite3_value_bytes(argv
[0]);
45 nOut
= 13 + nIn
+ (nIn
+999)/1000;
46 pOut
= sqlite3_malloc( nOut
+5 );
48 x
[i
] = (nIn
>> (7*(4-i
)))&0x7f;
50 for(i
=0; i
<4 && x
[i
]==0; i
++){}
51 for(j
=0; i
<=4; i
++, j
++) pOut
[j
] = x
[i
];
53 compress(&pOut
[j
], &nOut
, pIn
, nIn
);
54 sqlite3_result_blob(context
, pOut
, nOut
+j
, sqlite3_free
);
58 ** Implementation of the "uncompress(X)" SQL function. The argument X
59 ** is a blob which was obtained from compress(Y). The output will be
62 static void uncompressFunc(
63 sqlite3_context
*context
,
67 const unsigned char *pIn
;
70 unsigned long int nOut
;
74 pIn
= sqlite3_value_blob(argv
[0]);
75 nIn
= sqlite3_value_bytes(argv
[0]);
77 for(i
=0; i
<nIn
&& i
<5; i
++){
78 nOut
= (nOut
<<7) | (pIn
[i
]&0x7f);
79 if( (pIn
[i
]&0x80)!=0 ){ i
++; break; }
81 pOut
= sqlite3_malloc( nOut
+1 );
82 rc
= uncompress(pOut
, &nOut
, &pIn
[i
], nIn
-i
);
84 sqlite3_result_blob(context
, pOut
, nOut
, sqlite3_free
);
92 int sqlite3_compress_init(
95 const sqlite3_api_routines
*pApi
98 SQLITE_EXTENSION_INIT2(pApi
);
99 (void)pzErrMsg
; /* Unused parameter */
100 rc
= sqlite3_create_function(db
, "compress", 1, SQLITE_UTF8
, 0,
103 rc
= sqlite3_create_function(db
, "uncompress", 1, SQLITE_UTF8
, 0,
104 uncompressFunc
, 0, 0);