]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/libopensrf/osrf_json_object.c
Patch from Scott McKellar:
[OpenSRF.git] / src / libopensrf / osrf_json_object.c
1 /*
2 Copyright (C) 2006  Georgia Public Library Service 
3 Bill Erickson <billserickson@gmail.com>
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14 */
15
16 #include <stdlib.h>
17 #include <ctype.h>
18 #include <errno.h>
19 #include <limits.h>
20 #include <opensrf/log.h>
21 #include <opensrf/osrf_json.h>
22 #include <opensrf/osrf_json_utils.h>
23
24 /* cleans up an object if it is morphing another object, also
25  * verifies that the appropriate storage container exists where appropriate */
26 #define JSON_INIT_CLEAR(_obj_, newtype)         \
27         if( _obj_->type == JSON_HASH && newtype != JSON_HASH ) {                        \
28                 osrfHashFree(_obj_->value.h);                   \
29                 _obj_->value.h = NULL;                                  \
30 } else if( _obj_->type == JSON_ARRAY && newtype != JSON_ARRAY ) {       \
31                 osrfListFree(_obj_->value.l);                   \
32                 _obj_->value.l = NULL;                                  \
33 } else if( _obj_->type == JSON_STRING || _obj_->type == JSON_NUMBER ) { \
34                 free(_obj_->value.s);                                           \
35                 _obj_->value.s = NULL;                                  \
36 } \
37         _obj_->type = newtype;\
38         if( newtype == JSON_HASH && _obj_->value.h == NULL ) {  \
39                 _obj_->value.h = osrfNewHash();         \
40                 _obj_->value.h->freeItem = _jsonFreeHashItem; \
41 } else if( newtype == JSON_ARRAY && _obj_->value.l == NULL ) {  \
42                 _obj_->value.l = osrfNewList();         \
43                 _obj_->value.l->freeItem = _jsonFreeListItem;\
44 }
45
46 static int unusedObjCapture = 0;
47 static int unusedObjRelease = 0;
48 static int mallocObjCreate = 0;
49 static int currentListLen = 0;
50
51 union unusedObjUnion{
52
53         union unusedObjUnion* next;
54         jsonObject obj;
55 };
56 typedef union unusedObjUnion unusedObj;
57
58 // We maintain a free list of jsonObjects that are available
59 // for use, in order to reduce the churning through
60 // malloc() and free().
61
62 static unusedObj* freeObjList = NULL;
63
64 static void add_json_to_buffer( const jsonObject* obj, growing_buffer * buf );
65
66 /**
67  * Return all unused jsonObjects to the heap
68  * @return Nothing
69  */
70 void jsonObjectFreeUnused( void ) {
71
72         unusedObj* temp;
73         while( freeObjList ) {
74                 temp = freeObjList->next;
75                 free( freeObjList );
76                 freeObjList = temp;
77         }
78 }
79
80 jsonObject* jsonNewObject(const char* data) {
81
82         jsonObject* o;
83
84         if( freeObjList ) {
85                 o = (jsonObject*) freeObjList;
86                 freeObjList = freeObjList->next;
87         unusedObjRelease++;
88         currentListLen--;
89         } else {
90                 OSRF_MALLOC( o, sizeof(jsonObject) );
91         mallocObjCreate++;
92     }
93
94         o->size = 0;
95         o->classname = NULL;
96         o->parent = NULL;
97
98         if(data) {
99                 o->type = JSON_STRING;
100                 o->value.s = strdup(data);
101         } else {
102                 o->type = JSON_NULL;
103                 o->value.s = NULL;
104         }
105
106         return o;
107 }
108
109 jsonObject* jsonNewObjectFmt(const char* data, ...) {
110
111         jsonObject* o;
112
113         if( freeObjList ) {
114                 o = (jsonObject*) freeObjList;
115                 freeObjList = freeObjList->next;
116         unusedObjRelease++;
117         currentListLen--;
118         } else {
119                 OSRF_MALLOC( o, sizeof(jsonObject) );
120         mallocObjCreate++;
121     }
122
123         o->size = 0;
124         o->classname = NULL;
125         o->parent = NULL;
126
127         if(data) {
128                 VA_LIST_TO_STRING(data);
129                 o->type = JSON_STRING;
130                 o->value.s = strdup(VA_BUF);
131         }
132         else {
133                 o->type = JSON_NULL;
134                 o->value.s = NULL;
135         }
136         
137         return o;
138 }
139
140 jsonObject* jsonNewNumberObject( double num ) {
141         jsonObject* o = jsonNewObject(NULL);
142         o->type = JSON_NUMBER;
143         o->value.s = doubleToString( num );
144         return o;
145 }
146
147 /**
148  * Creates a new number object from a numeric string
149  */
150 jsonObject* jsonNewNumberStringObject( const char* numstr ) {
151         if( !numstr )
152                 numstr = "0";
153         else if( !jsonIsNumeric( numstr ) )
154                 return NULL;
155
156         jsonObject* o = jsonNewObject(NULL);
157         o->type = JSON_NUMBER;
158         o->value.s = strdup( numstr );
159         return o;
160 }
161
162 jsonObject* jsonNewBoolObject(int val) {
163     jsonObject* o = jsonNewObject(NULL);
164     o->type = JSON_BOOL;
165     jsonSetBool(o, val);
166     return o;
167 }
168
169 jsonObject* jsonNewObjectType(int type) {
170         jsonObject* o = jsonNewObject(NULL);
171         o->type = type;
172         return o;
173 }
174
175 void jsonObjectFree( jsonObject* o ) {
176
177         if(!o || o->parent) return;
178         free(o->classname);
179
180         switch(o->type) {
181                 case JSON_HASH          : osrfHashFree(o->value.h); break;
182                 case JSON_ARRAY : osrfListFree(o->value.l); break;
183                 case JSON_STRING        : free(o->value.s); break;
184                 case JSON_NUMBER        : free(o->value.s); break;
185         }
186
187         // Stick the old jsonObject onto a free list
188         // for potential reuse
189         
190         unusedObj* unused = (unusedObj*) o;
191         unused->next = freeObjList;
192         freeObjList = unused;
193
194     unusedObjCapture++;
195     currentListLen++;
196     if (unusedObjCapture > 1 && !(unusedObjCapture % 1000))
197         osrfLogDebug( OSRF_LOG_MARK, "Objects malloc()'d: %d, Reusable objects captured: %d, Objects reused: %d, Current List Length: %d", mallocObjCreate, unusedObjCapture, unusedObjRelease, currentListLen );
198 }
199
200 static void _jsonFreeHashItem(char* key, void* item){
201         if(!item) return;
202         jsonObject* o = (jsonObject*) item;
203         o->parent = NULL; /* detach the item */
204         jsonObjectFree(o);
205 }
206 static void _jsonFreeListItem(void* item){
207         if(!item) return;
208         jsonObject* o = (jsonObject*) item;
209         o->parent = NULL; /* detach the item */
210         jsonObjectFree(o);
211 }
212
213 void jsonSetBool(jsonObject* bl, int val) {
214     if(!bl) return;
215     JSON_INIT_CLEAR(bl, JSON_BOOL);
216     bl->value.b = val;
217 }
218
219 unsigned long jsonObjectPush(jsonObject* o, jsonObject* newo) {
220     if(!o) return -1;
221     if(!newo) newo = jsonNewObject(NULL);
222         JSON_INIT_CLEAR(o, JSON_ARRAY);
223         newo->parent = o;
224         osrfListPush( o->value.l, newo );
225         o->size = o->value.l->size;
226         return o->size;
227 }
228
229 unsigned long jsonObjectSetIndex(jsonObject* dest, unsigned long index, jsonObject* newObj) {
230     if(!dest) return -1;
231     if(!newObj) newObj = jsonNewObject(NULL);
232         JSON_INIT_CLEAR(dest, JSON_ARRAY);
233         newObj->parent = dest;
234         osrfListSet( dest->value.l, newObj, index );
235         dest->size = dest->value.l->size;
236         return dest->value.l->size;
237 }
238
239 unsigned long jsonObjectSetKey( jsonObject* o, const char* key, jsonObject* newo) {
240     if(!o) return -1;
241     if(!newo) newo = jsonNewObject(NULL);
242         JSON_INIT_CLEAR(o, JSON_HASH);
243         newo->parent = o;
244         osrfHashSet( o->value.h, newo, key );
245         o->size = o->value.h->size;
246         return o->size;
247 }
248
249 jsonObject* jsonObjectGetKey( jsonObject* obj, const char* key ) {
250         if(!(obj && obj->type == JSON_HASH && obj->value.h && key)) return NULL;
251         return osrfHashGet( obj->value.h, key);
252 }
253
254 const jsonObject* jsonObjectGetKeyConst( const jsonObject* obj, const char* key ) {
255         if(!(obj && obj->type == JSON_HASH && obj->value.h && key)) return NULL;
256         return osrfHashGet( obj->value.h, key);
257 }
258
259 char* jsonObjectToJSON( const jsonObject* obj ) {
260         jsonObject* obj2 = jsonObjectEncodeClass( obj );
261         char* json = jsonObjectToJSONRaw(obj2);
262         jsonObjectFree(obj2);
263         return json;
264 }
265
266 char* jsonObjectToJSONRaw( const jsonObject* obj ) {
267         if(!obj) return NULL;
268         growing_buffer* buf = buffer_init(32);
269         add_json_to_buffer( obj, buf );
270         return buffer_release( buf );
271 }
272
273 static void add_json_to_buffer( const jsonObject* obj, growing_buffer * buf ) {
274
275         switch(obj->type) {
276
277                 case JSON_BOOL :
278                         if(obj->value.b) OSRF_BUFFER_ADD(buf, "true"); 
279                         else OSRF_BUFFER_ADD(buf, "false"); 
280                         break;
281
282                 case JSON_NUMBER: {
283                         if(obj->value.s) OSRF_BUFFER_ADD( buf, obj->value.s );
284                         else OSRF_BUFFER_ADD_CHAR( buf, '0' );
285                         break;
286                 }
287
288                 case JSON_NULL:
289                         OSRF_BUFFER_ADD(buf, "null");
290                         break;
291
292                 case JSON_STRING:
293                         OSRF_BUFFER_ADD_CHAR(buf, '"');
294                         char* data = obj->value.s;
295                         int len = strlen(data);
296                         
297                         char* output = uescape(data, len, 1);
298                         OSRF_BUFFER_ADD(buf, output);
299                         free(output);
300                         OSRF_BUFFER_ADD_CHAR(buf, '"');
301                         break;
302                         
303                 case JSON_ARRAY: {
304                         OSRF_BUFFER_ADD_CHAR(buf, '[');
305                         if( obj->value.l ) {
306                                 int i;
307                                 for( i = 0; i != obj->value.l->size; i++ ) {
308                                         if(i > 0) OSRF_BUFFER_ADD(buf, ",");
309                                         add_json_to_buffer( OSRF_LIST_GET_INDEX(obj->value.l, i), buf );
310                                 }
311                         }
312                         OSRF_BUFFER_ADD_CHAR(buf, ']');
313                         break;
314                 }
315
316                 case JSON_HASH: {
317
318                         OSRF_BUFFER_ADD_CHAR(buf, '{');
319                         osrfHashIterator* itr = osrfNewHashIterator(obj->value.h);
320                         jsonObject* item;
321                         int i = 0;
322
323                         while( (item = osrfHashIteratorNext(itr)) ) {
324                                 if(i++ > 0) OSRF_BUFFER_ADD(buf, ",");
325                                 buffer_fadd(buf, "\"%s\":", itr->current);
326                                 add_json_to_buffer( item, buf );
327                         }
328
329                         osrfHashIteratorFree(itr);
330                         OSRF_BUFFER_ADD_CHAR(buf, '}');
331                         break;
332                 }
333         }
334 }
335
336
337 jsonIterator* jsonNewIterator(const jsonObject* obj) {
338         if(!obj) return NULL;
339         jsonIterator* itr;
340         OSRF_MALLOC(itr, sizeof(jsonIterator));
341
342         itr->obj                = (jsonObject*) obj;
343         itr->index      = 0;
344         itr->key                = NULL;
345
346         if( obj->type == JSON_HASH )
347                 itr->hashItr = osrfNewHashIterator(obj->value.h);
348         
349         return itr;
350 }
351
352 void jsonIteratorFree(jsonIterator* itr) {
353         if(!itr) return;
354         free(itr->key);
355         osrfHashIteratorFree(itr->hashItr);
356         free(itr);
357 }
358
359 jsonObject* jsonIteratorNext(jsonIterator* itr) {
360         if(!(itr && itr->obj)) return NULL;
361         if( itr->obj->type == JSON_HASH ) {
362                 if(!itr->hashItr) return NULL;
363                 jsonObject* item = osrfHashIteratorNext(itr->hashItr);
364                 free(itr->key);
365                 itr->key = strdup(itr->hashItr->current);
366                 return item;
367         } else {
368                 return jsonObjectGetIndex( itr->obj, itr->index++ );
369         }
370 }
371
372 int jsonIteratorHasNext(const jsonIterator* itr) {
373         if(!(itr && itr->obj)) return 0;
374         if( itr->obj->type == JSON_HASH )
375                 return osrfHashIteratorHasNext( itr->hashItr );
376         return (itr->index < itr->obj->size) ? 1 : 0;
377 }
378
379 jsonObject* jsonObjectGetIndex( const jsonObject* obj, unsigned long index ) {
380         if(!obj) return NULL;
381         return (obj->type == JSON_ARRAY) ? 
382         (OSRF_LIST_GET_INDEX(obj->value.l, index)) : NULL;
383 }
384
385
386
387 unsigned long jsonObjectRemoveIndex(jsonObject* dest, unsigned long index) {
388         if( dest && dest->type == JSON_ARRAY ) {
389                 osrfListRemove(dest->value.l, index);
390                 return dest->value.l->size;
391         }
392         return -1;
393 }
394
395
396 unsigned long jsonObjectRemoveKey( jsonObject* dest, const char* key) {
397         if( dest && key && dest->type == JSON_HASH ) {
398                 osrfHashRemove(dest->value.h, key);
399                 return 1;
400         }
401         return -1;
402 }
403
404 /**
405  Allocate a buffer and format a specified numeric value into it.
406  Caller is responsible for freeing the buffer.
407 **/
408 char* doubleToString( double num ) {
409         
410         char buf[ 64 ];
411         size_t len = snprintf(buf, sizeof( buf ), "%.30g", num) + 1;
412         if( len < sizeof( buf ) )
413                 return strdup( buf );
414         else
415         {
416                 // Need a bigger buffer (should never be necessary)
417                 
418                 char* bigger_buff = safe_malloc( len + 1 );
419                 (void) snprintf(bigger_buff, len + 1, "%.30g", num);
420                 return bigger_buff;
421         }
422 }
423
424 char* jsonObjectGetString(const jsonObject* obj) {
425         if(obj)
426         {
427                 if( obj->type == JSON_STRING )
428                         return obj->value.s;
429                 else if( obj->type == JSON_NUMBER )
430                         return obj->value.s ? obj->value.s : "0";
431                 else
432                         return NULL;
433         }
434         else
435                 return NULL;
436 }
437
438 double jsonObjectGetNumber( const jsonObject* obj ) {
439         return (obj && obj->type == JSON_NUMBER && obj->value.s)
440                         ? strtod( obj->value.s, NULL ) : 0;
441 }
442
443 void jsonObjectSetString(jsonObject* dest, const char* string) {
444         if(!(dest && string)) return;
445         JSON_INIT_CLEAR(dest, JSON_STRING);
446         dest->value.s = strdup(string);
447 }
448
449 /**
450  Turn a jsonObject into a JSON_NUMBER (if it isn't already one) and store
451  a specified numeric string in it.  If the string is not numeric,
452  store the equivalent of zero, and return an error status.
453 **/
454 int jsonObjectSetNumberString(jsonObject* dest, const char* string) {
455         if(!(dest && string)) return -1;
456         JSON_INIT_CLEAR(dest, JSON_NUMBER);
457
458         if( jsonIsNumeric( string ) ) {
459                 dest->value.s = strdup(string);
460                 return 0;
461         }
462         else {
463                 dest->value.s = NULL;  // equivalent to zero
464                 return -1;
465         }
466 }
467
468 void jsonObjectSetNumber(jsonObject* dest, double num) {
469         if(!dest) return;
470         JSON_INIT_CLEAR(dest, JSON_NUMBER);
471         dest->value.s = doubleToString( num );
472 }
473
474 void jsonObjectSetClass(jsonObject* dest, const char* classname ) {
475         if(!(dest && classname)) return;
476         free(dest->classname);
477         dest->classname = strdup(classname);
478 }
479 const char* jsonObjectGetClass(const jsonObject* dest) {
480     if(!dest) return NULL;
481     return dest->classname;
482 }
483
484 jsonObject* jsonObjectClone( const jsonObject* o ) {
485     if(!o) return jsonNewObject(NULL);
486
487     int i;
488     jsonObject* arr; 
489     jsonObject* hash; 
490     jsonIterator* itr;
491     jsonObject* tmp;
492     jsonObject* result = NULL;
493
494     switch(o->type) {
495         case JSON_NULL:
496             result = jsonNewObject(NULL);
497             break;
498         case JSON_STRING:
499             result = jsonNewObject(jsonObjectGetString(o));
500             break;
501         case JSON_NUMBER:
502                         result = jsonNewObject( o->value.s );
503                         result->type = JSON_NUMBER;
504             break;
505         case JSON_BOOL:
506             result = jsonNewBoolObject(jsonBoolIsTrue((jsonObject*) o));
507             break;
508         case JSON_ARRAY:
509             arr = jsonNewObject(NULL);
510             arr->type = JSON_ARRAY;
511             for(i=0; i < o->size; i++) 
512                 jsonObjectPush(arr, jsonObjectClone(jsonObjectGetIndex(o, i)));
513             result = arr;
514             break;
515         case JSON_HASH:
516             hash = jsonNewObject(NULL);
517             hash->type = JSON_HASH;
518             itr = jsonNewIterator(o);
519             while( (tmp = jsonIteratorNext(itr)) )
520                 jsonObjectSetKey(hash, itr->key, jsonObjectClone(tmp));
521             jsonIteratorFree(itr);
522             result = hash;
523             break;
524     }
525
526     jsonObjectSetClass(result, jsonObjectGetClass(o));
527     return result;
528 }
529
530 int jsonBoolIsTrue( const jsonObject* boolObj ) {
531     if( boolObj && boolObj->type == JSON_BOOL && boolObj->value.b )
532         return 1;
533     return 0;
534 }
535
536
537 char* jsonObjectToSimpleString( const jsonObject* o ) {
538         if(!o) return NULL;
539
540         char* value = NULL;
541
542         switch( o->type ) {
543
544                 case JSON_NUMBER:
545                         value = strdup( o->value.s ? o->value.s : "0" );
546                         break;
547
548                 case JSON_STRING:
549                         value = strdup(o->value.s);
550         }
551
552         return value;
553 }
554
555 /**
556  Return 1 if the string is numeric, otherwise return 0.
557  This validation follows the rules defined by the grammar at:
558  http://www.json.org/
559  **/
560 int jsonIsNumeric( const char* s ) {
561
562         if( !s || !*s ) return 0;
563
564         const char* p = s;
565
566         // skip leading minus sign, if present (leading plus sign not allowed)
567
568         if( '-' == *p )
569                 ++p;
570
571         // There must be at least one digit to the left of the decimal
572
573         if( isdigit( (unsigned char) *p ) ) {
574                 if( '0' == *p++ ) {
575
576                         // If the first digit is zero, it must be the
577                         // only digit to the lerft of the decimal
578
579                         if( isdigit( (unsigned char) *p ) )
580                                 return 0;
581                 }
582                 else {
583
584                         // Skip oer the following digits
585
586                         while( isdigit( (unsigned char) *p ) ) ++p;
587                 }
588         }
589         else
590                 return 0;
591
592         if( !*p )
593                 return 1;             // integer
594
595         if( '.' == *p ) {
596
597                 ++p;
598
599                 // If there is a decimal point, there must be
600                 // at least one digit to the right of it
601
602                 if( isdigit( (unsigned char) *p ) )
603                         ++p;
604                 else
605                         return 0;
606
607                 // skip over contiguous digits
608
609                 while( isdigit( (unsigned char) *p ) ) ++p;
610         }
611
612         if( ! *p )
613                 return 1;  // decimal fraction, no exponent
614         else if( *p != 'e' && *p != 'E' )
615                 return 0;  // extra junk, no exponent
616         else
617                 ++p;
618
619         // If we get this far, we have the beginnings of an exponent.
620         // Skip over optional sign of exponent.
621
622         if( '-' == *p || '+' == *p )
623                 ++p;
624
625         // There must be at least one digit in the exponent
626         
627         if( isdigit( (unsigned char) *p ) )
628                 ++p;
629         else
630                 return 0;
631
632         // skip over contiguous digits
633
634         while( isdigit( (unsigned char) *p ) ) ++p;
635
636         if( *p )
637                 return 0;  // extra junk
638         else
639                 return 1;  // number with exponent
640 }
641
642 /**
643  Allocate and reformat a numeric string into one that is valid
644  by JSON rules.  If the string is not numeric, return NULL.
645  Caller is responsible for freeing the buffer.
646  **/
647 char* jsonScrubNumber( const char* s ) {
648         if( !s || !*s ) return NULL;
649
650         growing_buffer* buf = buffer_init( 64 );
651
652         // Skip leading white space, if present
653
654         while( isspace( (unsigned char) *s ) ) ++s;
655
656         // Skip leading plus sign, if present, but keep a minus
657
658         if( '-' == *s )
659         {
660                 buffer_add_char( buf, '-' );
661                 ++s;
662         }
663         else if( '+' == *s )
664                 ++s;
665
666         if( '\0' == *s ) {
667                 // No digits found
668
669                 buffer_free( buf );
670                 return NULL;
671         }
672         // Skip any leading zeros
673
674         while( '0' == *s ) ++s;
675
676         // Capture digits to the left of the decimal,
677         // and note whether there are any.
678
679         int left_digit = 0;  // boolean
680
681         if( isdigit( (unsigned char) *s ) ) {
682                 buffer_add_char( buf, *s++ );
683                 left_digit = 1;
684         }
685         
686         while( isdigit( (unsigned char) *s  ) )
687                 buffer_add_char( buf, *s++ );
688
689         // Now we expect to see a decimal point,
690         // an exponent, or end-of-string.
691
692         switch( *s )
693         {
694                 case '\0' :
695                         break;
696                 case '.' :
697                 {
698                         // Add a single leading zero, if we need to
699
700                         if( ! left_digit )
701                                 buffer_add_char( buf, '0' );
702                         buffer_add_char( buf, '.' );
703                         ++s;
704
705                         if( ! left_digit && ! isdigit( (unsigned char) *s ) )
706                         {
707                                 // No digits on either side of decimal
708
709                                 buffer_free( buf );
710                                 return NULL;
711                         }
712
713                         // Collect digits to right of decimal
714
715                         while( isdigit( (unsigned char) *s ) )
716                                 buffer_add_char( buf, *s++ );
717
718                         break;
719                 }
720                 case 'e' :
721                 case 'E' :
722
723                         // Exponent; we'll deal with it later, but
724                         // meanwhile make sure we have something
725                         // to its left
726
727                         if( ! left_digit )
728                                 buffer_add_char( buf, '1' );
729                         break;
730                 default :
731
732                         // Unexpected character; bail out
733
734                         buffer_free( buf );
735                         return NULL;
736         }
737
738         if( '\0' == *s )    // Are we done yet?
739                 return buffer_release( buf );
740
741         if( 'e' != *s && 'E' != *s ) {
742
743                 // Unexpected character: bail out
744
745                 buffer_free( buf );
746                 return NULL;
747         }
748
749         // We have an exponent.  Load the e or E,
750         // and the sign if there is one.
751
752         buffer_add_char( buf, *s++ );
753
754         if( '+' == *s || '-' == *s )
755                 buffer_add_char( buf, *s++ );
756
757         // Collect digits of the exponent
758
759         while( isdigit( (unsigned char) *s ) )
760                 buffer_add_char( buf, *s++ );
761
762         // There better not be anything left
763
764         if( *s ) {
765                 buffer_free( buf );
766                 return NULL;
767         }
768
769         return buffer_release( buf );
770 }