1 /*
2 This library will provide common mathematical and string functions in
3 SQL queries using the operating system libraries or provided
4 definitions.  It includes the following functions:
5 
6 Math: acos, asin, atan, atn2, atan2, acosh, asinh, atanh, difference,
7 degrees, radians, cos, sin, tan, cot, cosh, sinh, tanh, coth, exp,
8 log, log10, power, sign, sqrt, square, ceil, floor, pi.
9 
10 String: replicate, charindex, leftstr, rightstr, ltrim, rtrim, trim,
11 replace, reverse, proper, padl, padr, padc, strfilter.
12 
13 Aggregate: stdev, variance, mode, median, lower_quartile,
14 upper_quartile.
15 
16 The string functions ltrim, rtrim, trim, replace are included in
17 recent versions of SQLite and so by default do not build.
18 
19 Compilation instructions:
20  Compile this C source file into a dynamic library as follows:
21  * Linux:
22    gcc -fPIC -lm -shared extension-functions.c -o libsqlitefunctions.so
23  * Mac OS X:
24    gcc -fno-common -dynamiclib extension-functions.c -o libsqlitefunctions.dylib
25  (You may need to add flags
26   -I /opt/local/include/ -L/opt/local/lib -lsqlite3
27   if your sqlite3 is installed from Mac ports, or
28   -I /sw/include/ -L/sw/lib -lsqlite3
29   if installed with Fink.)
30  * Windows:
31   1. Install MinGW (http://www.mingw.org/) and you will get the gcc
32   (gnu compiler collection)
33   2. add the path to your path variable (isn't done during the
34    installation!)
35   3. compile:
36    gcc -shared -I "path" -o libsqlitefunctions.so extension-functions.c
37    (path = path of sqlite3ext.h; i.e. C:\programs\sqlite)
38 
39 Usage instructions for applications calling the sqlite3 API functions:
40   In your application, call sqlite3_enable_load_extension(db,1) to
41   allow loading external libraries.  Then load the library libsqlitefunctions
42   using sqlite3_load_extension; the third argument should be 0.
43   See http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions.
44   Select statements may now use these functions, as in
45   SELECT cos(radians(inclination)) FROM satsum WHERE satnum = 25544;
46 
47 Usage instructions for the sqlite3 program:
48   If the program is built so that loading extensions is permitted,
49   the following will work:
50    sqlite> SELECT load_extension('./libsqlitefunctions.so');
51    sqlite> select cos(radians(45));
52    0.707106781186548
53   Note: Loading extensions is by default prohibited as a
54   security measure; see "Security Considerations" in
55   http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions.
56   If the sqlite3 program and library are built this
57   way, you cannot use these functions from the program, you
58   must write your own program using the sqlite3 API, and call
59   sqlite3_enable_load_extension as described above, or else
60   rebuilt the sqlite3 program to allow loadable extensions.
61 
62 Alterations:
63 The instructions are for Linux, Mac OS X, and Windows; users of other
64 OSes may need to modify this procedure.  In particular, if your math
65 library lacks one or more of the needed trig or log functions, comment
66 out the appropriate HAVE_ #define at the top of file.  If you do not
67 wish to make a loadable module, comment out the define for
68 COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE.  If you are using a
69 version of SQLite without the trim functions and replace, comment out
70 the HAVE_TRIM #define.
71 
72 Liam Healy
73 
74 History:
75 2010-01-06 Correct check for argc in squareFunc, and add Windows
76 compilation instructions.
77 2009-06-24 Correct check for argc in properFunc.
78 2008-09-14 Add check that memory was actually allocated after
79 sqlite3_malloc or sqlite3StrDup, call sqlite3_result_error_nomem if
80 not.  Thanks to Robert Simpson.
81 2008-06-13 Change to instructions to indicate use of the math library
82 and that program might work.
83 2007-10-01 Minor clarification to instructions.
84 2007-09-29 Compilation as loadable module is optional with
85 COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE.
86 2007-09-28 Use sqlite3_extension_init and macros
87 SQLITE_EXTENSION_INIT1, SQLITE_EXTENSION_INIT2, so that it works with
88 sqlite3_load_extension.  Thanks to Eric Higashino and Joe Wilson.
89 New instructions for Mac compilation.
90 2007-09-17 With help from Joe Wilson and Nuno Luca, made use of
91 external interfaces so that compilation is no longer dependent on
92 SQLite source code.  Merged source, header, and README into a single
93 file.  Added casts so that Mac will compile without warnings (unsigned
94 and signed char).
95 2007-09-05 Included some definitions from sqlite 3.3.13 so that this
96 will continue to work in newer versions of sqlite.  Completed
97 description of functions available.
98 2007-03-27 Revised description.
99 2007-03-23 Small cleanup and a bug fix on the code.  This was mainly
100 letting errno flag errors encountered in the math library and checking
101 the result, rather than pre-checking.  This fixes a bug in power that
102 would cause an error if any non-positive number was raised to any
103 power.
104 2007-02-07 posted by Mikey C to sqlite mailing list.
105 Original code 2006 June 05 by relicoder.
106 
107 */
108 
109 //#include "config.h"
110 
111 #define COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE 1
112 #define HAVE_ACOSH 1
113 #define HAVE_ASINH 1
114 #define HAVE_ATANH 1
115 #define HAVE_SINH 1
116 #define HAVE_COSH 1
117 #define HAVE_TANH 1
118 #define HAVE_LOG10 1
119 #define HAVE_ISBLANK 1
120 #define SQLITE_SOUNDEX 1
121 #define HAVE_TRIM 1		/* LMH 2007-03-25 if sqlite has trim functions */
122 
123 #ifdef COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE
124 #include "sqlite/sqlite3ext.h"
125 SQLITE_EXTENSION_INIT1
126 #else
127 #include "sqlite3.h"
128 #endif
129 
130 #include <ctype.h>
131 /* relicoder */
132 #include <math.h>
133 #include <string.h>
134 #include <stdio.h>
135 #include <errno.h>		/* LMH 2007-03-25 */
136 
137 #include <stdlib.h>
138 #include <assert.h>
139 
140 #ifndef _MAP_H_
141 #define _MAP_H_
142 
143 #include <stdint.h>
144 
145 /*
146 ** Simple binary tree implementation to use in median, mode and quartile calculations
147 ** Tree is not necessarily balanced. That would require something like red&black trees of AVL
148 */
149 
150 typedef int(*cmp_func)(const void *, const void *);
151 typedef void(*map_iterator)(void*, int64_t, void*);
152 
153 typedef struct node{
154   struct node *l;
155   struct node *r;
156   void* data;
157   int64_t count;
158 } node;
159 
160 typedef struct map{
161   node *base;
162   cmp_func cmp;
163 } map;
164 
165 /*
166 ** creates a map given a comparison function
167 */
168 map map_make(cmp_func cmp);
169 
170 /*
171 ** inserts the element e into map m
172 */
173 void map_insert(map *m, void *e);
174 
175 /*
176 ** executes function iter over all elements in the map, in key increasing order
177 */
178 void map_iterate(map *m, map_iterator iter, void* p);
179 
180 /*
181 ** frees all memory used by a map
182 */
183 void map_destroy(map *m);
184 
185 /*
186 ** compares 2 integers
187 ** to use with map_make
188 */
189 int int_cmp(const void *a, const void *b);
190 
191 /*
192 ** compares 2 doubles
193 ** to use with map_make
194 */
195 int double_cmp(const void *a, const void *b);
196 
197 #endif /* _MAP_H_ */
198 
199 typedef uint8_t         u8;
200 typedef uint16_t        u16;
201 typedef int64_t         i64;
202 
sqlite3StrDup(const char * z)203 static char *sqlite3StrDup( const char *z ) {
204     char *res = sqlite3_malloc( strlen(z)+1 );
205     return strcpy( res, z );
206 }
207 
208 /*
209 ** These are copied verbatim from fun.c so as to not have the names exported
210 */
211 
212 /* LMH from sqlite3 3.3.13 */
213 /*
214 ** This table maps from the first byte of a UTF-8 character to the number
215 ** of trailing bytes expected. A value '4' indicates that the table key
216 ** is not a legal first byte for a UTF-8 character.
217 */
218 static const u8 xtra_utf8_bytes[256]  = {
219 /* 0xxxxxxx */
220 0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
228 
229 /* 10wwwwww */
230 4, 4, 4, 4, 4, 4, 4, 4,     4, 4, 4, 4, 4, 4, 4, 4,
231 4, 4, 4, 4, 4, 4, 4, 4,     4, 4, 4, 4, 4, 4, 4, 4,
232 4, 4, 4, 4, 4, 4, 4, 4,     4, 4, 4, 4, 4, 4, 4, 4,
233 4, 4, 4, 4, 4, 4, 4, 4,     4, 4, 4, 4, 4, 4, 4, 4,
234 
235 /* 110yyyyy */
236 1, 1, 1, 1, 1, 1, 1, 1,     1, 1, 1, 1, 1, 1, 1, 1,
237 1, 1, 1, 1, 1, 1, 1, 1,     1, 1, 1, 1, 1, 1, 1, 1,
238 
239 /* 1110zzzz */
240 2, 2, 2, 2, 2, 2, 2, 2,     2, 2, 2, 2, 2, 2, 2, 2,
241 
242 /* 11110yyy */
243 3, 3, 3, 3, 3, 3, 3, 3,     4, 4, 4, 4, 4, 4, 4, 4,
244 };
245 
246 
247 /*
248 ** This table maps from the number of trailing bytes in a UTF-8 character
249 ** to an integer constant that is effectively calculated for each character
250 ** read by a naive implementation of a UTF-8 character reader. The code
251 ** in the READ_UTF8 macro explains things best.
252 */
253 static const int xtra_utf8_bits[] =  {
254   0,
255   12416,          /* (0xC0 << 6) + (0x80) */
256   925824,         /* (0xE0 << 12) + (0x80 << 6) + (0x80) */
257   63447168        /* (0xF0 << 18) + (0x80 << 12) + (0x80 << 6) + 0x80 */
258 };
259 
260 /*
261 ** If a UTF-8 character contains N bytes extra bytes (N bytes follow
262 ** the initial byte so that the total character length is N+1) then
263 ** masking the character with utf8_mask[N] must produce a non-zero
264 ** result.  Otherwise, we have an (illegal) overlong encoding.
265 */
266 static const int utf_mask[] = {
267   0x00000000,
268   0xffffff80,
269   0xfffff800,
270   0xffff0000,
271 };
272 
273 /* LMH salvaged from sqlite3 3.3.13 source code src/utf.c */
274 #define READ_UTF8(zIn, c) { \
275   int xtra;                                            \
276   c = *(zIn)++;                                        \
277   xtra = xtra_utf8_bytes[c];                           \
278   switch( xtra ){                                      \
279     case 4: c = (int)0xFFFD; break;                    \
280     case 3: c = (c<<6) + *(zIn)++;                     \
281     case 2: c = (c<<6) + *(zIn)++;                     \
282     case 1: c = (c<<6) + *(zIn)++;                     \
283     c -= xtra_utf8_bits[xtra];                         \
284     if( (utf_mask[xtra]&c)==0                          \
285         || (c&0xFFFFF800)==0xD800                      \
286         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }    \
287   }                                                    \
288 }
289 
sqlite3ReadUtf8(const unsigned char * z)290 static int sqlite3ReadUtf8(const unsigned char *z){
291   int c;
292   READ_UTF8(z, c);
293   return c;
294 }
295 
296 #define SKIP_UTF8(zIn) {                               \
297   zIn += (xtra_utf8_bytes[*(u8 *)zIn] + 1);            \
298 }
299 
300 /*
301 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
302 ** return the number of unicode characters in pZ up to (but not including)
303 ** the first 0x00 byte. If nByte is not less than zero, return the
304 ** number of unicode characters in the first nByte of pZ (or up to
305 ** the first 0x00, whichever comes first).
306 */
sqlite3Utf8CharLen(const char * z,int nByte)307 static int sqlite3Utf8CharLen(const char *z, int nByte){
308   int r = 0;
309   const char *zTerm;
310   if( nByte>=0 ){
311     zTerm = &z[nByte];
312   }else{
313     zTerm = (const char *)(-1);
314   }
315   assert( z<=zTerm );
316   while( *z!=0 && z<zTerm ){
317     SKIP_UTF8(z);
318     r++;
319   }
320   return r;
321 }
322 
323 /*
324 ** X is a pointer to the first byte of a UTF-8 character.  Increment
325 ** X so that it points to the next character.  This only works right
326 ** if X points to a well-formed UTF-8 string.
327 */
328 #define sqliteNextChar(X)  while( (0xc0&*++(X))==0x80 ){}
329 #define sqliteCharVal(X)   sqlite3ReadUtf8(X)
330 
331 /*
332 ** This is a macro that facilitates writting wrappers for math.h functions
333 ** it creates code for a function to use in SQlite that gets one numeric input
334 ** and returns a floating point value.
335 **
336 ** Could have been implemented using pointers to functions but this way it's inline
337 ** and thus more efficient. Lower * ranking though...
338 **
339 ** Parameters:
340 ** name:      function name to de defined (eg: sinFunc)
341 ** function:  function defined in math.h to wrap (eg: sin)
342 ** domain:    boolean condition that CAN'T happen in terms of the input parameter rVal
343 **            (eg: rval<0 for sqrt)
344 */
345 /* LMH 2007-03-25 Changed to use errno and remove domain; no pre-checking for errors. */
346 #define GEN_MATH_WRAP_DOUBLE_1(name, function) \
347 static void name(sqlite3_context *context, int argc, sqlite3_value **argv){\
348   double rVal = 0.0, val;\
349   assert( argc==1 );\
350   switch( sqlite3_value_type(argv[0]) ){\
351     case SQLITE_NULL: {\
352       sqlite3_result_null(context);\
353       break;\
354     }\
355     default: {\
356       rVal = sqlite3_value_double(argv[0]);\
357       errno = 0;\
358       val = function(rVal);\
359       if (errno == 0) {\
360         sqlite3_result_double(context, val);\
361       } else {\
362         sqlite3_result_error(context, strerror(errno), errno);\
363       }\
364       break;\
365     }\
366   }\
367 }\
368 
369 
370 /*
371 ** Example of GEN_MATH_WRAP_DOUBLE_1 usage
372 ** this creates function sqrtFunc to wrap the math.h standard function sqrt(x)=x^0.5
373 */
GEN_MATH_WRAP_DOUBLE_1(sqrtFunc,sqrt)374 GEN_MATH_WRAP_DOUBLE_1(sqrtFunc, sqrt)
375 
376 /* trignometric functions */
377 GEN_MATH_WRAP_DOUBLE_1(acosFunc, acos)
378 GEN_MATH_WRAP_DOUBLE_1(asinFunc, asin)
379 GEN_MATH_WRAP_DOUBLE_1(atanFunc, atan)
380 
381 /*
382 ** Many of systems don't have inverse hyperbolic trig functions so this will emulate
383 ** them on those systems in terms of log and sqrt (formulas are too trivial to demand
384 ** written proof here)
385 */
386 
387 #ifndef HAVE_ACOSH
388 static double acosh(double x){
389   return log(x + sqrt(x*x - 1.0));
390 }
391 #endif
392 
GEN_MATH_WRAP_DOUBLE_1(acoshFunc,acosh)393 GEN_MATH_WRAP_DOUBLE_1(acoshFunc, acosh)
394 
395 #ifndef HAVE_ASINH
396 static double asinh(double x){
397   return log(x + sqrt(x*x + 1.0));
398 }
399 #endif
400 
GEN_MATH_WRAP_DOUBLE_1(asinhFunc,asinh)401 GEN_MATH_WRAP_DOUBLE_1(asinhFunc, asinh)
402 
403 #ifndef HAVE_ATANH
404 static double atanh(double x){
405   return (1.0/2.0)*log((1+x)/(1-x)) ;
406 }
407 #endif
408 
GEN_MATH_WRAP_DOUBLE_1(atanhFunc,atanh)409 GEN_MATH_WRAP_DOUBLE_1(atanhFunc, atanh)
410 
411 /*
412 ** math.h doesn't require cot (cotangent) so it's defined here
413 */
414 static double cot(double x){
415   return 1.0/tan(x);
416 }
417 
GEN_MATH_WRAP_DOUBLE_1(sinFunc,sin)418 GEN_MATH_WRAP_DOUBLE_1(sinFunc, sin)
419 GEN_MATH_WRAP_DOUBLE_1(cosFunc, cos)
420 GEN_MATH_WRAP_DOUBLE_1(tanFunc, tan)
421 GEN_MATH_WRAP_DOUBLE_1(cotFunc, cot)
422 
423 static double coth(double x){
424   return 1.0/tanh(x);
425 }
426 
427 /*
428 ** Many systems don't have hyperbolic trigonometric functions so this will emulate
429 ** them on those systems directly from the definition in terms of exp
430 */
431 #ifndef HAVE_SINH
sinh(double x)432 static double sinh(double x){
433   return (exp(x)-exp(-x))/2.0;
434 }
435 #endif
436 
GEN_MATH_WRAP_DOUBLE_1(sinhFunc,sinh)437 GEN_MATH_WRAP_DOUBLE_1(sinhFunc, sinh)
438 
439 #ifndef HAVE_COSH
440 static double cosh(double x){
441   return (exp(x)+exp(-x))/2.0;
442 }
443 #endif
444 
GEN_MATH_WRAP_DOUBLE_1(coshFunc,cosh)445 GEN_MATH_WRAP_DOUBLE_1(coshFunc, cosh)
446 
447 #ifndef HAVE_TANH
448 static double tanh(double x){
449   return sinh(x)/cosh(x);
450 }
451 #endif
452 
GEN_MATH_WRAP_DOUBLE_1(tanhFunc,tanh)453 GEN_MATH_WRAP_DOUBLE_1(tanhFunc, tanh)
454 
455 GEN_MATH_WRAP_DOUBLE_1(cothFunc, coth)
456 
457 /*
458 ** Some systems lack log in base 10. This will emulate it
459 */
460 
461 #ifndef HAVE_LOG10
462 static double log10(double x){
463   static double l10 = -1.0;
464   if( l10<0.0 ){
465     l10 = log(10.0);
466   }
467   return log(x)/l10;
468 }
469 #endif
470 
GEN_MATH_WRAP_DOUBLE_1(logFunc,log)471 GEN_MATH_WRAP_DOUBLE_1(logFunc, log)
472 GEN_MATH_WRAP_DOUBLE_1(log10Func, log10)
473 GEN_MATH_WRAP_DOUBLE_1(expFunc, exp)
474 
475 /*
476 ** Fallback for systems where math.h doesn't define M_PI
477 */
478 #undef M_PI
479 #ifndef M_PI
480 /*
481 ** static double PI = acos(-1.0);
482 ** #define M_PI (PI)
483 */
484 #define M_PI 3.14159265358979323846
485 #endif
486 
487 /* Convert Degrees into Radians */
488 static double deg2rad(double x){
489   return x*M_PI/180.0;
490 }
491 
492 /* Convert Radians into Degrees */
rad2deg(double x)493 static double rad2deg(double x){
494   return 180.0*x/M_PI;
495 }
496 
GEN_MATH_WRAP_DOUBLE_1(rad2degFunc,rad2deg)497 GEN_MATH_WRAP_DOUBLE_1(rad2degFunc, rad2deg)
498 GEN_MATH_WRAP_DOUBLE_1(deg2radFunc, deg2rad)
499 
500 /* constant function that returns the value of PI=3.1415... */
501 static void piFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
502   sqlite3_result_double(context, M_PI);
503 }
504 
505 /*
506 ** Implements the sqrt function, it has the peculiarity of returning an integer when the
507 ** the argument is an integer.
508 ** Since SQLite isn't strongly typed (almost untyped actually) this is a bit pedantic
509 */
squareFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)510 static void squareFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
511   i64 iVal = 0;
512   double rVal = 0.0;
513   assert( argc==1 );
514   switch( sqlite3_value_type(argv[0]) ){
515     case SQLITE_INTEGER: {
516       iVal = sqlite3_value_int64(argv[0]);
517       sqlite3_result_int64(context, iVal*iVal);
518       break;
519     }
520     case SQLITE_NULL: {
521       sqlite3_result_null(context);
522       break;
523     }
524     default: {
525       rVal = sqlite3_value_double(argv[0]);
526       sqlite3_result_double(context, rVal*rVal);
527       break;
528     }
529   }
530 }
531 
532 /*
533 ** Wraps the pow math.h function
534 ** When both the base and the exponent are integers the result should be integer
535 ** (see sqrt just before this). Here the result is always double
536 */
537 /* LMH 2007-03-25 Changed to use errno; no pre-checking for errors.  Also removes
538   but that was present in the pre-checking that called sqlite3_result_error on
539   a non-positive first argument, which is not always an error. */
powerFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)540 static void powerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
541   double r1 = 0.0;
542   double r2 = 0.0;
543   double val;
544 
545   assert( argc==2 );
546 
547   if( sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL ){
548     sqlite3_result_null(context);
549   }else{
550     r1 = sqlite3_value_double(argv[0]);
551     r2 = sqlite3_value_double(argv[1]);
552     errno = 0;
553     val = pow(r1,r2);
554     if (errno == 0) {
555       sqlite3_result_double(context, val);
556     } else {
557       sqlite3_result_error(context, strerror(errno), errno);
558     }
559   }
560 }
561 
562 /*
563 ** atan2 wrapper
564 */
atn2Func(sqlite3_context * context,int argc,sqlite3_value ** argv)565 static void atn2Func(sqlite3_context *context, int argc, sqlite3_value **argv){
566   double r1 = 0.0;
567   double r2 = 0.0;
568 
569   assert( argc==2 );
570 
571   if( sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL ){
572     sqlite3_result_null(context);
573   }else{
574     r1 = sqlite3_value_double(argv[0]);
575     r2 = sqlite3_value_double(argv[1]);
576     sqlite3_result_double(context, atan2(r1,r2));
577   }
578 }
579 
580 /*
581 ** Implementation of the sign() function
582 ** return one of 3 possibilities +1,0 or -1 when the argument is respectively
583 ** positive, 0 or negative.
584 ** When the argument is NULL the result is also NULL (completly conventional)
585 */
signFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)586 static void signFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
587   double rVal=0.0;
588   i64 iVal=0;
589   assert( argc==1 );
590   switch( sqlite3_value_type(argv[0]) ){
591     case SQLITE_INTEGER: {
592       iVal = sqlite3_value_int64(argv[0]);
593       iVal = ( iVal > 0) ? 1: ( iVal < 0 ) ? -1: 0;
594       sqlite3_result_int64(context, iVal);
595       break;
596     }
597     case SQLITE_NULL: {
598       sqlite3_result_null(context);
599       break;
600     }
601     default: {
602  /* 2nd change below. Line for abs was: if( rVal<0 ) rVal = rVal * -1.0;  */
603 
604       rVal = sqlite3_value_double(argv[0]);
605       rVal = ( rVal > 0) ? 1: ( rVal < 0 ) ? -1: 0;
606       sqlite3_result_double(context, rVal);
607       break;
608     }
609   }
610 }
611 
612 
613 /*
614 ** smallest integer value not less than argument
615 */
ceilFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)616 static void ceilFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
617   double rVal=0.0;
618   assert( argc==1 );
619   switch( sqlite3_value_type(argv[0]) ){
620     case SQLITE_INTEGER: {
621       i64 iVal = sqlite3_value_int64(argv[0]);
622       sqlite3_result_int64(context, iVal);
623       break;
624     }
625     case SQLITE_NULL: {
626       sqlite3_result_null(context);
627       break;
628     }
629     default: {
630       rVal = sqlite3_value_double(argv[0]);
631       sqlite3_result_int64(context, (i64) ceil(rVal));
632       break;
633     }
634   }
635 }
636 
637 /*
638 ** largest integer value not greater than argument
639 */
floorFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)640 static void floorFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
641   double rVal=0.0;
642   assert( argc==1 );
643   switch( sqlite3_value_type(argv[0]) ){
644     case SQLITE_INTEGER: {
645       i64 iVal = sqlite3_value_int64(argv[0]);
646       sqlite3_result_int64(context, iVal);
647       break;
648     }
649     case SQLITE_NULL: {
650       sqlite3_result_null(context);
651       break;
652     }
653     default: {
654       rVal = sqlite3_value_double(argv[0]);
655       sqlite3_result_int64(context, (i64) floor(rVal));
656       break;
657     }
658   }
659 }
660 
661 /*
662 ** Given a string (s) in the first argument and an integer (n) in the second returns the
663 ** string that constains s contatenated n times
664 */
replicateFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)665 static void replicateFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
666   unsigned char *z;        /* input string */
667   unsigned char *zo;       /* result string */
668   i64 iCount;              /* times to repeat */
669   i64 nLen;                /* length of the input string (no multibyte considerations) */
670   i64 nTLen;               /* length of the result string (no multibyte considerations) */
671   i64 i=0;
672 
673   if( argc!=2 || SQLITE_NULL==sqlite3_value_type(argv[0]) )
674     return;
675 
676   iCount = sqlite3_value_int64(argv[1]);
677 
678   if( iCount<0 ){
679     sqlite3_result_error(context, "domain error", -1);
680   }else{
681 
682     nLen  = sqlite3_value_bytes(argv[0]);
683     nTLen = nLen*iCount;
684     z=sqlite3_malloc(nTLen+1);
685     zo=sqlite3_malloc(nLen+1);
686     if (!z || !zo){
687       sqlite3_result_error_nomem(context);
688       if (z) sqlite3_free(z);
689       if (zo) sqlite3_free(zo);
690       return;
691     }
692     strcpy((char*)zo, (char*)sqlite3_value_text(argv[0]));
693 
694     for(i=0; i<iCount; ++i){
695       strcpy((char*)(z+i*nLen), (char*)zo);
696     }
697 
698     sqlite3_result_text(context, (char*)z, -1, SQLITE_TRANSIENT);
699     sqlite3_free(z);
700     sqlite3_free(zo);
701   }
702 }
703 
704 /*
705 ** Some systems (win32 among others) don't have an isblank function, this will emulate it.
706 ** This function is not UFT-8 safe since it only analyses a byte character.
707 */
708 #ifndef HAVE_ISBLANK
isblank(char c)709 int isblank(char c){
710   return( ' '==c || '\t'==c );
711 }
712 #endif
713 
properFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)714 static void properFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
715   const unsigned char *z;     /* input string */
716   unsigned char *zo;          /* output string */
717   unsigned char *zt;          /* iterator */
718   char r;
719   int c=1;
720 
721   assert( argc==1);
722   if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
723     sqlite3_result_null(context);
724     return;
725   }
726 
727   z = sqlite3_value_text(argv[0]);
728   zo = (unsigned char *)sqlite3StrDup((char *) z);
729   if (!zo) {
730     sqlite3_result_error_nomem(context);
731     return;
732   }
733   zt = zo;
734 
735   while( (r = *(z++))!=0 ){
736     if( isblank(r) ){
737       c=1;
738     }else{
739       if( c==1 ){
740         r = toupper(r);
741       }else{
742         r = tolower(r);
743       }
744       c=0;
745     }
746     *(zt++) = r;
747   }
748   *zt = '\0';
749 
750   sqlite3_result_text(context, (char*)zo, -1, SQLITE_TRANSIENT);
751   sqlite3_free(zo);
752 }
753 
754 /*
755 ** given an input string (s) and an integer (n) adds spaces at the begining of  s
756 ** until it has a length of n characters.
757 ** When s has a length >=n it's a NOP
758 ** padl(NULL) = NULL
759 */
padlFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)760 static void padlFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
761   i64 ilen;          /* length to pad to */
762   i64 zl;            /* length of the input string (UTF-8 chars) */
763   int i = 0;
764   const char *zi;    /* input string */
765   char *zo;          /* output string */
766   char *zt;
767 
768   assert( argc==2 );
769 
770   if( sqlite3_value_type(argv[0]) == SQLITE_NULL ){
771     sqlite3_result_null(context);
772   }else{
773     zi = (char *)sqlite3_value_text(argv[0]);
774     ilen = sqlite3_value_int64(argv[1]);
775     /* check domain */
776     if(ilen<0){
777       sqlite3_result_error(context, "domain error", -1);
778       return;
779     }
780     zl = sqlite3Utf8CharLen(zi, -1);
781     if( zl>=ilen ){
782       /* string is longer than the requested pad length, return the same string (dup it) */
783       zo = sqlite3StrDup(zi);
784       if (!zo){
785         sqlite3_result_error_nomem(context);
786         return;
787       }
788       sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
789     }else{
790       zo = sqlite3_malloc(strlen(zi)+ilen-zl+1);
791       if (!zo){
792         sqlite3_result_error_nomem(context);
793         return;
794       }
795       zt = zo;
796       for(i=1; i+zl<=ilen; ++i){
797         *(zt++)=' ';
798       }
799       /* no need to take UTF-8 into consideration here */
800       strcpy(zt,zi);
801     }
802     sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
803     sqlite3_free(zo);
804   }
805 }
806 
807 /*
808 ** given an input string (s) and an integer (n) appends spaces at the end of  s
809 ** until it has a length of n characters.
810 ** When s has a length >=n it's a NOP
811 ** padl(NULL) = NULL
812 */
padrFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)813 static void padrFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
814   i64 ilen;          /* length to pad to */
815   i64 zl;            /* length of the input string (UTF-8 chars) */
816   i64 zll;           /* length of the input string (bytes) */
817   int i = 0;
818   const char *zi;    /* input string */
819   char *zo;          /* output string */
820   char *zt;
821 
822   assert( argc==2 );
823 
824   if( sqlite3_value_type(argv[0]) == SQLITE_NULL ){
825     sqlite3_result_null(context);
826   }else{
827     zi = (char *)sqlite3_value_text(argv[0]);
828     ilen = sqlite3_value_int64(argv[1]);
829     /* check domain */
830     if(ilen<0){
831       sqlite3_result_error(context, "domain error", -1);
832       return;
833     }
834     zl = sqlite3Utf8CharLen(zi, -1);
835     if( zl>=ilen ){
836       /* string is longer than the requested pad length, return the same string (dup it) */
837       zo = sqlite3StrDup(zi);
838       if (!zo){
839         sqlite3_result_error_nomem(context);
840         return;
841       }
842       sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
843     }else{
844       zll = strlen(zi);
845       zo = sqlite3_malloc(zll+ilen-zl+1);
846       if (!zo){
847         sqlite3_result_error_nomem(context);
848         return;
849       }
850       zt = strcpy(zo,zi)+zll;
851       for(i=1; i+zl<=ilen; ++i){
852         *(zt++) = ' ';
853       }
854       *zt = '\0';
855     }
856     sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
857     sqlite3_free(zo);
858   }
859 }
860 
861 /*
862 ** given an input string (s) and an integer (n) appends spaces at the end of  s
863 ** and adds spaces at the begining of s until it has a length of n characters.
864 ** Tries to add has many characters at the left as at the right.
865 ** When s has a length >=n it's a NOP
866 ** padl(NULL) = NULL
867 */
padcFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)868 static void padcFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
869   i64 ilen;           /* length to pad to */
870   i64 zl;             /* length of the input string (UTF-8 chars) */
871   i64 zll;            /* length of the input string (bytes) */
872   int i = 0;
873   const char *zi;     /* input string */
874   char *zo;           /* output string */
875   char *zt;
876 
877   assert( argc==2 );
878 
879   if( sqlite3_value_type(argv[0]) == SQLITE_NULL ){
880     sqlite3_result_null(context);
881   }else{
882     zi = (char *)sqlite3_value_text(argv[0]);
883     ilen = sqlite3_value_int64(argv[1]);
884     /* check domain */
885     if(ilen<0){
886       sqlite3_result_error(context, "domain error", -1);
887       return;
888     }
889     zl = sqlite3Utf8CharLen(zi, -1);
890     if( zl>=ilen ){
891       /* string is longer than the requested pad length, return the same string (dup it) */
892       zo = sqlite3StrDup(zi);
893       if (!zo){
894         sqlite3_result_error_nomem(context);
895         return;
896       }
897       sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
898     }else{
899       zll = strlen(zi);
900       zo = sqlite3_malloc(zll+ilen-zl+1);
901       if (!zo){
902         sqlite3_result_error_nomem(context);
903         return;
904       }
905       zt = zo;
906       for(i=1; 2*i+zl<=ilen; ++i){
907         *(zt++) = ' ';
908       }
909       strcpy(zt, zi);
910       zt+=zll;
911       for(; i+zl<=ilen; ++i){
912         *(zt++) = ' ';
913       }
914       *zt = '\0';
915     }
916     sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
917     sqlite3_free(zo);
918   }
919 }
920 
921 /*
922 ** given 2 string (s1,s2) returns the string s1 with the characters NOT in s2 removed
923 ** assumes strings are UTF-8 encoded
924 */
strfilterFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)925 static void strfilterFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
926   const char *zi1;        /* first parameter string (searched string) */
927   const char *zi2;        /* second parameter string (vcontains valid characters) */
928   const char *z1;
929   const char *z21;
930   const char *z22;
931   char *zo;               /* output string */
932   char *zot;
933   int c1 = 0;
934   int c2 = 0;
935 
936   assert( argc==2 );
937 
938   if( sqlite3_value_type(argv[0]) == SQLITE_NULL || sqlite3_value_type(argv[1]) == SQLITE_NULL ){
939     sqlite3_result_null(context);
940   }else{
941     zi1 = (char *)sqlite3_value_text(argv[0]);
942     zi2 = (char *)sqlite3_value_text(argv[1]);
943     /*
944     ** maybe I could allocate less, but that would imply 2 passes, rather waste
945     ** (possibly) some memory
946     */
947     zo = sqlite3_malloc(strlen(zi1)+1);
948     if (!zo){
949       sqlite3_result_error_nomem(context);
950       return;
951     }
952     zot = zo;
953     z1 = zi1;
954     while( (c1=sqliteCharVal((unsigned char *)z1))!=0 ){
955       z21=zi2;
956       while( (c2=sqliteCharVal((unsigned char *)z21))!=0 && c2!=c1 ){
957         sqliteNextChar(z21);
958       }
959       if( c2!=0){
960         z22=z21;
961         sqliteNextChar(z22);
962         strncpy(zot, z21, z22-z21);
963         zot+=z22-z21;
964       }
965       sqliteNextChar(z1);
966     }
967     *zot = '\0';
968 
969     sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
970     sqlite3_free(zo);
971   }
972 }
973 
974 /*
975 ** Given a string z1, retutns the (0 based) index of it's first occurence
976 ** in z2 after the first s characters.
977 ** Returns -1 when there isn't a match.
978 ** updates p to point to the character where the match occured.
979 ** This is an auxiliary function.
980 */
_substr(const char * z1,const char * z2,int s,const char ** p)981 static int _substr(const char* z1, const char* z2, int s, const char** p){
982   int c = 0;
983   int rVal=-1;
984   const char* zt1;
985   const char* zt2;
986   int c1,c2;
987 
988   if( '\0'==*z1 ){
989     return -1;
990   }
991 
992   while( (sqliteCharVal((unsigned char *)z2) != 0) && (c++)<s){
993     sqliteNextChar(z2);
994   }
995 
996   c = 0;
997   while( (sqliteCharVal((unsigned char *)z2)) != 0 ){
998     zt1 = z1;
999     zt2 = z2;
1000 
1001     do{
1002       c1 = sqliteCharVal((unsigned char *)zt1);
1003       c2 = sqliteCharVal((unsigned char *)zt2);
1004       sqliteNextChar(zt1);
1005       sqliteNextChar(zt2);
1006     }while( c1 == c2 && c1 != 0 && c2 != 0 );
1007 
1008     if( c1 == 0 ){
1009       rVal = c;
1010       break;
1011     }
1012 
1013     sqliteNextChar(z2);
1014     ++c;
1015   }
1016   if(p){
1017     *p=z2;
1018   }
1019   return rVal >=0 ? rVal+s : rVal;
1020 }
1021 
1022 /*
1023 ** given 2 input strings (s1,s2) and an integer (n) searches from the nth character
1024 ** for the string s1. Returns the position where the match occured.
1025 ** Characters are counted from 1.
1026 ** 0 is returned when no match occurs.
1027 */
1028 
charindexFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1029 static void charindexFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1030   const u8 *z1;          /* s1 string */
1031   u8 *z2;                /* s2 string */
1032   int s=0;
1033   int rVal=0;
1034 
1035   assert( argc==3 ||argc==2);
1036 
1037   if( SQLITE_NULL==sqlite3_value_type(argv[0]) || SQLITE_NULL==sqlite3_value_type(argv[1])){
1038     sqlite3_result_null(context);
1039     return;
1040   }
1041 
1042   z1 = sqlite3_value_text(argv[0]);
1043   if( z1==0 ) return;
1044   z2 = (u8*) sqlite3_value_text(argv[1]);
1045   if(argc==3){
1046     s = sqlite3_value_int(argv[2])-1;
1047     if(s<0){
1048       s=0;
1049     }
1050   }else{
1051     s = 0;
1052   }
1053 
1054   rVal = _substr((char *)z1,(char *)z2,s,NULL);
1055   sqlite3_result_int(context, rVal+1);
1056 }
1057 
1058 /*
1059 ** given a string (s) and an integer (n) returns the n leftmost (UTF-8) characters
1060 ** if the string has a length<=n or is NULL this function is NOP
1061 */
leftFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1062 static void leftFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1063   int c=0;
1064   int cc=0;
1065   int l=0;
1066   const unsigned char *z;       /* input string */
1067   const unsigned char *zt;
1068   unsigned char *rz;            /* output string */
1069 
1070   assert( argc==2);
1071 
1072   if( SQLITE_NULL==sqlite3_value_type(argv[0]) || SQLITE_NULL==sqlite3_value_type(argv[1])){
1073     sqlite3_result_null(context);
1074     return;
1075   }
1076 
1077   z  = sqlite3_value_text(argv[0]);
1078   l  = sqlite3_value_int(argv[1]);
1079   zt = z;
1080 
1081   while( sqliteCharVal(zt) && c++<l)
1082     sqliteNextChar(zt);
1083 
1084   cc=zt-z;
1085 
1086   rz = sqlite3_malloc(zt-z+1);
1087   if (!rz){
1088     sqlite3_result_error_nomem(context);
1089     return;
1090   }
1091   strncpy((char*) rz, (char*) z, zt-z);
1092   *(rz+cc) = '\0';
1093   sqlite3_result_text(context, (char*)rz, -1, SQLITE_TRANSIENT);
1094   sqlite3_free(rz);
1095 }
1096 
1097 /*
1098 ** given a string (s) and an integer (n) returns the n rightmost (UTF-8) characters
1099 ** if the string has a length<=n or is NULL this function is NOP
1100 */
rightFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1101 static void rightFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1102   int l=0;
1103   int c=0;
1104   int cc=0;
1105   const char *z;
1106   const char *zt;
1107   const char *ze;
1108   char *rz;
1109 
1110   assert( argc==2);
1111 
1112   if( SQLITE_NULL == sqlite3_value_type(argv[0]) || SQLITE_NULL == sqlite3_value_type(argv[1])){
1113     sqlite3_result_null(context);
1114     return;
1115   }
1116 
1117   z  = (char *)sqlite3_value_text(argv[0]);
1118   l  = sqlite3_value_int(argv[1]);
1119   zt = z;
1120 
1121   while( sqliteCharVal((unsigned char *)zt)!=0){
1122     sqliteNextChar(zt);
1123     ++c;
1124   }
1125 
1126   ze = zt;
1127   zt = z;
1128 
1129   cc=c-l;
1130   if(cc<0)
1131     cc=0;
1132 
1133   while( cc-- > 0 ){
1134     sqliteNextChar(zt);
1135   }
1136 
1137   rz = sqlite3_malloc(ze-zt+1);
1138   if (!rz){
1139     sqlite3_result_error_nomem(context);
1140     return;
1141   }
1142   strcpy((char*) rz, (char*) (zt));
1143   sqlite3_result_text(context, (char*)rz, -1, SQLITE_TRANSIENT);
1144   sqlite3_free(rz);
1145 }
1146 
1147 #ifndef HAVE_TRIM
1148 /*
1149 ** removes the whitespaces at the begining of a string.
1150 */
ltrim(const char * s)1151 const char* ltrim(const char* s){
1152   while( *s==' ' )
1153     ++s;
1154   return s;
1155 }
1156 
1157 /*
1158 ** removes the whitespaces at the end of a string.
1159 ** !mutates the input string!
1160 */
rtrim(char * s)1161 void rtrim(char* s){
1162   char* ss = s+strlen(s)-1;
1163   while( ss>=s && *ss==' ' )
1164     --ss;
1165   *(ss+1)='\0';
1166 }
1167 
1168 /*
1169 **  Removes the whitespace at the begining of a string
1170 */
ltrimFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1171 static void ltrimFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1172   const char *z;
1173 
1174   assert( argc==1);
1175 
1176   if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
1177     sqlite3_result_null(context);
1178     return;
1179   }
1180   z = sqlite3_value_text(argv[0]);
1181   sqlite3_result_text(context, ltrim(z), -1, SQLITE_TRANSIENT);
1182 }
1183 
1184 /*
1185 **  Removes the whitespace at the end of a string
1186 */
rtrimFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1187 static void rtrimFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1188   const char *z;
1189   char *rz;
1190   /* try not to change data in argv */
1191 
1192   assert( argc==1);
1193 
1194   if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
1195     sqlite3_result_null(context);
1196     return;
1197   }
1198   z = sqlite3_value_text(argv[0]);
1199   rz = sqlite3StrDup(z);
1200   rtrim(rz);
1201   sqlite3_result_text(context, rz, -1, SQLITE_TRANSIENT);
1202   sqlite3_free(rz);
1203 }
1204 
1205 /*
1206 **  Removes the whitespace at the begining and end of a string
1207 */
trimFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1208 static void trimFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1209   const char *z;
1210   char *rz;
1211   /* try not to change data in argv */
1212 
1213   assert( argc==1);
1214 
1215   if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
1216     sqlite3_result_null(context);
1217     return;
1218   }
1219   z = sqlite3_value_text(argv[0]);
1220   rz = sqlite3StrDup(z);
1221   rtrim(rz);
1222   sqlite3_result_text(context, ltrim(rz), -1, SQLITE_TRANSIENT);
1223   sqlite3_free(rz);
1224 }
1225 #endif
1226 
1227 /*
1228 ** given a pointer to a string s1, the length of that string (l1), a new string (s2)
1229 ** and it's length (l2) appends s2 to s1.
1230 ** All lengths in bytes.
1231 ** This is just an auxiliary function
1232 */
1233 // static void _append(char **s1, int l1, const char *s2, int l2){
1234 //   *s1 = realloc(*s1, (l1+l2+1)*sizeof(char));
1235 //   strncpy((*s1)+l1, s2, l2);
1236 //   *(*(s1)+l1+l2) = '\0';
1237 // }
1238 
1239 #ifndef HAVE_TRIM
1240 
1241 /*
1242 ** given strings s, s1 and s2 replaces occurrences of s1 in s by s2
1243 */
replaceFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1244 static void replaceFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1245   const char *z1;     /* string s (first parameter) */
1246   const char *z2;     /* string s1 (second parameter) string to look for */
1247   const char *z3;     /* string s2 (third parameter) string to replace occurrences of s1 with */
1248   int lz1;
1249   int lz2;
1250   int lz3;
1251   int lzo=0;
1252   char *zo=0;
1253   int ret=0;
1254   const char *zt1;
1255   const char *zt2;
1256 
1257   assert( 3==argc );
1258 
1259   if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
1260     sqlite3_result_null(context);
1261     return;
1262   }
1263 
1264   z1 = sqlite3_value_text(argv[0]);
1265   z2 = sqlite3_value_text(argv[1]);
1266   z3 = sqlite3_value_text(argv[2]);
1267   /* handle possible null values */
1268   if( 0==z2 ){
1269     z2="";
1270   }
1271   if( 0==z3 ){
1272     z3="";
1273   }
1274 
1275   lz1 = strlen(z1);
1276   lz2 = strlen(z2);
1277   lz3 = strlen(z3);
1278 
1279 #if 0
1280   /* special case when z2 is empty (or null) nothing will be changed */
1281   if( 0==lz2 ){
1282     sqlite3_result_text(context, z1, -1, SQLITE_TRANSIENT);
1283     return;
1284   }
1285 #endif
1286 
1287   zt1=z1;
1288   zt2=z1;
1289 
1290   while(1){
1291     ret=_substr(z2,zt1 , 0, &zt2);
1292 
1293     if( ret<0 )
1294       break;
1295 
1296     _append(&zo, lzo, zt1, zt2-zt1);
1297     lzo+=zt2-zt1;
1298     _append(&zo, lzo, z3, lz3);
1299     lzo+=lz3;
1300 
1301     zt1=zt2+lz2;
1302   }
1303   _append(&zo, lzo, zt1, lz1-(zt1-z1));
1304   sqlite3_result_text(context, zo, -1, SQLITE_TRANSIENT);
1305   sqlite3_free(zo);
1306 }
1307 #endif
1308 
1309 /*
1310 ** given a string returns the same string but with the characters in reverse order
1311 */
reverseFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1312 static void reverseFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1313   const char *z;
1314   const char *zt;
1315   char *rz;
1316   char *rzt;
1317   int l = 0;
1318   int i = 0;
1319 
1320   assert( 1==argc );
1321 
1322   if( SQLITE_NULL==sqlite3_value_type(argv[0]) ){
1323     sqlite3_result_null(context);
1324     return;
1325   }
1326   z = (char *)sqlite3_value_text(argv[0]);
1327   l = strlen(z);
1328   rz = sqlite3_malloc(l+1);
1329   if (!rz){
1330     sqlite3_result_error_nomem(context);
1331     return;
1332   }
1333   rzt = rz+l;
1334   *(rzt--) = '\0';
1335 
1336   zt=z;
1337   while( sqliteCharVal((unsigned char *)zt)!=0 ){
1338     z=zt;
1339     sqliteNextChar(zt);
1340     for(i=1; zt-i>=z; ++i){
1341       *(rzt--)=*(zt-i);
1342     }
1343   }
1344 
1345   sqlite3_result_text(context, rz, -1, SQLITE_TRANSIENT);
1346   sqlite3_free(rz);
1347 }
1348 
1349 /*
1350 ** An instance of the following structure holds the context of a
1351 ** stdev() or variance() aggregate computation.
1352 ** implementaion of http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Algorithm_II
1353 ** less prone to rounding errors
1354 */
1355 typedef struct StdevCtx StdevCtx;
1356 struct StdevCtx {
1357   double rM;
1358   double rS;
1359   i64 cnt;          /* number of elements */
1360 };
1361 
1362 /*
1363 ** An instance of the following structure holds the context of a
1364 ** mode() or median() aggregate computation.
1365 ** Depends on structures defined in map.c (see map & map)
1366 ** These aggregate functions only work for integers and floats although
1367 ** they could be made to work for strings. This is usually considered meaningless.
1368 ** Only usuall order (for median), no use of collation functions (would this even make sense?)
1369 */
1370 typedef struct ModeCtx ModeCtx;
1371 struct ModeCtx {
1372   i64 riM;            /* integer value found so far */
1373   double rdM;         /* double value found so far */
1374   i64 cnt;            /* number of elements so far */
1375   double pcnt;        /* number of elements smaller than a percentile */
1376   i64 mcnt;           /* maximum number of occurrences (for mode) */
1377   i64 mn;             /* number of occurrences (for mode and percentiles) */
1378   i64 is_double;      /* whether the computation is being done for doubles (>0) or integers (=0) */
1379   map* m;             /* map structure used for the computation */
1380   int done;           /* whether the answer has been found */
1381 };
1382 
1383 /*
1384 ** called for each value received during a calculation of stdev or variance
1385 */
varianceStep(sqlite3_context * context,int argc,sqlite3_value ** argv)1386 static void varianceStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1387   StdevCtx *p;
1388 
1389   double delta;
1390   double x;
1391 
1392   assert( argc==1 );
1393   p = sqlite3_aggregate_context(context, sizeof(*p));
1394   /* only consider non-null values */
1395   if( SQLITE_NULL != sqlite3_value_numeric_type(argv[0]) ){
1396     p->cnt++;
1397     x = sqlite3_value_double(argv[0]);
1398     delta = (x-p->rM);
1399     p->rM += delta/p->cnt;
1400     p->rS += delta*(x-p->rM);
1401   }
1402 }
1403 
1404 /*
1405 ** called for each value received during a calculation of mode of median
1406 */
modeStep(sqlite3_context * context,int argc,sqlite3_value ** argv)1407 static void modeStep(sqlite3_context *context, int argc, sqlite3_value **argv){
1408   ModeCtx *p;
1409   i64 xi=0;
1410   double xd=0.0;
1411   i64 *iptr;
1412   double *dptr;
1413   int type;
1414 
1415   assert( argc==1 );
1416   type = sqlite3_value_numeric_type(argv[0]);
1417 
1418   if( type == SQLITE_NULL)
1419     return;
1420 
1421   p = sqlite3_aggregate_context(context, sizeof(*p));
1422 
1423   if( 0==(p->m) ){
1424     p->m = calloc(1, sizeof(map));
1425     if( type==SQLITE_INTEGER ){
1426       /* map will be used for integers */
1427       *(p->m) = map_make(int_cmp);
1428       p->is_double = 0;
1429     }else{
1430       p->is_double = 1;
1431       /* map will be used for doubles */
1432       *(p->m) = map_make(double_cmp);
1433     }
1434   }
1435 
1436   ++(p->cnt);
1437 
1438   if( 0==p->is_double ){
1439     xi = sqlite3_value_int64(argv[0]);
1440     iptr = (i64*)calloc(1,sizeof(i64));
1441     *iptr = xi;
1442     map_insert(p->m, iptr);
1443   }else{
1444     xd = sqlite3_value_double(argv[0]);
1445     dptr = (double*)calloc(1,sizeof(double));
1446     *dptr = xd;
1447     map_insert(p->m, dptr);
1448   }
1449 }
1450 
1451 /*
1452 **  Auxiliary function that iterates all elements in a map and finds the mode
1453 **  (most frequent value)
1454 */
modeIterate(void * e,i64 c,void * pp)1455 static void modeIterate(void* e, i64 c, void* pp){
1456   i64 ei;
1457   double ed;
1458   ModeCtx *p = (ModeCtx*)pp;
1459 
1460   if( 0==p->is_double ){
1461     ei = *(int*)(e);
1462 
1463 	if( p->mcnt==c ){
1464       ++p->mn;
1465     }else if( p->mcnt<c ){
1466       p->riM = ei;
1467       p->mcnt = c;
1468 	  p->mn=1;
1469     }
1470   }else{
1471     ed = *(double*)(e);
1472 
1473 	if( p->mcnt==c ){
1474       ++p->mn;
1475     }else if(p->mcnt<c){
1476       p->rdM = ed;
1477       p->mcnt = c;
1478 	  p->mn=1;
1479     }
1480   }
1481 }
1482 
1483 /*
1484 **  Auxiliary function that iterates all elements in a map and finds the median
1485 **  (the value such that the number of elements smaller is equal the the number of
1486 **  elements larger)
1487 */
medianIterate(void * e,i64 c,void * pp)1488 static void medianIterate(void* e, i64 c, void* pp){
1489   i64 ei;
1490   double ed;
1491   double iL;
1492   double iR;
1493   int il;
1494   int ir;
1495   ModeCtx *p = (ModeCtx*)pp;
1496 
1497   if(p->done>0)
1498     return;
1499 
1500   iL = p->pcnt;
1501   iR = p->cnt - p->pcnt;
1502   il = p->mcnt + c;
1503   ir = p->cnt - p->mcnt;
1504 
1505   if( il >= iL ){
1506     if( ir >= iR ){
1507     ++p->mn;
1508       if( 0==p->is_double ){
1509         ei = *(int*)(e);
1510         p->riM += ei;
1511       }else{
1512         ed = *(double*)(e);
1513         p->rdM += ed;
1514       }
1515     }else{
1516       p->done=1;
1517     }
1518   }
1519   p->mcnt+=c;
1520 }
1521 
1522 /*
1523 ** Returns the mode value
1524 */
modeFinalize(sqlite3_context * context)1525 static void modeFinalize(sqlite3_context *context){
1526   ModeCtx *p;
1527   p = sqlite3_aggregate_context(context, 0);
1528   if( p && p->m ){
1529     map_iterate(p->m, modeIterate, p);
1530     map_destroy(p->m);
1531     free(p->m);
1532 
1533     if( 1==p->mn ){
1534       if( 0==p->is_double )
1535         sqlite3_result_int64(context, p->riM);
1536       else
1537         sqlite3_result_double(context, p->rdM);
1538     }
1539   }
1540 }
1541 
1542 /*
1543 ** auxiliary function for percentiles
1544 */
_medianFinalize(sqlite3_context * context)1545 static void _medianFinalize(sqlite3_context *context){
1546   ModeCtx *p;
1547   p = (ModeCtx*) sqlite3_aggregate_context(context, 0);
1548   if( p && p->m ){
1549     p->done=0;
1550     map_iterate(p->m, medianIterate, p);
1551     map_destroy(p->m);
1552     free(p->m);
1553 
1554     if( 0==p->is_double )
1555       if( 1==p->mn )
1556       	sqlite3_result_int64(context, p->riM);
1557       else
1558       	sqlite3_result_double(context, p->riM*1.0/p->mn);
1559     else
1560       sqlite3_result_double(context, p->rdM/p->mn);
1561   }
1562 }
1563 
1564 /*
1565 ** Returns the median value
1566 */
medianFinalize(sqlite3_context * context)1567 static void medianFinalize(sqlite3_context *context){
1568   ModeCtx *p;
1569   p = (ModeCtx*) sqlite3_aggregate_context(context, 0);
1570   if( p!=0 ){
1571     p->pcnt = (p->cnt)/2.0;
1572     _medianFinalize(context);
1573   }
1574 }
1575 
1576 /*
1577 ** Returns the lower_quartile value
1578 */
lower_quartileFinalize(sqlite3_context * context)1579 static void lower_quartileFinalize(sqlite3_context *context){
1580   ModeCtx *p;
1581   p = (ModeCtx*) sqlite3_aggregate_context(context, 0);
1582   if( p!=0 ){
1583     p->pcnt = (p->cnt)/4.0;
1584     _medianFinalize(context);
1585   }
1586 }
1587 
1588 /*
1589 ** Returns the upper_quartile value
1590 */
upper_quartileFinalize(sqlite3_context * context)1591 static void upper_quartileFinalize(sqlite3_context *context){
1592   ModeCtx *p;
1593   p = (ModeCtx*) sqlite3_aggregate_context(context, 0);
1594   if( p!=0 ){
1595     p->pcnt = (p->cnt)*3/4.0;
1596     _medianFinalize(context);
1597   }
1598 }
1599 
1600 /*
1601 ** Returns the stdev value
1602 */
stdevFinalize(sqlite3_context * context)1603 static void stdevFinalize(sqlite3_context *context){
1604   StdevCtx *p;
1605   p = sqlite3_aggregate_context(context, 0);
1606   if( p && p->cnt>1 ){
1607     sqlite3_result_double(context, sqrt(p->rS/(p->cnt-1)));
1608   }else{
1609     sqlite3_result_double(context, 0.0);
1610   }
1611 }
1612 
1613 /*
1614 ** Returns the variance value
1615 */
varianceFinalize(sqlite3_context * context)1616 static void varianceFinalize(sqlite3_context *context){
1617   StdevCtx *p;
1618   p = sqlite3_aggregate_context(context, 0);
1619   if( p && p->cnt>1 ){
1620     sqlite3_result_double(context, p->rS/(p->cnt-1));
1621   }else{
1622     sqlite3_result_double(context, 0.0);
1623   }
1624 }
1625 
1626 #ifdef SQLITE_SOUNDEX
1627 
1628 /* relicoder factored code */
1629 /*
1630 ** Calculates the soundex value of a string
1631 */
1632 
soundex(const u8 * zIn,char * zResult)1633 static void soundex(const u8 *zIn, char *zResult){
1634   int i, j;
1635   static const unsigned char iCode[] = {
1636     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1637     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1638     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1639     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1640     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1641     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1642     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
1643     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
1644   };
1645 
1646   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
1647   if( zIn[i] ){
1648     zResult[0] = toupper(zIn[i]);
1649     for(j=1; j<4 && zIn[i]; i++){
1650       int code = iCode[zIn[i]&0x7f];
1651       if( code>0 ){
1652         zResult[j++] = code + '0';
1653       }
1654     }
1655     while( j<4 ){
1656       zResult[j++] = '0';
1657     }
1658     zResult[j] = 0;
1659   }else{
1660     strcpy(zResult, "?000");
1661   }
1662 }
1663 
1664 /*
1665 ** computes the number of different characters between the soundex value fo 2 strings
1666 */
differenceFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)1667 static void differenceFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
1668   char zResult1[8];
1669   char zResult2[8];
1670   char *zR1 = zResult1;
1671   char *zR2 = zResult2;
1672   int rVal = 0;
1673   int i = 0;
1674   const u8 *zIn1;
1675   const u8 *zIn2;
1676 
1677   assert( argc==2 );
1678 
1679   if( sqlite3_value_type(argv[0])==SQLITE_NULL || sqlite3_value_type(argv[1])==SQLITE_NULL ){
1680     sqlite3_result_null(context);
1681     return;
1682   }
1683 
1684   zIn1 = (u8*)sqlite3_value_text(argv[0]);
1685   zIn2 = (u8*)sqlite3_value_text(argv[1]);
1686 
1687   soundex(zIn1, zR1);
1688   soundex(zIn2, zR2);
1689 
1690   for(i=0; i<4; ++i){
1691     if( sqliteCharVal((unsigned char *)zR1)==sqliteCharVal((unsigned char *)zR2) )
1692       ++rVal;
1693     sqliteNextChar(zR1);
1694     sqliteNextChar(zR2);
1695   }
1696   sqlite3_result_int(context, rVal);
1697 }
1698 #endif
1699 
1700 /*
1701 ** This function registered all of the above C functions as SQL
1702 ** functions.  This should be the only routine in this file with
1703 ** external linkage.
1704 */
RegisterExtensionFunctions(sqlite3 * db)1705 int RegisterExtensionFunctions(sqlite3 *db){
1706   static const struct FuncDef {
1707      char *zName;
1708      signed char nArg;
1709      u8 argType;           /* 0: none.  1: db  2: (-1) */
1710      u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
1711      u8 needCollSeq;
1712      void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
1713   } aFuncs[] = {
1714     /* math.h */
1715     { "acos",               1, 0, SQLITE_UTF8,    0, acosFunc  },
1716     { "asin",               1, 0, SQLITE_UTF8,    0, asinFunc  },
1717     { "atan",               1, 0, SQLITE_UTF8,    0, atanFunc  },
1718     { "atn2",               2, 0, SQLITE_UTF8,    0, atn2Func  },
1719     /* XXX alias */
1720     { "atan2",              2, 0, SQLITE_UTF8,    0, atn2Func  },
1721     { "acosh",              1, 0, SQLITE_UTF8,    0, acoshFunc  },
1722     { "asinh",              1, 0, SQLITE_UTF8,    0, asinhFunc  },
1723     { "atanh",              1, 0, SQLITE_UTF8,    0, atanhFunc  },
1724 
1725     { "difference",         2, 0, SQLITE_UTF8,    0, differenceFunc},
1726     { "degrees",            1, 0, SQLITE_UTF8,    0, rad2degFunc  },
1727     { "radians",            1, 0, SQLITE_UTF8,    0, deg2radFunc  },
1728 
1729     { "cos",                1, 0, SQLITE_UTF8,    0, cosFunc  },
1730     { "sin",                1, 0, SQLITE_UTF8,    0, sinFunc },
1731     { "tan",                1, 0, SQLITE_UTF8,    0, tanFunc },
1732     { "cot",                1, 0, SQLITE_UTF8,    0, cotFunc },
1733     { "cosh",               1, 0, SQLITE_UTF8,    0, coshFunc  },
1734     { "sinh",               1, 0, SQLITE_UTF8,    0, sinhFunc },
1735     { "tanh",               1, 0, SQLITE_UTF8,    0, tanhFunc },
1736     { "coth",               1, 0, SQLITE_UTF8,    0, cothFunc },
1737 
1738     { "exp",                1, 0, SQLITE_UTF8,    0, expFunc  },
1739     { "log",                1, 0, SQLITE_UTF8,    0, logFunc  },
1740     { "log10",              1, 0, SQLITE_UTF8,    0, log10Func  },
1741     { "power",              2, 0, SQLITE_UTF8,    0, powerFunc  },
1742     { "sign",               1, 0, SQLITE_UTF8,    0, signFunc },
1743     { "sqrt",               1, 0, SQLITE_UTF8,    0, sqrtFunc },
1744     { "square",             1, 0, SQLITE_UTF8,    0, squareFunc },
1745 
1746     { "ceil",               1, 0, SQLITE_UTF8,    0, ceilFunc },
1747     { "floor",              1, 0, SQLITE_UTF8,    0, floorFunc },
1748 
1749     { "pi",                 0, 0, SQLITE_UTF8,    1, piFunc },
1750 
1751 
1752     /* string */
1753     { "replicate",          2, 0, SQLITE_UTF8,    0, replicateFunc },
1754     { "charindex",          2, 0, SQLITE_UTF8,    0, charindexFunc },
1755     { "charindex",          3, 0, SQLITE_UTF8,    0, charindexFunc },
1756     { "leftstr",            2, 0, SQLITE_UTF8,    0, leftFunc },
1757     { "rightstr",           2, 0, SQLITE_UTF8,    0, rightFunc },
1758 #ifndef HAVE_TRIM
1759     { "ltrim",              1, 0, SQLITE_UTF8,    0, ltrimFunc },
1760     { "rtrim",              1, 0, SQLITE_UTF8,    0, rtrimFunc },
1761     { "trim",               1, 0, SQLITE_UTF8,    0, trimFunc },
1762     { "replace",            3, 0, SQLITE_UTF8,    0, replaceFunc },
1763 #endif
1764     { "reverse",            1, 0, SQLITE_UTF8,    0, reverseFunc },
1765     { "proper",             1, 0, SQLITE_UTF8,    0, properFunc },
1766     { "padl",               2, 0, SQLITE_UTF8,    0, padlFunc },
1767     { "padr",               2, 0, SQLITE_UTF8,    0, padrFunc },
1768     { "padc",               2, 0, SQLITE_UTF8,    0, padcFunc },
1769     { "strfilter",          2, 0, SQLITE_UTF8,    0, strfilterFunc },
1770 
1771   };
1772   /* Aggregate functions */
1773   static const struct FuncDefAgg {
1774     char *zName;
1775     signed char nArg;
1776     u8 argType;
1777     u8 needCollSeq;
1778     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
1779     void (*xFinalize)(sqlite3_context*);
1780   } aAggs[] = {
1781     { "stdev",            1, 0, 0, varianceStep, stdevFinalize  },
1782     { "variance",         1, 0, 0, varianceStep, varianceFinalize  },
1783     { "mode",             1, 0, 0, modeStep,     modeFinalize  },
1784     { "median",           1, 0, 0, modeStep,     medianFinalize  },
1785     { "lower_quartile",   1, 0, 0, modeStep,     lower_quartileFinalize  },
1786     { "upper_quartile",   1, 0, 0, modeStep,     upper_quartileFinalize  },
1787   };
1788   int i;
1789 
1790   for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
1791     void *pArg = 0;
1792     switch( aFuncs[i].argType ){
1793       case 1: pArg = db; break;
1794       case 2: pArg = (void *)(-1); break;
1795     }
1796     //sqlite3CreateFunc
1797     /* LMH no error checking */
1798     sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
1799         aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
1800 #if 0
1801     if( aFuncs[i].needCollSeq ){
1802       struct FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
1803           strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
1804       if( pFunc && aFuncs[i].needCollSeq ){
1805         pFunc->needCollSeq = 1;
1806       }
1807     }
1808 #endif
1809   }
1810 
1811   for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
1812     void *pArg = 0;
1813     switch( aAggs[i].argType ){
1814       case 1: pArg = db; break;
1815       case 2: pArg = (void *)(-1); break;
1816     }
1817     //sqlite3CreateFunc
1818     /* LMH no error checking */
1819     sqlite3_create_function(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
1820         pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
1821 #if 0
1822     if( aAggs[i].needCollSeq ){
1823       struct FuncDefAgg *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
1824           strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
1825       if( pFunc && aAggs[i].needCollSeq ){
1826         pFunc->needCollSeq = 1;
1827       }
1828     }
1829 #endif
1830   }
1831   return 0;
1832 }
1833 
1834 #ifdef COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE
sqlite3_extension_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)1835 int sqlite3_extension_init(
1836     sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi){
1837   SQLITE_EXTENSION_INIT2(pApi);
1838   RegisterExtensionFunctions(db);
1839   return 0;
1840 }
1841 #endif /* COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE */
1842 
map_make(cmp_func cmp)1843 map map_make(cmp_func cmp){
1844   map r;
1845   r.cmp=cmp;
1846   r.base = 0;
1847 
1848   return r;
1849 }
1850 
xcalloc(size_t nmemb,size_t size,char * s)1851 void* xcalloc(size_t nmemb, size_t size, char* s){
1852   void* ret = calloc(nmemb, size);
1853   return ret;
1854 }
1855 
xfree(void * p)1856 void xfree(void* p){
1857   free(p);
1858 }
1859 
node_insert(node ** n,cmp_func cmp,void * e)1860 void node_insert(node** n, cmp_func cmp, void *e){
1861   int c;
1862   node* nn;
1863   if(*n==0){
1864     nn = (node*)xcalloc(1,sizeof(node), "for node");
1865     nn->data = e;
1866     nn->count = 1;
1867     *n=nn;
1868   }else{
1869     c=cmp((*n)->data,e);
1870     if(0==c){
1871       ++((*n)->count);
1872       xfree(e);
1873     }else if(c>0){
1874       /* put it right here */
1875       node_insert(&((*n)->l), cmp, e);
1876     }else{
1877       node_insert(&((*n)->r), cmp, e);
1878     }
1879   }
1880 }
1881 
map_insert(map * m,void * e)1882 void map_insert(map *m, void *e){
1883   node_insert(&(m->base), m->cmp, e);
1884 }
1885 
node_iterate(node * n,map_iterator iter,void * p)1886 void node_iterate(node *n, map_iterator iter, void* p){
1887   if(n){
1888     if(n->l)
1889       node_iterate(n->l, iter, p);
1890     iter(n->data, n->count, p);
1891     if(n->r)
1892       node_iterate(n->r, iter, p);
1893   }
1894 }
1895 
map_iterate(map * m,map_iterator iter,void * p)1896 void map_iterate(map *m, map_iterator iter, void* p){
1897   node_iterate(m->base, iter, p);
1898 }
1899 
node_destroy(node * n)1900 void node_destroy(node *n){
1901   if(0!=n){
1902     xfree(n->data);
1903     if(n->l)
1904       node_destroy(n->l);
1905     if(n->r)
1906       node_destroy(n->r);
1907 
1908     xfree(n);
1909   }
1910 }
1911 
map_destroy(map * m)1912 void map_destroy(map *m){
1913   node_destroy(m->base);
1914 }
1915 
int_cmp(const void * a,const void * b)1916 int int_cmp(const void *a, const void *b){
1917   int64_t aa = *(int64_t *)(a);
1918   int64_t bb = *(int64_t *)(b);
1919   /* printf("cmp %d <=> %d\n",aa,bb); */
1920   if(aa==bb)
1921     return 0;
1922   else if(aa<bb)
1923     return -1;
1924   else
1925     return 1;
1926 }
1927 
double_cmp(const void * a,const void * b)1928 int double_cmp(const void *a, const void *b){
1929   double aa = *(double *)(a);
1930   double bb = *(double *)(b);
1931   /* printf("cmp %d <=> %d\n",aa,bb); */
1932   if(aa==bb)
1933     return 0;
1934   else if(aa<bb)
1935     return -1;
1936   else
1937     return 1;
1938 }
1939