-
-
Notifications
You must be signed in to change notification settings - Fork 249
/
oj.c
2234 lines (2042 loc) · 73.3 KB
/
oj.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* oj.c
* Copyright (c) 2012, Peter Ohler
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of Peter Ohler nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include "oj.h"
#include "parse.h"
#include "hash.h"
#include "odd.h"
#include "encode.h"
typedef struct _YesNoOpt {
VALUE sym;
char *attr;
} *YesNoOpt;
void Init_oj();
VALUE Oj = Qnil;
ID oj_add_value_id;
ID oj_array_append_id;
ID oj_array_end_id;
ID oj_array_start_id;
ID oj_as_json_id;
ID oj_error_id;
ID oj_file_id;
ID oj_fileno_id;
ID oj_ftype_id;
ID oj_hash_end_id;
ID oj_hash_key_id;
ID oj_hash_set_id;
ID oj_hash_start_id;
ID oj_iconv_id;
ID oj_instance_variables_id;
ID oj_json_create_id;
ID oj_length_id;
ID oj_new_id;
ID oj_pos_id;
ID oj_read_id;
ID oj_readpartial_id;
ID oj_replace_id;
ID oj_stat_id;
ID oj_string_id;
ID oj_to_hash_id;
ID oj_to_json_id;
ID oj_to_s_id;
ID oj_to_sym_id;
ID oj_to_time_id;
ID oj_tv_nsec_id;
ID oj_tv_sec_id;
ID oj_tv_usec_id;
ID oj_utc_offset_id;
ID oj_write_id;
VALUE oj_bag_class;
VALUE oj_bigdecimal_class;
VALUE oj_cstack_class;
VALUE oj_date_class;
VALUE oj_datetime_class;
VALUE oj_parse_error_class;
VALUE oj_stream_writer_class;
VALUE oj_string_writer_class;
VALUE oj_stringio_class;
VALUE oj_struct_class;
VALUE oj_time_class;
VALUE oj_slash_string;
static VALUE allow_gc_sym;
static VALUE ascii_only_sym;
static VALUE ascii_sym;
static VALUE auto_define_sym;
static VALUE auto_sym;
static VALUE bigdecimal_as_decimal_sym;
static VALUE bigdecimal_load_sym;
static VALUE bigdecimal_sym;
static VALUE circular_sym;
static VALUE class_cache_sym;
static VALUE compat_sym;
static VALUE create_id_sym;
static VALUE escape_mode_sym;
static VALUE float_prec_sym;
static VALUE float_sym;
static VALUE indent_sym;
static VALUE json_sym;
static VALUE mode_sym;
static VALUE newline_sym;
static VALUE nilnil_sym;
static VALUE null_sym;
static VALUE object_sym;
static VALUE quirks_mode_sym;
static VALUE ruby_sym;
static VALUE sec_prec_sym;
static VALUE strict_sym;
static VALUE symbol_keys_sym;
static VALUE time_format_sym;
static VALUE unix_sym;
static VALUE use_to_json_sym;
static VALUE xmlschema_sym;
static VALUE xss_safe_sym;
static VALUE array_nl_sym;
static VALUE create_additions_sym;
static VALUE object_nl_sym;
static VALUE space_before_sym;
static VALUE space_sym;
static VALUE symbolize_names_sym;
static VALUE mimic = Qnil;
#if HAS_ENCODING_SUPPORT
rb_encoding *oj_utf8_encoding = 0;
#else
VALUE oj_utf8_encoding = Qnil;
#endif
#if USE_PTHREAD_MUTEX
pthread_mutex_t oj_cache_mutex;
#elif USE_RB_MUTEX
VALUE oj_cache_mutex = Qnil;
#endif
static const char json_class[] = "json_class";
struct _Options oj_default_options = {
0, // indent
No, // circular
No, // auto_define
No, // sym_key
JSONEsc, // escape_mode
ObjectMode, // mode
Yes, // class_cache
UnixTime, // time_format
Yes, // bigdec_as_num
AutoDec, // bigdec_load
Yes, // to_json
No, // nilnil
Yes, // allow_gc
Yes, // quirks_mode
json_class, // create_id
10, // create_id_len
9, // sec_prec
0, // dump_opts
15, // float_prec
"%0.15g", // float_fmt
};
static VALUE define_mimic_json(int argc, VALUE *argv, VALUE self);
/* call-seq: default_options() => Hash
*
* Returns the default load and dump options as a Hash. The options are
* - indent: [Fixnum] number of spaces to indent each element in an JSON document, zero is no newline between JSON elements, negative indicates no newline between top level JSON elements in a stream
* - circular: [true|false|nil] support circular references while dumping
* - auto_define: [true|false|nil] automatically define classes if they do not exist
* - symbol_keys: [true|false|nil] use symbols instead of strings for hash keys
* - escape_mode: [:newline|:json|:xss_safe|:ascii|nil] determines the characters to escape
* - class_cache: [true|false|nil] cache classes for faster parsing (if dynamically modifying classes or reloading classes then don't use this)
* - mode: [:object|:strict|:compat|:null] load and dump modes to use for JSON
* - time_format: [:unix|:xmlschema|:ruby] time format when dumping in :compat mode
* - bigdecimal_as_decimal: [true|false|nil] dump BigDecimal as a decimal number or as a String
* - bigdecimal_load: [:bigdecimal|:float|:auto] load decimals as BigDecimal instead of as a Float. :auto pick the most precise for the number of digits.
* - create_id: [String|nil] create id for json compatible object encoding, default is 'json_create'
* - second_precision: [Fixnum|nil] number of digits after the decimal when dumping the seconds portion of time
* - float_precision: [Fixnum|nil] number of digits of precision when dumping floats, 0 indicates use Ruby
* - use_to_json: [true|false|nil] call to_json() methods on dump, default is false
* - nilnil: [true|false|nil] if true a nil input to load will return nil and not raise an Exception
* - allow_gc: [true|false|nil] allow or prohibit GC during parsing, default is true (allow)
* - quirks_mode: [true,|false|nil] Allow single JSON values instead of documents, default is true (allow)
* @return [Hash] all current option settings.
*/
static VALUE
get_def_opts(VALUE self) {
VALUE opts = rb_hash_new();
rb_hash_aset(opts, indent_sym, INT2FIX(oj_default_options.indent));
rb_hash_aset(opts, sec_prec_sym, INT2FIX(oj_default_options.sec_prec));
rb_hash_aset(opts, circular_sym, (Yes == oj_default_options.circular) ? Qtrue : ((No == oj_default_options.circular) ? Qfalse : Qnil));
rb_hash_aset(opts, class_cache_sym, (Yes == oj_default_options.class_cache) ? Qtrue : ((No == oj_default_options.class_cache) ? Qfalse : Qnil));
rb_hash_aset(opts, auto_define_sym, (Yes == oj_default_options.auto_define) ? Qtrue : ((No == oj_default_options.auto_define) ? Qfalse : Qnil));
rb_hash_aset(opts, symbol_keys_sym, (Yes == oj_default_options.sym_key) ? Qtrue : ((No == oj_default_options.sym_key) ? Qfalse : Qnil));
rb_hash_aset(opts, bigdecimal_as_decimal_sym, (Yes == oj_default_options.bigdec_as_num) ? Qtrue : ((No == oj_default_options.bigdec_as_num) ? Qfalse : Qnil));
rb_hash_aset(opts, use_to_json_sym, (Yes == oj_default_options.to_json) ? Qtrue : ((No == oj_default_options.to_json) ? Qfalse : Qnil));
rb_hash_aset(opts, nilnil_sym, (Yes == oj_default_options.nilnil) ? Qtrue : ((No == oj_default_options.nilnil) ? Qfalse : Qnil));
rb_hash_aset(opts, allow_gc_sym, (Yes == oj_default_options.allow_gc) ? Qtrue : ((No == oj_default_options.allow_gc) ? Qfalse : Qnil));
rb_hash_aset(opts, quirks_mode_sym, (Yes == oj_default_options.quirks_mode) ? Qtrue : ((No == oj_default_options.quirks_mode) ? Qfalse : Qnil));
rb_hash_aset(opts, float_prec_sym, INT2FIX(oj_default_options.float_prec));
switch (oj_default_options.mode) {
case StrictMode: rb_hash_aset(opts, mode_sym, strict_sym); break;
case CompatMode: rb_hash_aset(opts, mode_sym, compat_sym); break;
case NullMode: rb_hash_aset(opts, mode_sym, null_sym); break;
case ObjectMode:
default: rb_hash_aset(opts, mode_sym, object_sym); break;
}
switch (oj_default_options.escape_mode) {
case NLEsc: rb_hash_aset(opts, escape_mode_sym, newline_sym); break;
case JSONEsc: rb_hash_aset(opts, escape_mode_sym, json_sym); break;
case XSSEsc: rb_hash_aset(opts, escape_mode_sym, xss_safe_sym); break;
case ASCIIEsc: rb_hash_aset(opts, escape_mode_sym, ascii_sym); break;
default: rb_hash_aset(opts, escape_mode_sym, json_sym); break;
}
switch (oj_default_options.time_format) {
case XmlTime: rb_hash_aset(opts, time_format_sym, xmlschema_sym); break;
case RubyTime: rb_hash_aset(opts, time_format_sym, ruby_sym); break;
case UnixTime:
default: rb_hash_aset(opts, time_format_sym, unix_sym); break;
}
switch (oj_default_options.bigdec_load) {
case BigDec: rb_hash_aset(opts, bigdecimal_load_sym, bigdecimal_sym);break;
case FloatDec: rb_hash_aset(opts, bigdecimal_load_sym, float_sym); break;
case AutoDec:
default: rb_hash_aset(opts, bigdecimal_load_sym, auto_sym); break;
}
rb_hash_aset(opts, create_id_sym, (0 == oj_default_options.create_id) ? Qnil : rb_str_new2(oj_default_options.create_id));
return opts;
}
/* call-seq: default_options=(opts)
*
* Sets the default options for load and dump.
* @param [Hash] opts options to change
* @param [Fixnum] :indent number of spaces to indent each element in an JSON document
* @param [true|false|nil] :circular support circular references while dumping
* @param [true|false|nil] :auto_define automatically define classes if they do not exist
* @param [true|false|nil] :symbol_keys convert hash keys to symbols
* @param [true|false|nil] :class_cache cache classes for faster parsing
* @param [:newline|:json|:xss_safe|:ascii|nil] :escape mode encodes all high-bit characters as
* escaped sequences if :ascii, :json is standand UTF-8 JSON encoding,
* :newline is the same as :json but newlines are not escaped,
* and :xss_safe escapes &, <, and >, and some others.
* @param [true|false|nil] :bigdecimal_as_decimal dump BigDecimal as a decimal number or as a String
* @param [:bigdecimal|:float|:auto|nil] :bigdecimal_load load decimals as BigDecimal instead of as a Float. :auto pick the most precise for the number of digits.
* @param [:object|:strict|:compat|:null] load and dump mode to use for JSON
* :strict raises an exception when a non-supported Object is
* encountered. :compat attempts to extract variable values from an
* Object using to_json() or to_hash() then it walks the Object's
* variables if neither is found. The :object mode ignores to_hash()
* and to_json() methods and encodes variables using code internal to
* the Oj gem. The :null mode ignores non-supported Objects and
* replaces them with a null.
* @param [:unix|:xmlschema|:ruby] time format when dumping in :compat mode
* :unix decimal number denoting the number of seconds since 1/1/1970,
* :xmlschema date-time format taken from XML Schema as a String,
* :ruby Time.to_s formatted String
* @param [String|nil] :create_id create id for json compatible object encoding
* @param [Fixnum|nil] :second_precision number of digits after the decimal when dumping the seconds portion of time
* @param [Fixnum|nil] :float_precision number of digits of precision when dumping floats, 0 indicates use Ruby
* @param [true|false|nil] :use_to_json call to_json() methods on dump, default is false
* @param [true|false|nil] :nilnil if true a nil input to load will return nil and not raise an Exception
* @param [true|false|nil] :allow_gc allow or prohibit GC during parsing, default is true (allow)
* @param [true|false|nil] :quirks_mode allow single JSON values instead of documents, default is true (allow)
* @return [nil]
*/
static VALUE
set_def_opts(VALUE self, VALUE opts) {
struct _YesNoOpt ynos[] = {
{ circular_sym, &oj_default_options.circular },
{ auto_define_sym, &oj_default_options.auto_define },
{ symbol_keys_sym, &oj_default_options.sym_key },
{ class_cache_sym, &oj_default_options.class_cache },
{ bigdecimal_as_decimal_sym, &oj_default_options.bigdec_as_num },
{ use_to_json_sym, &oj_default_options.to_json },
{ nilnil_sym, &oj_default_options.nilnil },
{ allow_gc_sym, &oj_default_options.allow_gc },
{ quirks_mode_sym, &oj_default_options.quirks_mode },
{ Qnil, 0 }
};
YesNoOpt o;
VALUE v;
Check_Type(opts, T_HASH);
v = rb_hash_aref(opts, indent_sym);
if (Qnil != v) {
Check_Type(v, T_FIXNUM);
oj_default_options.indent = FIX2INT(v);
}
v = rb_hash_aref(opts, float_prec_sym);
if (Qnil != v) {
int n;
Check_Type(v, T_FIXNUM);
n = FIX2INT(v);
if (0 >= n) {
*oj_default_options.float_fmt = '\0';
oj_default_options.float_prec = 0;
} else {
if (20 < n) {
n = 20;
}
sprintf(oj_default_options.float_fmt, "%%0.%dg", n);
oj_default_options.float_prec = n;
}
}
v = rb_hash_aref(opts, sec_prec_sym);
if (Qnil != v) {
int n;
Check_Type(v, T_FIXNUM);
n = FIX2INT(v);
if (0 > n) {
n = 0;
} else if (9 < n) {
n = 9;
}
oj_default_options.sec_prec = n;
}
v = rb_hash_lookup(opts, mode_sym);
if (Qnil == v) {
// ignore
} else if (object_sym == v) {
oj_default_options.mode = ObjectMode;
} else if (strict_sym == v) {
oj_default_options.mode = StrictMode;
} else if (compat_sym == v) {
oj_default_options.mode = CompatMode;
} else if (null_sym == v) {
oj_default_options.mode = NullMode;
} else {
rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.");
}
v = rb_hash_lookup(opts, time_format_sym);
if (Qnil == v) {
// ignore
} else if (unix_sym == v) {
oj_default_options.time_format = UnixTime;
} else if (xmlschema_sym == v) {
oj_default_options.time_format = XmlTime;
} else if (ruby_sym == v) {
oj_default_options.time_format = RubyTime;
} else {
rb_raise(rb_eArgError, ":time_format must be :unix, :xmlschema, or :ruby.");
}
v = rb_hash_lookup(opts, escape_mode_sym);
if (Qnil == v) {
// ignore
} else if (newline_sym == v) {
oj_default_options.escape_mode = NLEsc;
} else if (json_sym == v) {
oj_default_options.escape_mode = JSONEsc;
} else if (xss_safe_sym == v) {
oj_default_options.escape_mode = XSSEsc;
} else if (ascii_sym == v) {
oj_default_options.escape_mode = ASCIIEsc;
} else {
rb_raise(rb_eArgError, ":encoding must be :json, :xss_safe, or :ascii.");
}
v = rb_hash_lookup(opts, bigdecimal_load_sym);
if (Qnil == v) {
// ignore
} else if (bigdecimal_sym == v || Qtrue == v) {
oj_default_options.bigdec_load = BigDec;
} else if (float_sym == v) {
oj_default_options.bigdec_load = FloatDec;
} else if (auto_sym == v || Qfalse == v) {
oj_default_options.bigdec_load = AutoDec;
} else {
rb_raise(rb_eArgError, ":bigdecimal_load must be :bigdecimal, :float, or :auto.");
}
if (Qtrue == rb_funcall(opts, rb_intern("has_key?"), 1, create_id_sym)) {
if (0 != oj_default_options.create_id) {
if (json_class != oj_default_options.create_id) {
xfree((char*)oj_default_options.create_id);
}
oj_default_options.create_id = 0;
oj_default_options.create_id_len = 0;
}
v = rb_hash_lookup(opts, create_id_sym);
if (Qnil != v) {
size_t len = RSTRING_LEN(v) + 1;
oj_default_options.create_id = ALLOC_N(char, len);
strcpy((char*)oj_default_options.create_id, StringValuePtr(v));
oj_default_options.create_id_len = len - 1;
}
}
for (o = ynos; 0 != o->attr; o++) {
if (Qtrue != rb_funcall(opts, rb_intern("has_key?"), 1, o->sym)) {
continue;
}
if (Qnil != (v = rb_hash_lookup(opts, o->sym))) {
if (Qtrue == v) {
*o->attr = Yes;
} else if (Qfalse == v) {
*o->attr = No;
} else {
rb_raise(rb_eArgError, "%s must be true, false, or nil.", rb_id2name(SYM2ID(o->sym)));
}
}
}
// This is here only for backwards compatibility with the original Oj.
v = rb_hash_lookup(opts, ascii_only_sym);
if (Qtrue == v) {
oj_default_options.escape_mode = ASCIIEsc;
} else if (Qfalse == v) {
oj_default_options.escape_mode = JSONEsc;
}
return Qnil;
}
void
oj_parse_options(VALUE ropts, Options copts) {
struct _YesNoOpt ynos[] = {
{ circular_sym, &copts->circular },
{ auto_define_sym, &copts->auto_define },
{ symbol_keys_sym, &copts->sym_key },
{ class_cache_sym, &copts->class_cache },
{ bigdecimal_as_decimal_sym, &copts->bigdec_as_num },
{ use_to_json_sym, &copts->to_json },
{ nilnil_sym, &copts->nilnil },
{ allow_gc_sym, &copts->allow_gc },
{ quirks_mode_sym, &copts->quirks_mode },
{ Qnil, 0 }
};
YesNoOpt o;
if (rb_cHash == rb_obj_class(ropts)) {
VALUE v;
if (Qnil != (v = rb_hash_lookup(ropts, indent_sym))) {
if (rb_cFixnum != rb_obj_class(v)) {
rb_raise(rb_eArgError, ":indent must be a Fixnum.");
}
copts->indent = NUM2INT(v);
}
if (Qnil != (v = rb_hash_lookup(ropts, float_prec_sym))) {
int n;
if (rb_cFixnum != rb_obj_class(v)) {
rb_raise(rb_eArgError, ":float_precision must be a Fixnum.");
}
Check_Type(v, T_FIXNUM);
n = FIX2INT(v);
if (0 >= n) {
*copts->float_fmt = '\0';
copts->float_prec = 0;
} else {
if (20 < n) {
n = 20;
}
sprintf(copts->float_fmt, "%%0.%dg", n);
copts->float_prec = n;
}
}
if (Qnil != (v = rb_hash_lookup(ropts, sec_prec_sym))) {
int n;
if (rb_cFixnum != rb_obj_class(v)) {
rb_raise(rb_eArgError, ":second_precision must be a Fixnum.");
}
n = NUM2INT(v);
if (0 > n) {
n = 0;
} else if (9 < n) {
n = 9;
}
copts->sec_prec = n;
}
if (Qnil != (v = rb_hash_lookup(ropts, mode_sym))) {
if (object_sym == v) {
copts->mode = ObjectMode;
} else if (strict_sym == v) {
copts->mode = StrictMode;
} else if (compat_sym == v) {
copts->mode = CompatMode;
} else if (null_sym == v) {
copts->mode = NullMode;
} else {
rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.");
}
}
if (Qnil != (v = rb_hash_lookup(ropts, time_format_sym))) {
if (unix_sym == v) {
copts->time_format = UnixTime;
} else if (xmlschema_sym == v) {
copts->time_format = XmlTime;
} else if (ruby_sym == v) {
copts->time_format = RubyTime;
} else {
rb_raise(rb_eArgError, ":time_format must be :unix, :xmlschema, or :ruby.");
}
}
if (Qnil != (v = rb_hash_lookup(ropts, escape_mode_sym))) {
if (newline_sym == v) {
copts->escape_mode = NLEsc;
} else if (json_sym == v) {
copts->escape_mode = JSONEsc;
} else if (xss_safe_sym == v) {
copts->escape_mode = XSSEsc;
} else if (ascii_sym == v) {
copts->escape_mode = ASCIIEsc;
} else {
rb_raise(rb_eArgError, ":encoding must be :newline, :json, :xss_safe, or :ascii.");
}
}
if (Qnil != (v = rb_hash_lookup(ropts, bigdecimal_load_sym))) {
if (bigdecimal_sym == v || Qtrue == v) {
copts->bigdec_load = BigDec;
} else if (float_sym == v) {
copts->bigdec_load = FloatDec;
} else if (auto_sym == v || Qfalse == v) {
copts->bigdec_load = AutoDec;
} else {
rb_raise(rb_eArgError, ":bigdecimal_load must be :bigdecimal, :float, or :auto.");
}
}
if (Qtrue == rb_funcall(ropts, rb_intern("has_key?"), 1, create_id_sym)) {
v = rb_hash_lookup(ropts, create_id_sym);
if (Qnil == v) {
if (json_class != oj_default_options.create_id) {
xfree((char*)oj_default_options.create_id);
}
copts->create_id = 0;
copts->create_id_len = 0;
} else if (T_STRING == rb_type(v)) {
size_t len = RSTRING_LEN(v);
const char *str = StringValuePtr(v);
if (len != copts->create_id_len ||
0 != strcmp(copts->create_id, str)) {
copts->create_id = ALLOC_N(char, len + 1);
strcpy((char*)copts->create_id, str);
copts->create_id_len = len;
}
} else {
rb_raise(rb_eArgError, ":create_id must be string.");
}
}
for (o = ynos; 0 != o->attr; o++) {
if (Qnil != (v = rb_hash_lookup(ropts, o->sym))) {
if (Qtrue == v) {
*o->attr = Yes;
} else if (Qfalse == v) {
*o->attr = No;
} else {
rb_raise(rb_eArgError, "%s must be true or false.", rb_id2name(SYM2ID(o->sym)));
}
}
}
// This is here only for backwards compatibility with the original Oj.
v = rb_hash_lookup(ropts, ascii_only_sym);
if (Qtrue == v) {
copts->escape_mode = ASCIIEsc;
} else if (Qfalse == v) {
copts->escape_mode = JSONEsc;
}
}
}
/* Document-method: strict_load
* call-seq: strict_load(json, options) => Hash, Array, String, Fixnum, Float, true, false, or nil
*
* Parses a JSON document String into an Hash, Array, String, Fixnum, Float,
* true, false, or nil. It parses using a mode that is strict in that it maps
* each primitive JSON type to a similar Ruby type. The :create_id is not
* honored in this mode. Note that a Ruby Hash is used to represent the JSON
* Object type. These two are not the same since the JSON Object type can have
* repeating entries with the same key and Ruby Hash can not.
*
* When used with a document that has multiple JSON elements the block, if
* any, will be yielded to. If no block then the last element read will be
* returned.
*
* Raises an exception if the JSON is malformed or the classes specified are not
* valid. If the input is not a valid JSON document (an empty string is not a
* valid JSON document) an exception is raised.
*
* @param [String|IO] json JSON String or an Object that responds to read()
* @param [Hash] options load options (same as default_options)
*/
/* Document-method: compat_load
* call-seq: compat_load(json, options) => Object, Hash, Array, String, Fixnum, Float, true, false, or nil
*
* Parses a JSON document String into an Object, Hash, Array, String, Fixnum,
* Float, true, false, or nil. It parses using a mode that is generally
* compatible with other Ruby JSON parsers in that it will create objects based
* on the :create_id value. It is not compatible in every way to every other
* parser though as each parser has it's own variations.
*
* When used with a document that has multiple JSON elements the block, if
* any, will be yielded to. If no block then the last element read will be
* returned.
*
* Raises an exception if the JSON is malformed or the classes specified are not
* valid. If the input is not a valid JSON document (an empty string is not a
* valid JSON document) an exception is raised.
*
* @param [String|IO] json JSON String or an Object that responds to read()
* @param [Hash] options load options (same as default_options)
*/
/* Document-method: object_load
* call-seq: object_load(json, options) => Object, Hash, Array, String, Fixnum, Float, true, false, or nil
*
* Parses a JSON document String into an Object, Hash, Array, String, Fixnum,
* Float, true, false, or nil. In the :object mode the JSON should have been
* generated by Oj.dump(). The parser will reconstitute the original marshalled
* or dumped Object. The :auto_define and :circular options have meaning with
* this parsing mode.
*
* When used with a document that has multiple JSON elements the block, if
* any, will be yielded to. If no block then the last element read will be
* returned.
*
* Raises an exception if the JSON is malformed or the classes specified are not
* valid. If the input is not a valid JSON document (an empty string is not a
* valid JSON document) an exception is raised.
*
* Note: Oj is not able to automatically deserialize all classes that are a
* subclass of a Ruby Exception. Only exception that take one required string
* argument in the initialize() method are supported. This is an example of how
* to write an Exception subclass that supports both a single string intializer
* and an Exception as an argument. Additional optional arguments can be added
* as well.
*
* The reason for this restriction has to do with a design decision on the part
* of the Ruby developers. Exceptions are special Objects. They do not follow the
* rules of other Objects. Exceptions have 'mesg' and a 'bt' attribute. Note that
* these are not '@mesg' and '@bt'. They can not be set using the normal C or
* Ruby calls. The only way I have found to set the 'mesg' attribute is through
* the initializer. Unfortunately that means any subclass that provides a
* different initializer can not be automatically decoded. A way around this is
* to use a create function but this example shows an alternative.
*
* @param [String|IO] json JSON String or an Object that responds to read()
* @param [Hash] options load options (same as default_options)
*/
/* call-seq: load(json, options) => Object, Hash, Array, String, Fixnum, Float, true, false, or nil
*
* Parses a JSON document String into a Object, Hash, Array, String, Fixnum,
* Float, true, false, or nil according to the default mode or the mode
* specified. Raises an exception if the JSON is malformed or the classes
* specified are not valid. If the string input is not a valid JSON document (an
* empty string is not a valid JSON document) an exception is raised.
*
* When used with a document that has multiple JSON elements the block, if
* any, will be yielded to. If no block then the last element read will be
* returned.
*
* This parser operates on string and will attempt to load files into memory if
* a file object is passed as the first argument. A stream input will be parsed
* using a stream parser but others use the slightly faster string parser.
*
* @param [String|IO] json JSON String or an Object that responds to read()
* @param [Hash] options load options (same as default_options)
*/
static VALUE
load(int argc, VALUE *argv, VALUE self) {
Mode mode = oj_default_options.mode;
if (1 > argc) {
rb_raise(rb_eArgError, "Wrong number of arguments to load().");
}
if (2 <= argc) {
VALUE ropts = argv[1];
VALUE v;
if (Qnil != (v = rb_hash_lookup(ropts, mode_sym))) {
if (object_sym == v) {
mode = ObjectMode;
} else if (strict_sym == v) {
mode = StrictMode;
} else if (compat_sym == v) {
mode = CompatMode;
} else if (null_sym == v) {
mode = NullMode;
} else {
rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.");
}
}
}
switch (mode) {
case StrictMode:
return oj_strict_parse(argc, argv, self);
case NullMode:
case CompatMode:
return oj_compat_parse(argc, argv, self);
case ObjectMode:
default:
break;
}
return oj_object_parse(argc, argv, self);
}
/* Document-method: load_file
* call-seq: load_file(path, options) => Object, Hash, Array, String, Fixnum, Float, true, false, or nil
*
* Parses a JSON document String into a Object, Hash, Array, String, Fixnum,
* Float, true, false, or nil according to the default mode or the mode
* specified. Raises an exception if the JSON is malformed or the classes
* specified are not valid. If the string input is not a valid JSON document (an
* empty string is not a valid JSON document) an exception is raised.
*
* When used with a document that has multiple JSON elements the block, if
* any, will be yielded to. If no block then the last element read will be
* returned.
*
* If the input file is not a valid JSON document (an empty file is not a valid
* JSON document) an exception is raised.
*
* This is a stream based parser which allows a large or huge file to be loaded
* without pulling the whole file into memory.
*
* @param [String] path path to a file containing a JSON document
* @param [Hash] options load options (same as default_options)
*/
static VALUE
load_file(int argc, VALUE *argv, VALUE self) {
char *path;
int fd;
Mode mode = oj_default_options.mode;
struct _ParseInfo pi;
if (1 > argc) {
rb_raise(rb_eArgError, "Wrong number of arguments to load().");
}
Check_Type(*argv, T_STRING);
pi.options = oj_default_options;
pi.handler = Qnil;
if (2 <= argc) {
VALUE ropts = argv[1];
VALUE v;
if (Qnil != (v = rb_hash_lookup(ropts, mode_sym))) {
if (object_sym == v) {
mode = ObjectMode;
} else if (strict_sym == v) {
mode = StrictMode;
} else if (compat_sym == v) {
mode = CompatMode;
} else if (null_sym == v) {
mode = NullMode;
} else {
rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.");
}
}
}
path = StringValuePtr(*argv);
if (0 == (fd = open(path, O_RDONLY))) {
rb_raise(rb_eIOError, "%s", strerror(errno));
}
switch (mode) {
case StrictMode:
oj_set_strict_callbacks(&pi);
return oj_pi_sparse(argc, argv, &pi, fd);
case NullMode:
case CompatMode:
oj_set_compat_callbacks(&pi);
return oj_pi_sparse(argc, argv, &pi, fd);
case ObjectMode:
default:
break;
}
oj_set_object_callbacks(&pi);
return oj_pi_sparse(argc, argv, &pi, fd);
}
/* call-seq: safe_load(doc)
*
* Loads a JSON document in strict mode with :auto_define and :symbol_keys
* turned off. This function should be safe to use with JSON received on an
* unprotected public interface.
*
* @param [String|IO] doc JSON String or IO to load
* @return [Hash|Array|String|Fixnum|Bignum|BigDecimal|nil|True|False]
*/
static VALUE
safe_load(VALUE self, VALUE doc) {
struct _ParseInfo pi;
VALUE args[1];
pi.options = oj_default_options;
pi.options.auto_define = No;
pi.options.sym_key = No;
pi.options.mode = StrictMode;
oj_set_strict_callbacks(&pi);
*args = doc;
return oj_pi_parse(1, args, &pi, 0, 0, 1);
}
/* call-seq: saj_parse(handler, io)
*
* Parses an IO stream or file containing a JSON document. Raises an exception
* if the JSON is malformed. This is a callback parser that calls the methods in
* the handler if they exist. A sample is the Oj::Saj class which can be used as
* a base class for the handler.
*
* @param [Oj::Saj] handler responds to Oj::Saj methods
* @param [IO|String] io IO Object to read from
*/
/* call-seq: sc_parse(handler, io)
*
* Parses an IO stream or file containing a JSON document. Raises an exception
* if the JSON is malformed. This is a callback parser (Simple Callback Parser)
* that calls the methods in the handler if they exist. A sample is the
* Oj::ScHandler class which can be used as a base class for the handler. This
* callback parser is slightly more efficient than the Saj callback parser and
* requires less argument checking.
*
* @param [Oj::ScHandler] handler responds to Oj::ScHandler methods
* @param [IO|String] io IO Object to read from
*/
/* call-seq: dump(obj, options) => json-string
*
* Dumps an Object (obj) to a string.
* @param [Object] obj Object to serialize as an JSON document String
* @param [Hash] options same as default_options
*/
static VALUE
dump(int argc, VALUE *argv, VALUE self) {
char buf[4096];
struct _Out out;
struct _Options copts = oj_default_options;
VALUE rstr;
if (2 == argc) {
oj_parse_options(argv[1], &copts);
}
out.buf = buf;
out.end = buf + sizeof(buf) - 10;
out.allocated = 0;
oj_dump_obj_to_json(*argv, &copts, &out);
if (0 == out.buf) {
rb_raise(rb_eNoMemError, "Not enough memory.");
}
rstr = rb_str_new2(out.buf);
rstr = oj_encode(rstr);
if (out.allocated) {
xfree(out.buf);
}
return rstr;
}
/* call-seq: to_file(file_path, obj, options)
*
* Dumps an Object to the specified file.
* @param [String] file_path file path to write the JSON document to
* @param [Object] obj Object to serialize as an JSON document String
* @param [Hash] options formating options
* @param [Fixnum] :indent format expected
* @param [true|false] :circular allow circular references, default: false
*/
static VALUE
to_file(int argc, VALUE *argv, VALUE self) {
struct _Options copts = oj_default_options;
if (3 == argc) {
oj_parse_options(argv[2], &copts);
}
Check_Type(*argv, T_STRING);
oj_write_obj_to_file(argv[1], StringValuePtr(*argv), &copts);
return Qnil;
}
/* call-seq: to_stream(io, obj, options)
*
* Dumps an Object to the specified IO stream.
* @param [IO] io IO stream to write the JSON document to
* @param [Object] obj Object to serialize as an JSON document String
* @param [Hash] options formating options
* @param [Fixnum] :indent format expected
* @param [true|false] :circular allow circular references, default: false
*/
static VALUE
to_stream(int argc, VALUE *argv, VALUE self) {
struct _Options copts = oj_default_options;
if (3 == argc) {
oj_parse_options(argv[2], &copts);
}
oj_write_obj_to_stream(argv[1], *argv, &copts);
return Qnil;
}
/* call-seq: register_odd(clas, create_object, create_method, *members)
*
* Registers a class as special. This is useful for working around subclasses of
* primitive types as is done with ActiveSupport classes. The use of this
* function should be limited to just classes that can not be handled in the
* normal way. It is not intended as a hook for changing the output of all
* classes as it is not optimized for large numbers of classes.
*
* @param [Class] clas Class to be made special
* @param [Object] create_object object to call the create method on
* @param [Symbol] create_method method on the clas that will create a new
* instance of the clas when given all the member values in the
* order specified.
* @param [Symbol|String] members methods used to get the member values from
* instances of the clas
*/
static VALUE
register_odd(int argc, VALUE *argv, VALUE self) {
if (3 > argc) {
rb_raise(rb_eArgError, "incorrect number of arguments.");
}
Check_Type(argv[0], T_CLASS);
Check_Type(argv[2], T_SYMBOL);
if (MAX_ODD_ARGS < argc - 2) {
rb_raise(rb_eArgError, "too many members.");
}
oj_reg_odd(argv[0], argv[1], argv[2], argc - 3, argv + 3);
return Qnil;
}
static void
str_writer_free(void *ptr) {
StrWriter sw;
if (0 == ptr) {
return;
}
sw = (StrWriter)ptr;
xfree(sw->out.buf);
xfree(sw->types);
xfree(ptr);
}
/* Document-class: Oj::StringWriter
*
* Supports building a JSON document one element at a time. Build the document
* by pushing values into the document. Pushing an array or an object will
* create that element in the JSON document and subsequent pushes will add the
* elements to that array or object until a pop() is called. When complete
* calling to_s() will return the JSON document. Note tha calling to_s() before
* construction is complete will return the document in it's current state.
*/
static void
str_writer_init(StrWriter sw) {
sw->opts = oj_default_options;
sw->depth = 0;
sw->types = ALLOC_N(char, 256);
sw->types_end = sw->types + 256;
*sw->types = '\0';
sw->keyWritten = 0;
sw->out.buf = ALLOC_N(char, 4096);
sw->out.end = sw->out.buf + 4086;
sw->out.allocated = 1;
sw->out.cur = sw->out.buf;
*sw->out.cur = '\0';
sw->out.circ_cnt = 0;
sw->out.hash_cnt = 0;
sw->out.opts = &sw->opts;
sw->out.indent = sw->opts.indent;
sw->out.depth = 0;
}