oj 2.18.3 → 3.13.14

Sign up to get free protection for your applications and to get access to all the features.
Files changed (182) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +1324 -0
  3. data/README.md +51 -204
  4. data/RELEASE_NOTES.md +61 -0
  5. data/ext/oj/buf.h +49 -72
  6. data/ext/oj/cache.c +326 -0
  7. data/ext/oj/cache.h +21 -0
  8. data/ext/oj/cache8.c +61 -64
  9. data/ext/oj/cache8.h +12 -39
  10. data/ext/oj/circarray.c +37 -68
  11. data/ext/oj/circarray.h +16 -42
  12. data/ext/oj/code.c +221 -0
  13. data/ext/oj/code.h +40 -0
  14. data/ext/oj/compat.c +231 -107
  15. data/ext/oj/custom.c +1125 -0
  16. data/ext/oj/debug.c +132 -0
  17. data/ext/oj/dump.c +935 -2513
  18. data/ext/oj/dump.h +108 -0
  19. data/ext/oj/dump_compat.c +936 -0
  20. data/ext/oj/dump_leaf.c +164 -0
  21. data/ext/oj/dump_object.c +761 -0
  22. data/ext/oj/dump_strict.c +410 -0
  23. data/ext/oj/encode.h +7 -42
  24. data/ext/oj/encoder.c +43 -0
  25. data/ext/oj/err.c +40 -54
  26. data/ext/oj/err.h +52 -46
  27. data/ext/oj/extconf.rb +21 -30
  28. data/ext/oj/fast.c +1097 -1080
  29. data/ext/oj/intern.c +301 -0
  30. data/ext/oj/intern.h +26 -0
  31. data/ext/oj/mimic_json.c +893 -0
  32. data/ext/oj/object.c +549 -620
  33. data/ext/oj/odd.c +155 -167
  34. data/ext/oj/odd.h +37 -63
  35. data/ext/oj/oj.c +1661 -2063
  36. data/ext/oj/oj.h +341 -270
  37. data/ext/oj/parse.c +974 -737
  38. data/ext/oj/parse.h +105 -97
  39. data/ext/oj/parser.c +1526 -0
  40. data/ext/oj/parser.h +90 -0
  41. data/ext/oj/rails.c +1504 -0
  42. data/ext/oj/rails.h +18 -0
  43. data/ext/oj/reader.c +141 -163
  44. data/ext/oj/reader.h +75 -113
  45. data/ext/oj/resolve.c +45 -93
  46. data/ext/oj/resolve.h +7 -34
  47. data/ext/oj/rxclass.c +143 -0
  48. data/ext/oj/rxclass.h +26 -0
  49. data/ext/oj/saj.c +447 -511
  50. data/ext/oj/saj2.c +348 -0
  51. data/ext/oj/scp.c +91 -138
  52. data/ext/oj/sparse.c +793 -644
  53. data/ext/oj/stream_writer.c +331 -0
  54. data/ext/oj/strict.c +145 -109
  55. data/ext/oj/string_writer.c +493 -0
  56. data/ext/oj/trace.c +72 -0
  57. data/ext/oj/trace.h +28 -0
  58. data/ext/oj/usual.c +1254 -0
  59. data/ext/oj/util.c +136 -0
  60. data/ext/oj/util.h +20 -0
  61. data/ext/oj/val_stack.c +62 -70
  62. data/ext/oj/val_stack.h +95 -129
  63. data/ext/oj/validate.c +51 -0
  64. data/ext/oj/wab.c +622 -0
  65. data/lib/oj/bag.rb +1 -0
  66. data/lib/oj/easy_hash.rb +17 -8
  67. data/lib/oj/error.rb +10 -11
  68. data/lib/oj/json.rb +176 -0
  69. data/lib/oj/mimic.rb +158 -19
  70. data/lib/oj/state.rb +132 -0
  71. data/lib/oj/version.rb +2 -2
  72. data/lib/oj.rb +1 -31
  73. data/pages/Advanced.md +22 -0
  74. data/pages/Compatibility.md +25 -0
  75. data/pages/Custom.md +23 -0
  76. data/pages/Encoding.md +65 -0
  77. data/pages/JsonGem.md +94 -0
  78. data/pages/Modes.md +161 -0
  79. data/pages/Options.md +327 -0
  80. data/pages/Parser.md +309 -0
  81. data/pages/Rails.md +167 -0
  82. data/pages/Security.md +20 -0
  83. data/pages/WAB.md +13 -0
  84. data/test/activerecord/result_test.rb +32 -0
  85. data/test/activesupport4/decoding_test.rb +108 -0
  86. data/test/activesupport4/encoding_test.rb +531 -0
  87. data/test/activesupport4/test_helper.rb +41 -0
  88. data/test/activesupport5/abstract_unit.rb +45 -0
  89. data/test/activesupport5/decoding_test.rb +133 -0
  90. data/test/activesupport5/encoding_test.rb +500 -0
  91. data/test/activesupport5/encoding_test_cases.rb +98 -0
  92. data/test/activesupport5/test_helper.rb +72 -0
  93. data/test/activesupport5/time_zone_test_helpers.rb +39 -0
  94. data/test/activesupport6/abstract_unit.rb +44 -0
  95. data/test/activesupport6/decoding_test.rb +133 -0
  96. data/test/activesupport6/encoding_test.rb +507 -0
  97. data/test/activesupport6/encoding_test_cases.rb +98 -0
  98. data/test/activesupport6/test_common.rb +17 -0
  99. data/test/activesupport6/test_helper.rb +163 -0
  100. data/test/activesupport6/time_zone_test_helpers.rb +39 -0
  101. data/test/activesupport7/abstract_unit.rb +49 -0
  102. data/test/activesupport7/decoding_test.rb +125 -0
  103. data/test/activesupport7/encoding_test.rb +486 -0
  104. data/test/activesupport7/encoding_test_cases.rb +104 -0
  105. data/test/activesupport7/time_zone_test_helpers.rb +47 -0
  106. data/test/bar.rb +9 -0
  107. data/test/baz.rb +16 -0
  108. data/test/bug.rb +11 -46
  109. data/test/foo.rb +69 -16
  110. data/test/helper.rb +10 -1
  111. data/test/isolated/shared.rb +12 -8
  112. data/test/isolated/test_mimic_rails_after.rb +3 -3
  113. data/test/isolated/test_mimic_rails_before.rb +3 -3
  114. data/test/json_gem/json_addition_test.rb +216 -0
  115. data/test/json_gem/json_common_interface_test.rb +153 -0
  116. data/test/json_gem/json_encoding_test.rb +107 -0
  117. data/test/json_gem/json_ext_parser_test.rb +20 -0
  118. data/test/json_gem/json_fixtures_test.rb +35 -0
  119. data/test/json_gem/json_generator_test.rb +397 -0
  120. data/test/json_gem/json_generic_object_test.rb +90 -0
  121. data/test/json_gem/json_parser_test.rb +470 -0
  122. data/test/json_gem/json_string_matching_test.rb +42 -0
  123. data/test/json_gem/test_helper.rb +26 -0
  124. data/test/mem.rb +33 -0
  125. data/test/perf.rb +1 -1
  126. data/test/perf_compat.rb +30 -28
  127. data/test/perf_dump.rb +50 -0
  128. data/test/perf_object.rb +1 -1
  129. data/test/perf_once.rb +58 -0
  130. data/test/perf_parser.rb +189 -0
  131. data/test/perf_scp.rb +11 -10
  132. data/test/perf_strict.rb +30 -19
  133. data/test/perf_wab.rb +131 -0
  134. data/test/prec.rb +23 -0
  135. data/test/sample.rb +0 -1
  136. data/test/sample_json.rb +1 -1
  137. data/test/test_compat.rb +219 -102
  138. data/test/test_custom.rb +533 -0
  139. data/test/test_fast.rb +107 -35
  140. data/test/test_file.rb +19 -25
  141. data/test/test_generate.rb +21 -0
  142. data/test/test_hash.rb +11 -1
  143. data/test/test_integer_range.rb +72 -0
  144. data/test/test_null.rb +376 -0
  145. data/test/test_object.rb +357 -70
  146. data/test/test_parser.rb +27 -0
  147. data/test/test_parser_saj.rb +245 -0
  148. data/test/test_parser_usual.rb +217 -0
  149. data/test/test_rails.rb +35 -0
  150. data/test/test_saj.rb +1 -1
  151. data/test/test_scp.rb +39 -2
  152. data/test/test_strict.rb +186 -7
  153. data/test/test_various.rb +160 -774
  154. data/test/test_wab.rb +307 -0
  155. data/test/test_writer.rb +90 -2
  156. data/test/tests.rb +24 -0
  157. data/test/tests_mimic.rb +14 -0
  158. data/test/tests_mimic_addition.rb +7 -0
  159. data/test/zoo.rb +13 -0
  160. metadata +194 -56
  161. data/ext/oj/hash.c +0 -163
  162. data/ext/oj/hash.h +0 -46
  163. data/ext/oj/hash_test.c +0 -512
  164. data/test/activesupport_datetime_test.rb +0 -23
  165. data/test/bug2.rb +0 -10
  166. data/test/bug3.rb +0 -46
  167. data/test/bug_fast.rb +0 -32
  168. data/test/bug_load.rb +0 -24
  169. data/test/crash.rb +0 -111
  170. data/test/curl/curl_oj.rb +0 -46
  171. data/test/curl/get_oj.rb +0 -24
  172. data/test/curl/just_curl.rb +0 -31
  173. data/test/curl/just_oj.rb +0 -51
  174. data/test/example.rb +0 -11
  175. data/test/io.rb +0 -48
  176. data/test/isolated/test_mimic_rails_datetime.rb +0 -27
  177. data/test/mod.rb +0 -16
  178. data/test/rails.rb +0 -50
  179. data/test/russian.rb +0 -18
  180. data/test/struct.rb +0 -29
  181. data/test/test_serializer.rb +0 -59
  182. data/test/write_timebars.rb +0 -31
data/ext/oj/rails.c ADDED
@@ -0,0 +1,1504 @@
1
+ // Copyright (c) 2017 Peter Ohler. All rights reserved.
2
+ // Licensed under the MIT License. See LICENSE file in the project root for license details.
3
+
4
+ #include "rails.h"
5
+
6
+ #include "code.h"
7
+ #include "encode.h"
8
+ #include "trace.h"
9
+ #include "util.h"
10
+
11
+ #define OJ_INFINITY (1.0 / 0.0)
12
+
13
+ // TBD keep static array of strings and functions to help with rails optimization
14
+ typedef struct _encoder {
15
+ struct _rOptTable ropts;
16
+ struct _options opts;
17
+ VALUE arg;
18
+ } * Encoder;
19
+
20
+ bool oj_rails_hash_opt = false;
21
+ bool oj_rails_array_opt = false;
22
+ bool oj_rails_float_opt = false;
23
+
24
+ extern void oj_mimic_json_methods(VALUE json);
25
+
26
+ static void dump_rails_val(VALUE obj, int depth, Out out, bool as_ok);
27
+
28
+ extern VALUE Oj;
29
+
30
+ static struct _rOptTable ropts = {0, 0, NULL};
31
+
32
+ static VALUE encoder_class = Qnil;
33
+ static bool escape_html = true;
34
+ static bool xml_time = true;
35
+
36
+ static ROpt create_opt(ROptTable rot, VALUE clas);
37
+
38
+ ROpt oj_rails_get_opt(ROptTable rot, VALUE clas) {
39
+ if (NULL == rot) {
40
+ rot = &ropts;
41
+ }
42
+ if (0 < rot->len) {
43
+ int lo = 0;
44
+ int hi = rot->len - 1;
45
+ int mid;
46
+ VALUE v;
47
+
48
+ if (clas < rot->table->clas || rot->table[hi].clas < clas) {
49
+ return NULL;
50
+ }
51
+ if (rot->table[lo].clas == clas) {
52
+ return rot->table;
53
+ }
54
+ if (rot->table[hi].clas == clas) {
55
+ return &rot->table[hi];
56
+ }
57
+ while (2 <= hi - lo) {
58
+ mid = (hi + lo) / 2;
59
+ v = rot->table[mid].clas;
60
+ if (v == clas) {
61
+ return &rot->table[mid];
62
+ }
63
+ if (v < clas) {
64
+ lo = mid;
65
+ } else {
66
+ hi = mid;
67
+ }
68
+ }
69
+ }
70
+ return NULL;
71
+ }
72
+
73
+ static ROptTable copy_opts(ROptTable src, ROptTable dest) {
74
+ dest->len = src->len;
75
+ dest->alen = src->alen;
76
+ if (NULL == src->table) {
77
+ dest->table = NULL;
78
+ } else {
79
+ dest->table = ALLOC_N(struct _rOpt, dest->alen);
80
+ memcpy(dest->table, src->table, sizeof(struct _rOpt) * dest->alen);
81
+ }
82
+ return NULL;
83
+ }
84
+
85
+ static int dump_attr_cb(ID key, VALUE value, VALUE ov) {
86
+ Out out = (Out)ov;
87
+ int depth = out->depth;
88
+ size_t size = depth * out->indent + 1;
89
+ const char *attr = rb_id2name(key);
90
+
91
+ // Some exceptions such as NoMethodError have an invisible attribute where
92
+ // the key name is NULL. Not an empty string but NULL.
93
+ if (NULL == attr) {
94
+ attr = "";
95
+ }
96
+ if (0 == strcmp("bt", attr) || 0 == strcmp("mesg", attr)) {
97
+ return ST_CONTINUE;
98
+ }
99
+ assure_size(out, size);
100
+ fill_indent(out, depth);
101
+ if ('@' == *attr) {
102
+ attr++;
103
+ oj_dump_cstr(attr, strlen(attr), 0, 0, out);
104
+ } else {
105
+ char buf[32];
106
+
107
+ *buf = '~';
108
+ strncpy(buf + 1, attr, sizeof(buf) - 2);
109
+ buf[sizeof(buf) - 1] = '\0';
110
+ oj_dump_cstr(buf, strlen(buf), 0, 0, out);
111
+ }
112
+ *out->cur++ = ':';
113
+ dump_rails_val(value, depth, out, true);
114
+ out->depth = depth;
115
+ *out->cur++ = ',';
116
+
117
+ return ST_CONTINUE;
118
+ }
119
+
120
+ static void dump_obj_attrs(VALUE obj, int depth, Out out, bool as_ok) {
121
+ assure_size(out, 2);
122
+ *out->cur++ = '{';
123
+ out->depth = depth + 1;
124
+ rb_ivar_foreach(obj, dump_attr_cb, (VALUE)out);
125
+ if (',' == *(out->cur - 1)) {
126
+ out->cur--; // backup to overwrite last comma
127
+ }
128
+ out->depth = depth;
129
+ fill_indent(out, depth);
130
+ *out->cur++ = '}';
131
+ *out->cur = '\0';
132
+ }
133
+
134
+ static void dump_struct(VALUE obj, int depth, Out out, bool as_ok) {
135
+ int d3 = depth + 2;
136
+ size_t size = d3 * out->indent + 2;
137
+ size_t sep_len = out->opts->dump_opts.before_size + out->opts->dump_opts.after_size + 2;
138
+ volatile VALUE ma;
139
+ volatile VALUE v;
140
+ int cnt;
141
+ int i;
142
+ int len;
143
+ const char * name;
144
+
145
+ #ifdef RSTRUCT_LEN
146
+ #if RSTRUCT_LEN_RETURNS_INTEGER_OBJECT
147
+ cnt = (int)NUM2LONG(RSTRUCT_LEN(obj));
148
+ #else // RSTRUCT_LEN_RETURNS_INTEGER_OBJECT
149
+ cnt = (int)RSTRUCT_LEN(obj);
150
+ #endif // RSTRUCT_LEN_RETURNS_INTEGER_OBJECT
151
+ #else
152
+ // This is a bit risky as a struct in C ruby is not the same as a Struct
153
+ // class in interpreted Ruby so length() may not be defined.
154
+ cnt = FIX2INT(rb_funcall(obj, oj_length_id, 0));
155
+ #endif
156
+ ma = rb_struct_s_members(rb_obj_class(obj));
157
+ assure_size(out, 2);
158
+ *out->cur++ = '{';
159
+ for (i = 0; i < cnt; i++) {
160
+ volatile VALUE s = rb_sym2str(RARRAY_AREF(ma, i));
161
+
162
+ name = RSTRING_PTR(s);
163
+ len = (int)RSTRING_LEN(s);
164
+ assure_size(out, size + sep_len + 6);
165
+ if (0 < i) {
166
+ *out->cur++ = ',';
167
+ }
168
+ fill_indent(out, d3);
169
+ *out->cur++ = '"';
170
+ APPEND_CHARS(out->cur, name, len);
171
+ *out->cur++ = '"';
172
+ if (0 < out->opts->dump_opts.before_size) {
173
+ APPEND_CHARS(out->cur, out->opts->dump_opts.before_sep, out->opts->dump_opts.before_size);
174
+ }
175
+ *out->cur++ = ':';
176
+ if (0 < out->opts->dump_opts.after_size) {
177
+ APPEND_CHARS(out->cur, out->opts->dump_opts.after_sep, out->opts->dump_opts.after_size);
178
+ }
179
+ #ifdef RSTRUCT_LEN
180
+ v = RSTRUCT_GET(obj, i);
181
+ #else
182
+ v = rb_struct_aref(obj, INT2FIX(i));
183
+ #endif
184
+ dump_rails_val(v, d3, out, true);
185
+ }
186
+ fill_indent(out, depth);
187
+ *out->cur++ = '}';
188
+ *out->cur = '\0';
189
+ }
190
+
191
+ static ID to_a_id = 0;
192
+
193
+ static void dump_enumerable(VALUE obj, int depth, Out out, bool as_ok) {
194
+ if (0 == to_a_id) {
195
+ to_a_id = rb_intern("to_a");
196
+ }
197
+ dump_rails_val(rb_funcall(obj, to_a_id, 0), depth, out, false);
198
+ }
199
+
200
+ static void dump_bigdecimal(VALUE obj, int depth, Out out, bool as_ok) {
201
+ volatile VALUE rstr = rb_funcall(obj, oj_to_s_id, 0);
202
+ const char * str = RSTRING_PTR(rstr);
203
+
204
+ if ('I' == *str || 'N' == *str || ('-' == *str && 'I' == str[1])) {
205
+ oj_dump_nil(Qnil, depth, out, false);
206
+ } else if (out->opts->int_range_max != 0 || out->opts->int_range_min != 0) {
207
+ oj_dump_cstr(str, (int)RSTRING_LEN(rstr), 0, 0, out);
208
+ } else if (Yes == out->opts->bigdec_as_num) {
209
+ oj_dump_raw(str, (int)RSTRING_LEN(rstr), out);
210
+ } else {
211
+ oj_dump_cstr(str, (int)RSTRING_LEN(rstr), 0, 0, out);
212
+ }
213
+ }
214
+
215
+ static void dump_sec_nano(VALUE obj, int64_t sec, long nsec, Out out) {
216
+ char buf[64];
217
+ struct _timeInfo ti;
218
+ long one = 1000000000;
219
+ long tzsecs = NUM2LONG(rb_funcall2(obj, oj_utc_offset_id, 0, 0));
220
+ int tzhour, tzmin;
221
+ char tzsign = '+';
222
+ int len;
223
+
224
+ if (out->end - out->cur <= 36) {
225
+ assure_size(out, 36);
226
+ }
227
+ if (9 > out->opts->sec_prec) {
228
+ int i;
229
+
230
+ // Rails does not round when reducing precision but instead floors,
231
+ for (i = 9 - out->opts->sec_prec; 0 < i; i--) {
232
+ nsec = nsec / 10;
233
+ one /= 10;
234
+ }
235
+ if (one <= nsec) {
236
+ nsec -= one;
237
+ sec++;
238
+ }
239
+ }
240
+ // 2012-01-05T23:58:07.123456000+09:00 or 2012/01/05 23:58:07 +0900
241
+ sec += tzsecs;
242
+ sec_as_time(sec, &ti);
243
+ if (0 > tzsecs) {
244
+ tzsign = '-';
245
+ tzhour = (int)(tzsecs / -3600);
246
+ tzmin = (int)(tzsecs / -60) - (tzhour * 60);
247
+ } else {
248
+ tzhour = (int)(tzsecs / 3600);
249
+ tzmin = (int)(tzsecs / 60) - (tzhour * 60);
250
+ }
251
+ if (!xml_time) {
252
+ len = sprintf(buf,
253
+ "%04d/%02d/%02d %02d:%02d:%02d %c%02d%02d",
254
+ ti.year,
255
+ ti.mon,
256
+ ti.day,
257
+ ti.hour,
258
+ ti.min,
259
+ ti.sec,
260
+ tzsign,
261
+ tzhour,
262
+ tzmin);
263
+ } else if (0 == out->opts->sec_prec) {
264
+ if (0 == tzsecs && rb_funcall2(obj, oj_utcq_id, 0, 0)) {
265
+ len = sprintf(buf,
266
+ "%04d-%02d-%02dT%02d:%02d:%02dZ",
267
+ ti.year,
268
+ ti.mon,
269
+ ti.day,
270
+ ti.hour,
271
+ ti.min,
272
+ ti.sec);
273
+ } else {
274
+ len = sprintf(buf,
275
+ "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
276
+ ti.year,
277
+ ti.mon,
278
+ ti.day,
279
+ ti.hour,
280
+ ti.min,
281
+ ti.sec,
282
+ tzsign,
283
+ tzhour,
284
+ tzmin);
285
+ }
286
+ } else if (0 == tzsecs && rb_funcall2(obj, oj_utcq_id, 0, 0)) {
287
+ char format[64] = "%04d-%02d-%02dT%02d:%02d:%02d.%09ldZ";
288
+
289
+ len = 30;
290
+ if (9 > out->opts->sec_prec) {
291
+ format[32] = '0' + out->opts->sec_prec;
292
+ len -= 9 - out->opts->sec_prec;
293
+ }
294
+ len = sprintf(buf, format, ti.year, ti.mon, ti.day, ti.hour, ti.min, ti.sec, nsec);
295
+ } else {
296
+ char format[64] = "%04d-%02d-%02dT%02d:%02d:%02d.%09ld%c%02d:%02d";
297
+
298
+ len = 35;
299
+ if (9 > out->opts->sec_prec) {
300
+ format[32] = '0' + out->opts->sec_prec;
301
+ len -= 9 - out->opts->sec_prec;
302
+ }
303
+ len = sprintf(buf,
304
+ format,
305
+ ti.year,
306
+ ti.mon,
307
+ ti.day,
308
+ ti.hour,
309
+ ti.min,
310
+ ti.sec,
311
+ nsec,
312
+ tzsign,
313
+ tzhour,
314
+ tzmin);
315
+ }
316
+ oj_dump_cstr(buf, len, 0, 0, out);
317
+ }
318
+
319
+ static void dump_time(VALUE obj, int depth, Out out, bool as_ok) {
320
+ long long sec;
321
+ long long nsec;
322
+
323
+ #ifdef HAVE_RB_TIME_TIMESPEC
324
+ if (16 <= sizeof(struct timespec)) {
325
+ struct timespec ts = rb_time_timespec(obj);
326
+
327
+ sec = (long long)ts.tv_sec;
328
+ nsec = ts.tv_nsec;
329
+ } else {
330
+ sec = NUM2LL(rb_funcall2(obj, oj_tv_sec_id, 0, 0));
331
+ nsec = NUM2LL(rb_funcall2(obj, oj_tv_nsec_id, 0, 0));
332
+ }
333
+ #else
334
+ sec = NUM2LL(rb_funcall2(obj, oj_tv_sec_id, 0, 0));
335
+ nsec = NUM2LL(rb_funcall2(obj, oj_tv_nsec_id, 0, 0));
336
+ #endif
337
+ dump_sec_nano(obj, sec, nsec, out);
338
+ }
339
+
340
+ static void dump_timewithzone(VALUE obj, int depth, Out out, bool as_ok) {
341
+ int64_t sec = NUM2LONG(rb_funcall2(obj, oj_tv_sec_id, 0, 0));
342
+ long long nsec = 0;
343
+
344
+ if (rb_respond_to(obj, oj_tv_nsec_id)) {
345
+ nsec = NUM2LL(rb_funcall2(obj, oj_tv_nsec_id, 0, 0));
346
+ } else if (rb_respond_to(obj, oj_tv_usec_id)) {
347
+ nsec = NUM2LL(rb_funcall2(obj, oj_tv_usec_id, 0, 0)) * 1000;
348
+ }
349
+ dump_sec_nano(obj, sec, nsec, out);
350
+ }
351
+
352
+ static void dump_to_s(VALUE obj, int depth, Out out, bool as_ok) {
353
+ volatile VALUE rstr = rb_funcall(obj, oj_to_s_id, 0);
354
+
355
+ oj_dump_cstr(RSTRING_PTR(rstr), (int)RSTRING_LEN(rstr), 0, 0, out);
356
+ }
357
+
358
+ static ID parameters_id = 0;
359
+
360
+ typedef struct _strLen {
361
+ const char *str;
362
+ int len;
363
+ } * StrLen;
364
+
365
+ static void dump_actioncontroller_parameters(VALUE obj, int depth, Out out, bool as_ok) {
366
+ if (0 == parameters_id) {
367
+ parameters_id = rb_intern("@parameters");
368
+ }
369
+ out->argc = 0;
370
+ dump_rails_val(rb_ivar_get(obj, parameters_id), depth, out, true);
371
+ }
372
+
373
+ static StrLen columns_array(VALUE rcols, int *ccnt) {
374
+ volatile VALUE v;
375
+ StrLen cp;
376
+ StrLen cols;
377
+ int i;
378
+ int cnt = (int)RARRAY_LEN(rcols);
379
+
380
+ *ccnt = cnt;
381
+ cols = ALLOC_N(struct _strLen, cnt);
382
+ for (i = 0, cp = cols; i < cnt; i++, cp++) {
383
+ v = RARRAY_AREF(rcols, i);
384
+ if (T_STRING != rb_type(v)) {
385
+ v = rb_funcall(v, oj_to_s_id, 0);
386
+ }
387
+ cp->str = StringValuePtr(v);
388
+ cp->len = (int)RSTRING_LEN(v);
389
+ }
390
+ return cols;
391
+ }
392
+
393
+ static void dump_row(VALUE row, StrLen cols, int ccnt, int depth, Out out) {
394
+ size_t size;
395
+ int d2 = depth + 1;
396
+ int i;
397
+
398
+ assure_size(out, 2);
399
+ *out->cur++ = '{';
400
+ size = depth * out->indent + 3;
401
+ for (i = 0; i < ccnt; i++, cols++) {
402
+ assure_size(out, size);
403
+ if (out->opts->dump_opts.use) {
404
+ if (0 < out->opts->dump_opts.array_size) {
405
+ APPEND_CHARS(out->cur, out->opts->dump_opts.array_nl, out->opts->dump_opts.array_size);
406
+ }
407
+ if (0 < out->opts->dump_opts.indent_size) {
408
+ int i;
409
+ for (i = d2; 0 < i; i--) {
410
+ APPEND_CHARS(out->cur, out->opts->dump_opts.indent_str, out->opts->dump_opts.indent_size);
411
+ }
412
+ }
413
+ } else {
414
+ fill_indent(out, d2);
415
+ }
416
+ oj_dump_cstr(cols->str, cols->len, 0, 0, out);
417
+ *out->cur++ = ':';
418
+ dump_rails_val(RARRAY_AREF(row, i), depth, out, true);
419
+ if (i < ccnt - 1) {
420
+ *out->cur++ = ',';
421
+ }
422
+ }
423
+ size = depth * out->indent + 1;
424
+ assure_size(out, size);
425
+ if (out->opts->dump_opts.use) {
426
+ if (0 < out->opts->dump_opts.array_size) {
427
+ APPEND_CHARS(out->cur, out->opts->dump_opts.array_nl, out->opts->dump_opts.array_size);
428
+ }
429
+ if (0 < out->opts->dump_opts.indent_size) {
430
+ int i;
431
+
432
+ for (i = depth; 0 < i; i--) {
433
+ APPEND_CHARS(out->cur, out->opts->dump_opts.indent_str, out->opts->dump_opts.indent_size);
434
+ }
435
+ }
436
+ } else {
437
+ fill_indent(out, depth);
438
+ }
439
+ *out->cur++ = '}';
440
+ }
441
+
442
+ static ID rows_id = 0;
443
+ static ID columns_id = 0;
444
+
445
+ static void dump_activerecord_result(VALUE obj, int depth, Out out, bool as_ok) {
446
+ volatile VALUE rows;
447
+ StrLen cols;
448
+ int ccnt = 0;
449
+ int i, rcnt;
450
+ size_t size;
451
+ int d2 = depth + 1;
452
+
453
+ if (0 == rows_id) {
454
+ rows_id = rb_intern("@rows");
455
+ columns_id = rb_intern("@columns");
456
+ }
457
+ out->argc = 0;
458
+ cols = columns_array(rb_ivar_get(obj, columns_id), &ccnt);
459
+ rows = rb_ivar_get(obj, rows_id);
460
+ rcnt = (int)RARRAY_LEN(rows);
461
+ assure_size(out, 2);
462
+ *out->cur++ = '[';
463
+ if (out->opts->dump_opts.use) {
464
+ size = d2 * out->opts->dump_opts.indent_size + out->opts->dump_opts.array_size + 1;
465
+ } else {
466
+ size = d2 * out->indent + 2;
467
+ }
468
+ assure_size(out, 2);
469
+ for (i = 0; i < rcnt; i++) {
470
+ assure_size(out, size);
471
+ if (out->opts->dump_opts.use) {
472
+ if (0 < out->opts->dump_opts.array_size) {
473
+ APPEND_CHARS(out->cur, out->opts->dump_opts.array_nl, out->opts->dump_opts.array_size);
474
+ }
475
+ if (0 < out->opts->dump_opts.indent_size) {
476
+ int i;
477
+ for (i = d2; 0 < i; i--) {
478
+ APPEND_CHARS(out->cur, out->opts->dump_opts.indent_str, out->opts->dump_opts.indent_size);
479
+ }
480
+ }
481
+ } else {
482
+ fill_indent(out, d2);
483
+ }
484
+ dump_row(RARRAY_AREF(rows, i), cols, ccnt, d2, out);
485
+ if (i < rcnt - 1) {
486
+ *out->cur++ = ',';
487
+ }
488
+ }
489
+ xfree(cols);
490
+ size = depth * out->indent + 1;
491
+ assure_size(out, size);
492
+ if (out->opts->dump_opts.use) {
493
+ if (0 < out->opts->dump_opts.array_size) {
494
+ APPEND_CHARS(out->cur, out->opts->dump_opts.array_nl, out->opts->dump_opts.array_size);
495
+ }
496
+ if (0 < out->opts->dump_opts.indent_size) {
497
+ int i;
498
+
499
+ for (i = depth; 0 < i; i--) {
500
+ APPEND_CHARS(out->cur, out->opts->dump_opts.indent_str, out->opts->dump_opts.indent_size);
501
+ }
502
+ }
503
+ } else {
504
+ fill_indent(out, depth);
505
+ }
506
+ *out->cur++ = ']';
507
+ }
508
+
509
+ typedef struct _namedFunc {
510
+ const char *name;
511
+ DumpFunc func;
512
+ } * NamedFunc;
513
+
514
+ static void dump_as_string(VALUE obj, int depth, Out out, bool as_ok) {
515
+ if (oj_code_dump(oj_compat_codes, obj, depth, out)) {
516
+ out->argc = 0;
517
+ return;
518
+ }
519
+ oj_dump_obj_to_s(obj, out);
520
+ }
521
+
522
+ static void dump_as_json(VALUE obj, int depth, Out out, bool as_ok) {
523
+ volatile VALUE ja;
524
+
525
+ if (Yes == out->opts->trace) {
526
+ oj_trace("as_json", obj, __FILE__, __LINE__, depth + 1, TraceRubyIn);
527
+ }
528
+ // Some classes elect to not take an options argument so check the arity
529
+ // of as_json.
530
+ if (0 == rb_obj_method_arity(obj, oj_as_json_id)) {
531
+ ja = rb_funcall(obj, oj_as_json_id, 0);
532
+ } else {
533
+ ja = rb_funcall2(obj, oj_as_json_id, out->argc, out->argv);
534
+ }
535
+ if (Yes == out->opts->trace) {
536
+ oj_trace("as_json", obj, __FILE__, __LINE__, depth + 1, TraceRubyOut);
537
+ }
538
+
539
+ out->argc = 0;
540
+ if (ja == obj || !as_ok) {
541
+ // Once as_json is called it should never be called again on the same
542
+ // object with as_ok.
543
+ dump_rails_val(ja, depth, out, false);
544
+ } else {
545
+ int type = rb_type(ja);
546
+
547
+ if (T_HASH == type || T_ARRAY == type) {
548
+ dump_rails_val(ja, depth, out, true);
549
+ } else {
550
+ dump_rails_val(ja, depth, out, true);
551
+ }
552
+ }
553
+ }
554
+
555
+ static void dump_regexp(VALUE obj, int depth, Out out, bool as_ok) {
556
+ if (as_ok && rb_respond_to(obj, oj_as_json_id)) {
557
+ dump_as_json(obj, depth, out, false);
558
+ return;
559
+ }
560
+ dump_as_string(obj, depth, out, as_ok);
561
+ }
562
+
563
+ static struct _namedFunc dump_map[] = {
564
+ {"ActionController::Parameters", dump_actioncontroller_parameters},
565
+ {"ActiveRecord::Result", dump_activerecord_result},
566
+ {"ActiveSupport::TimeWithZone", dump_timewithzone},
567
+ {"BigDecimal", dump_bigdecimal},
568
+ {"Range", dump_to_s},
569
+ {"Regexp", dump_regexp},
570
+ //{ "Regexp", dump_to_s },
571
+ {"Time", dump_time},
572
+ {NULL, NULL},
573
+ };
574
+
575
+ static VALUE activerecord_base = Qundef;
576
+ static ID attributes_id = 0;
577
+
578
+ static void dump_activerecord(VALUE obj, int depth, Out out, bool as_ok) {
579
+ if (0 == attributes_id) {
580
+ attributes_id = rb_intern("@attributes");
581
+ }
582
+ out->argc = 0;
583
+ dump_rails_val(rb_ivar_get(obj, attributes_id), depth, out, true);
584
+ }
585
+
586
+ static ROpt create_opt(ROptTable rot, VALUE clas) {
587
+ ROpt ro;
588
+ NamedFunc nf;
589
+ const char *classname = rb_class2name(clas);
590
+ int olen = rot->len;
591
+
592
+ rot->len++;
593
+ if (NULL == rot->table) {
594
+ rot->alen = 256;
595
+ rot->table = ALLOC_N(struct _rOpt, rot->alen);
596
+ memset(rot->table, 0, sizeof(struct _rOpt) * rot->alen);
597
+ } else if (rot->alen <= rot->len) {
598
+ rot->alen *= 2;
599
+ REALLOC_N(rot->table, struct _rOpt, rot->alen);
600
+ memset(rot->table + olen, 0, sizeof(struct _rOpt) * olen);
601
+ }
602
+ if (0 == olen) {
603
+ ro = rot->table;
604
+ } else if (rot->table[olen - 1].clas < clas) {
605
+ ro = &rot->table[olen];
606
+ } else {
607
+ int i;
608
+
609
+ for (i = 0, ro = rot->table; i < olen; i++, ro++) {
610
+ if (clas < ro->clas) {
611
+ memmove(ro + 1, ro, sizeof(struct _rOpt) * (olen - i));
612
+ break;
613
+ }
614
+ }
615
+ }
616
+ ro->clas = clas;
617
+ ro->on = true;
618
+ ro->dump = dump_obj_attrs;
619
+ for (nf = dump_map; NULL != nf->name; nf++) {
620
+ if (0 == strcmp(nf->name, classname)) {
621
+ ro->dump = nf->func;
622
+ break;
623
+ }
624
+ }
625
+ if (ro->dump == dump_obj_attrs) {
626
+ if (Qundef == activerecord_base) {
627
+ // If not defined let an exception be raised.
628
+ VALUE ar = rb_const_get_at(rb_cObject, rb_intern("ActiveRecord"));
629
+
630
+ if (Qundef != ar) {
631
+ activerecord_base = rb_const_get_at(ar, rb_intern("Base"));
632
+ }
633
+ }
634
+ if (Qundef != activerecord_base && Qtrue == rb_class_inherited_p(clas, activerecord_base)) {
635
+ ro->dump = dump_activerecord;
636
+ } else if (Qtrue == rb_class_inherited_p(clas, rb_cStruct)) { // check before enumerable
637
+ ro->dump = dump_struct;
638
+ } else if (Qtrue == rb_class_inherited_p(clas, rb_mEnumerable)) {
639
+ ro->dump = dump_enumerable;
640
+ } else if (Qtrue == rb_class_inherited_p(clas, rb_eException)) {
641
+ ro->dump = dump_to_s;
642
+ }
643
+ }
644
+ return ro;
645
+ }
646
+
647
+ static void encoder_free(void *ptr) {
648
+ if (NULL != ptr) {
649
+ Encoder e = (Encoder)ptr;
650
+
651
+ if (NULL != e->ropts.table) {
652
+ xfree(e->ropts.table);
653
+ }
654
+ xfree(ptr);
655
+ }
656
+ }
657
+
658
+ static void encoder_mark(void *ptr) {
659
+ if (NULL != ptr) {
660
+ Encoder e = (Encoder)ptr;
661
+
662
+ if (Qnil != e->arg) {
663
+ rb_gc_mark(e->arg);
664
+ }
665
+ }
666
+ }
667
+
668
+ /* Document-method: new
669
+ * call-seq: new(options=nil)
670
+ *
671
+ * Creates a new Encoder.
672
+ * - *options* [_Hash_] formatting options
673
+ */
674
+ static VALUE encoder_new(int argc, VALUE *argv, VALUE self) {
675
+ Encoder e = ALLOC(struct _encoder);
676
+
677
+ e->opts = oj_default_options;
678
+ e->arg = Qnil;
679
+ copy_opts(&ropts, &e->ropts);
680
+
681
+ if (1 <= argc && Qnil != *argv) {
682
+ oj_parse_options(*argv, &e->opts);
683
+ e->arg = *argv;
684
+ }
685
+ return Data_Wrap_Struct(encoder_class, encoder_mark, encoder_free, e);
686
+ }
687
+
688
+ static VALUE resolve_classpath(const char *name) {
689
+ char class_name[1024];
690
+ VALUE clas;
691
+ char * end = class_name + sizeof(class_name) - 1;
692
+ char * s;
693
+ const char *n = name;
694
+ ID cid;
695
+
696
+ clas = rb_cObject;
697
+ for (s = class_name; '\0' != *n; n++) {
698
+ if (':' == *n) {
699
+ *s = '\0';
700
+ n++;
701
+ if (':' != *n) {
702
+ return Qnil;
703
+ }
704
+ cid = rb_intern(class_name);
705
+ if (!rb_const_defined_at(clas, cid)) {
706
+ return Qnil;
707
+ }
708
+ clas = rb_const_get_at(clas, cid);
709
+ s = class_name;
710
+ } else if (end <= s) {
711
+ return Qnil;
712
+ } else {
713
+ *s++ = *n;
714
+ }
715
+ }
716
+ *s = '\0';
717
+ cid = rb_intern(class_name);
718
+ if (!rb_const_defined_at(clas, cid)) {
719
+ return Qnil;
720
+ }
721
+ clas = rb_const_get_at(clas, cid);
722
+
723
+ return clas;
724
+ }
725
+
726
+ static void optimize(int argc, VALUE *argv, ROptTable rot, bool on) {
727
+ ROpt ro;
728
+
729
+ if (0 == argc) {
730
+ int i;
731
+ NamedFunc nf;
732
+ VALUE clas;
733
+
734
+ oj_rails_hash_opt = on;
735
+ oj_rails_array_opt = on;
736
+ oj_rails_float_opt = on;
737
+
738
+ for (nf = dump_map; NULL != nf->name; nf++) {
739
+ if (Qnil != (clas = resolve_classpath(nf->name))) {
740
+ if (NULL == oj_rails_get_opt(rot, clas)) {
741
+ create_opt(rot, clas);
742
+ }
743
+ }
744
+ }
745
+ for (i = 0; i < rot->len; i++) {
746
+ rot->table[i].on = on;
747
+ }
748
+ }
749
+ for (; 0 < argc; argc--, argv++) {
750
+ if (rb_cHash == *argv) {
751
+ oj_rails_hash_opt = on;
752
+ } else if (rb_cArray == *argv) {
753
+ oj_rails_array_opt = on;
754
+ } else if (rb_cFloat == *argv) {
755
+ oj_rails_float_opt = on;
756
+ } else if (oj_string_writer_class == *argv) {
757
+ string_writer_optimized = on;
758
+ } else if (NULL != (ro = oj_rails_get_opt(rot, *argv)) ||
759
+ NULL != (ro = create_opt(rot, *argv))) {
760
+ ro->on = on;
761
+ }
762
+ }
763
+ }
764
+
765
+ /* Document-method optimize
766
+ * call-seq: optimize(*classes)
767
+ *
768
+ * Use Oj rails optimized routines to encode the specified classes. This
769
+ * ignores the as_json() method on the class and uses an internal encoding
770
+ * instead. Passing in no classes indicates all should use the optimized
771
+ * version of encoding for all previously optimized classes. Passing in the
772
+ * Object class set a global switch that will then use the optimized behavior
773
+ * for all classes.
774
+ *
775
+ * - *classes* [_Class_] a list of classes to optimize
776
+ */
777
+ static VALUE encoder_optimize(int argc, VALUE *argv, VALUE self) {
778
+ Encoder e = (Encoder)DATA_PTR(self);
779
+
780
+ optimize(argc, argv, &e->ropts, true);
781
+
782
+ return Qnil;
783
+ }
784
+
785
+ /* Document-method: optimize
786
+ * call-seq: optimize(*classes)
787
+ *
788
+ * Use Oj rails optimized routines to encode the specified classes. This
789
+ * ignores the as_json() method on the class and uses an internal encoding
790
+ * instead. Passing in no classes indicates all should use the optimized
791
+ * version of encoding for all previously optimized classes. Passing in the
792
+ * Object class set a global switch that will then use the optimized behavior
793
+ * for all classes.
794
+ *
795
+ * - *classes* [_Class_] a list of classes to optimize
796
+ */
797
+ static VALUE rails_optimize(int argc, VALUE *argv, VALUE self) {
798
+ optimize(argc, argv, &ropts, true);
799
+ string_writer_optimized = true;
800
+
801
+ return Qnil;
802
+ }
803
+
804
+ /* Document-module: mimic_JSON
805
+ * call-seq: mimic_JSON()
806
+ *
807
+ * Sets the JSON method to use Oj similar to Oj.mimic_JSON except with the
808
+ * ActiveSupport monkey patches instead of the json gem monkey patches.
809
+ */
810
+ VALUE
811
+ rails_mimic_json(VALUE self) {
812
+ VALUE json;
813
+
814
+ if (rb_const_defined_at(rb_cObject, rb_intern("JSON"))) {
815
+ json = rb_const_get_at(rb_cObject, rb_intern("JSON"));
816
+ } else {
817
+ json = rb_define_module("JSON");
818
+ }
819
+ oj_mimic_json_methods(json);
820
+ // Setting the default mode breaks the prmoise in the docs not to.
821
+ //oj_default_options.mode = RailsMode;
822
+
823
+ return Qnil;
824
+ }
825
+
826
+ /* Document-method: deoptimize
827
+ * call-seq: deoptimize(*classes)
828
+ *
829
+ * Turn off Oj rails optimization on the specified classes.
830
+ *
831
+ * - *classes* [_Class_] a list of classes to deoptimize
832
+ */
833
+ static VALUE encoder_deoptimize(int argc, VALUE *argv, VALUE self) {
834
+ Encoder e = (Encoder)DATA_PTR(self);
835
+
836
+ optimize(argc, argv, &e->ropts, false);
837
+
838
+ return Qnil;
839
+ }
840
+
841
+ /* Document-method: deoptimize
842
+ * call-seq: deoptimize(*classes)
843
+ *
844
+ * Turn off Oj rails optimization on the specified classes.
845
+ *
846
+ * - *classes* [_Class_] a list of classes to deoptimize
847
+ */
848
+ static VALUE rails_deoptimize(int argc, VALUE *argv, VALUE self) {
849
+ optimize(argc, argv, &ropts, false);
850
+ string_writer_optimized = false;
851
+
852
+ return Qnil;
853
+ }
854
+
855
+ /* Document-method:optimized?
856
+ * call-seq: optimized?(clas)
857
+ *
858
+ * - *clas* [_Class_] Class to check
859
+ *
860
+ * @return true if the class is being optimized for rails and false otherwise
861
+ */
862
+ static VALUE encoder_optimized(VALUE self, VALUE clas) {
863
+ Encoder e = (Encoder)DATA_PTR(self);
864
+ ROpt ro = oj_rails_get_opt(&e->ropts, clas);
865
+
866
+ if (NULL == ro) {
867
+ return Qfalse;
868
+ }
869
+ return (ro->on) ? Qtrue : Qfalse;
870
+ }
871
+
872
+ /* Document-method: optimized?
873
+ * call-seq: optimized?(clas)
874
+ *
875
+ * Returns true if the specified Class is being optimized.
876
+ */
877
+ static VALUE rails_optimized(VALUE self, VALUE clas) {
878
+ ROpt ro = oj_rails_get_opt(&ropts, clas);
879
+
880
+ if (NULL == ro) {
881
+ return Qfalse;
882
+ }
883
+ return (ro->on) ? Qtrue : Qfalse;
884
+ }
885
+
886
+ typedef struct _oo {
887
+ Out out;
888
+ VALUE obj;
889
+ } * OO;
890
+
891
+ static VALUE protect_dump(VALUE ov) {
892
+ OO oo = (OO)ov;
893
+
894
+ dump_rails_val(oo->obj, 0, oo->out, true);
895
+
896
+ return Qnil;
897
+ }
898
+
899
+ static VALUE encode(VALUE obj, ROptTable ropts, Options opts, int argc, VALUE *argv) {
900
+ struct _out out;
901
+ struct _options copts = *opts;
902
+ volatile VALUE rstr = Qnil;
903
+ struct _oo oo;
904
+ int line = 0;
905
+
906
+ oo.out = &out;
907
+ oo.obj = obj;
908
+ copts.str_rx.head = NULL;
909
+ copts.str_rx.tail = NULL;
910
+ copts.mode = RailsMode;
911
+ if (escape_html) {
912
+ copts.escape_mode = RailsXEsc;
913
+ } else {
914
+ copts.escape_mode = RailsEsc;
915
+ }
916
+
917
+ oj_out_init(&out);
918
+
919
+ out.omit_nil = copts.dump_opts.omit_nil;
920
+ out.caller = 0;
921
+ out.cur = out.buf;
922
+ out.circ_cnt = 0;
923
+ out.opts = &copts;
924
+ out.hash_cnt = 0;
925
+ out.indent = copts.indent;
926
+ out.argc = argc;
927
+ out.argv = argv;
928
+ out.ropts = ropts;
929
+ if (Yes == copts.circular) {
930
+ oj_cache8_new(&out.circ_cache);
931
+ }
932
+ // dump_rails_val(*argv, 0, &out, true);
933
+ rb_protect(protect_dump, (VALUE)&oo, &line);
934
+
935
+ if (0 == line) {
936
+ if (0 < out.indent) {
937
+ switch (*(out.cur - 1)) {
938
+ case ']':
939
+ case '}': assure_size(&out, 2); *out.cur++ = '\n';
940
+ default: break;
941
+ }
942
+ }
943
+ *out.cur = '\0';
944
+
945
+ if (0 == out.buf) {
946
+ rb_raise(rb_eNoMemError, "Not enough memory.");
947
+ }
948
+ rstr = rb_str_new2(out.buf);
949
+ rstr = oj_encode(rstr);
950
+ }
951
+ if (Yes == copts.circular) {
952
+ oj_cache8_delete(out.circ_cache);
953
+ }
954
+
955
+ oj_out_free(&out);
956
+
957
+ if (0 != line) {
958
+ rb_jump_tag(line);
959
+ }
960
+ return rstr;
961
+ }
962
+
963
+ /* Document-method: encode
964
+ * call-seq: encode(obj)
965
+ *
966
+ * - *obj* [_Object_] object to encode
967
+ *
968
+ * Returns encoded object as a JSON string.
969
+ */
970
+ static VALUE encoder_encode(VALUE self, VALUE obj) {
971
+ Encoder e = (Encoder)DATA_PTR(self);
972
+
973
+ if (Qnil != e->arg) {
974
+ VALUE argv[1] = {e->arg};
975
+
976
+ return encode(obj, &e->ropts, &e->opts, 1, argv);
977
+ }
978
+ return encode(obj, &e->ropts, &e->opts, 0, NULL);
979
+ }
980
+
981
+ /* Document-method: encode
982
+ * call-seq: encode(obj, opts=nil)
983
+ *
984
+ * Encode obj as a JSON String.
985
+ *
986
+ * - *obj* [_Object_|Hash|Array] object to convert to a JSON String
987
+ * - *opts* [_Hash_] options
988
+ *
989
+ * Returns [_String_]
990
+ */
991
+ static VALUE rails_encode(int argc, VALUE *argv, VALUE self) {
992
+ if (1 > argc) {
993
+ rb_raise(rb_eArgError, "wrong number of arguments (0 for 1).");
994
+ }
995
+ if (1 == argc) {
996
+ return encode(*argv, NULL, &oj_default_options, 0, NULL);
997
+ } else {
998
+ return encode(*argv, NULL, &oj_default_options, argc - 1, argv + 1);
999
+ }
1000
+ }
1001
+
1002
+ static VALUE rails_use_standard_json_time_format(VALUE self, VALUE state) {
1003
+ if (Qtrue == state || Qfalse == state) {
1004
+ // no change needed
1005
+ } else if (Qnil == state) {
1006
+ state = Qfalse;
1007
+ } else {
1008
+ state = Qtrue;
1009
+ }
1010
+ rb_iv_set(self, "@use_standard_json_time_format", state);
1011
+ xml_time = Qtrue == state;
1012
+
1013
+ return state;
1014
+ }
1015
+
1016
+ static VALUE rails_use_standard_json_time_format_get(VALUE self) {
1017
+ return xml_time ? Qtrue : Qfalse;
1018
+ }
1019
+
1020
+ static VALUE rails_escape_html_entities_in_json(VALUE self, VALUE state) {
1021
+ rb_iv_set(self, "@escape_html_entities_in_json", state);
1022
+ escape_html = Qtrue == state;
1023
+
1024
+ return state;
1025
+ }
1026
+
1027
+ static VALUE rails_escape_html_entities_in_json_get(VALUE self) {
1028
+ return escape_html ? Qtrue : Qfalse;
1029
+ }
1030
+
1031
+ static VALUE rails_time_precision(VALUE self, VALUE prec) {
1032
+ rb_iv_set(self, "@time_precision", prec);
1033
+ oj_default_options.sec_prec = NUM2INT(prec);
1034
+ oj_default_options.sec_prec_set = true;
1035
+
1036
+ return prec;
1037
+ }
1038
+
1039
+ /* Document-method: set_encoder
1040
+ * call-seq: set_encoder()
1041
+ *
1042
+ * Sets the ActiveSupport.encoder to Oj::Rails::Encoder and wraps some of the
1043
+ * formatting globals used by ActiveSupport to allow the use of those globals
1044
+ * in the Oj::Rails optimizations.
1045
+ */
1046
+ static VALUE rails_set_encoder(VALUE self) {
1047
+ VALUE active;
1048
+ VALUE json;
1049
+ VALUE encoding;
1050
+ VALUE pv;
1051
+ VALUE verbose;
1052
+ VALUE enc = resolve_classpath("ActiveSupport::JSON::Encoding");
1053
+
1054
+ if (Qnil != enc) {
1055
+ escape_html = Qtrue == rb_iv_get(self, "@escape_html_entities_in_json");
1056
+ xml_time = Qtrue == rb_iv_get(enc, "@use_standard_json_time_format");
1057
+ }
1058
+ if (rb_const_defined_at(rb_cObject, rb_intern("ActiveSupport"))) {
1059
+ active = rb_const_get_at(rb_cObject, rb_intern("ActiveSupport"));
1060
+ } else {
1061
+ rb_raise(rb_eStandardError, "ActiveSupport not loaded.");
1062
+ }
1063
+ rb_funcall(active, rb_intern("json_encoder="), 1, encoder_class);
1064
+
1065
+ json = rb_const_get_at(active, rb_intern("JSON"));
1066
+ encoding = rb_const_get_at(json, rb_intern("Encoding"));
1067
+
1068
+ // rb_undef_method doesn't work for modules or maybe sometimes
1069
+ // doesn't. Anyway setting verbose should hide the warning.
1070
+ verbose = rb_gv_get("$VERBOSE");
1071
+ rb_gv_set("$VERBOSE", Qfalse);
1072
+ rb_undef_method(encoding, "use_standard_json_time_format=");
1073
+ rb_define_module_function(encoding,
1074
+ "use_standard_json_time_format=",
1075
+ rails_use_standard_json_time_format,
1076
+ 1);
1077
+ rb_undef_method(encoding, "use_standard_json_time_format");
1078
+ rb_define_module_function(encoding,
1079
+ "use_standard_json_time_format",
1080
+ rails_use_standard_json_time_format_get,
1081
+ 0);
1082
+
1083
+ pv = rb_iv_get(encoding, "@escape_html_entities_in_json");
1084
+ escape_html = Qtrue == pv;
1085
+ rb_undef_method(encoding, "escape_html_entities_in_json=");
1086
+ rb_define_module_function(encoding,
1087
+ "escape_html_entities_in_json=",
1088
+ rails_escape_html_entities_in_json,
1089
+ 1);
1090
+ rb_undef_method(encoding, "escape_html_entities_in_json");
1091
+ rb_define_module_function(encoding,
1092
+ "escape_html_entities_in_json",
1093
+ rails_escape_html_entities_in_json_get,
1094
+ 0);
1095
+
1096
+ pv = rb_iv_get(encoding, "@time_precision");
1097
+ oj_default_options.sec_prec = NUM2INT(pv);
1098
+ oj_default_options.sec_prec_set = true;
1099
+ rb_undef_method(encoding, "time_precision=");
1100
+ rb_define_module_function(encoding, "time_precision=", rails_time_precision, 1);
1101
+ rb_gv_set("$VERBOSE", verbose);
1102
+
1103
+ return Qnil;
1104
+ }
1105
+
1106
+ /* Document-method: set_decoder
1107
+ * call-seq: set_decoder()
1108
+ *
1109
+ * Sets the JSON.parse function to be the Oj::parse function which is json gem
1110
+ * compatible.
1111
+ */
1112
+ static VALUE rails_set_decoder(VALUE self) {
1113
+ VALUE json;
1114
+ VALUE json_error;
1115
+ VALUE verbose;
1116
+
1117
+ if (rb_const_defined_at(rb_cObject, rb_intern("JSON"))) {
1118
+ json = rb_const_get_at(rb_cObject, rb_intern("JSON"));
1119
+ } else {
1120
+ json = rb_define_module("JSON");
1121
+ }
1122
+ if (rb_const_defined_at(json, rb_intern("JSONError"))) {
1123
+ json_error = rb_const_get(json, rb_intern("JSONError"));
1124
+ } else {
1125
+ json_error = rb_define_class_under(json, "JSONError", rb_eStandardError);
1126
+ }
1127
+ if (rb_const_defined_at(json, rb_intern("ParserError"))) {
1128
+ oj_json_parser_error_class = rb_const_get(json, rb_intern("ParserError"));
1129
+ } else {
1130
+ oj_json_parser_error_class = rb_define_class_under(json, "ParserError", json_error);
1131
+ }
1132
+ // rb_undef_method doesn't work for modules or maybe sometimes
1133
+ // doesn't. Anyway setting verbose should hide the warning.
1134
+ verbose = rb_gv_get("$VERBOSE");
1135
+ rb_gv_set("$VERBOSE", Qfalse);
1136
+ rb_undef_method(json, "parse");
1137
+ rb_define_module_function(json, "parse", oj_mimic_parse, -1);
1138
+ rb_gv_set("$VERBOSE", verbose);
1139
+
1140
+ return Qnil;
1141
+ }
1142
+
1143
+ /* Document-module: Oj.optimize_rails()
1144
+ *
1145
+ * Sets the Oj as the Rails encoder and decoder. Oj::Rails.optimize is also
1146
+ * called.
1147
+ */
1148
+ VALUE
1149
+ oj_optimize_rails(VALUE self) {
1150
+ rails_set_encoder(self);
1151
+ rails_set_decoder(self);
1152
+ rails_optimize(0, NULL, self);
1153
+ rails_mimic_json(self);
1154
+
1155
+ return Qnil;
1156
+ }
1157
+
1158
+ /* Document-module: Oj::Rails
1159
+ *
1160
+ * Module that provides rails and active support compatibility.
1161
+ */
1162
+ /* Document-class: Oj::Rails::Encoder
1163
+ *
1164
+ * The Oj ActiveSupport compliant encoder.
1165
+ */
1166
+ void oj_mimic_rails_init(void) {
1167
+ VALUE rails = rb_define_module_under(Oj, "Rails");
1168
+
1169
+ rb_define_module_function(rails, "encode", rails_encode, -1);
1170
+
1171
+ encoder_class = rb_define_class_under(rails, "Encoder", rb_cObject);
1172
+ rb_gc_register_address(&encoder_class);
1173
+ rb_undef_alloc_func(encoder_class);
1174
+
1175
+ rb_define_module_function(encoder_class, "new", encoder_new, -1);
1176
+ rb_define_module_function(rails, "optimize", rails_optimize, -1);
1177
+ rb_define_module_function(rails, "deoptimize", rails_deoptimize, -1);
1178
+ rb_define_module_function(rails, "optimized?", rails_optimized, 1);
1179
+ rb_define_module_function(rails, "mimic_JSON", rails_mimic_json, 0);
1180
+
1181
+ rb_define_module_function(rails, "set_encoder", rails_set_encoder, 0);
1182
+ rb_define_module_function(rails, "set_decoder", rails_set_decoder, 0);
1183
+
1184
+ rb_define_method(encoder_class, "encode", encoder_encode, 1);
1185
+ rb_define_method(encoder_class, "optimize", encoder_optimize, -1);
1186
+ rb_define_method(encoder_class, "deoptimize", encoder_deoptimize, -1);
1187
+ rb_define_method(encoder_class, "optimized?", encoder_optimized, 1);
1188
+ }
1189
+
1190
+ static void dump_to_hash(VALUE obj, int depth, Out out) {
1191
+ dump_rails_val(rb_funcall(obj, oj_to_hash_id, 0), depth, out, true);
1192
+ }
1193
+
1194
+ static void dump_float(VALUE obj, int depth, Out out, bool as_ok) {
1195
+ char buf[64];
1196
+ char * b;
1197
+ double d = rb_num2dbl(obj);
1198
+ int cnt = 0;
1199
+
1200
+ if (0.0 == d) {
1201
+ b = buf;
1202
+ *b++ = '0';
1203
+ *b++ = '.';
1204
+ *b++ = '0';
1205
+ *b++ = '\0';
1206
+ cnt = 3;
1207
+ } else {
1208
+ if (isnan(d) || OJ_INFINITY == d || -OJ_INFINITY == d) {
1209
+ strcpy(buf, "null");
1210
+ cnt = 4;
1211
+ } else if (d == (double)(long long int)d) {
1212
+ cnt = snprintf(buf, sizeof(buf), "%.1f", d);
1213
+ } else if (oj_rails_float_opt) {
1214
+ cnt = oj_dump_float_printf(buf, sizeof(buf), obj, d, "%0.16g");
1215
+ } else {
1216
+ volatile VALUE rstr = rb_funcall(obj, oj_to_s_id, 0);
1217
+
1218
+ strcpy(buf, RSTRING_PTR(rstr));
1219
+ cnt = (int)RSTRING_LEN(rstr);
1220
+ }
1221
+ }
1222
+ assure_size(out, cnt);
1223
+ for (b = buf; '\0' != *b; b++) {
1224
+ *out->cur++ = *b;
1225
+ }
1226
+ *out->cur = '\0';
1227
+ }
1228
+
1229
+ static void dump_array(VALUE a, int depth, Out out, bool as_ok) {
1230
+ size_t size;
1231
+ int i, cnt;
1232
+ int d2 = depth + 1;
1233
+
1234
+ if (Yes == out->opts->circular) {
1235
+ if (0 > oj_check_circular(a, out)) {
1236
+ oj_dump_nil(Qnil, 0, out, false);
1237
+ return;
1238
+ }
1239
+ }
1240
+ // if (!oj_rails_array_opt && as_ok && 0 < out->argc && rb_respond_to(a, oj_as_json_id)) {
1241
+ if (as_ok && 0 < out->argc && rb_respond_to(a, oj_as_json_id)) {
1242
+ dump_as_json(a, depth, out, false);
1243
+ return;
1244
+ }
1245
+ cnt = (int)RARRAY_LEN(a);
1246
+ *out->cur++ = '[';
1247
+ size = 2;
1248
+ assure_size(out, size);
1249
+ if (0 == cnt) {
1250
+ *out->cur++ = ']';
1251
+ } else {
1252
+ if (out->opts->dump_opts.use) {
1253
+ size = d2 * out->opts->dump_opts.indent_size + out->opts->dump_opts.array_size + 1;
1254
+ } else {
1255
+ size = d2 * out->indent + 2;
1256
+ }
1257
+ assure_size(out, size * cnt);
1258
+ cnt--;
1259
+ for (i = 0; i <= cnt; i++) {
1260
+ if (out->opts->dump_opts.use) {
1261
+ if (0 < out->opts->dump_opts.array_size) {
1262
+ APPEND_CHARS(out->cur, out->opts->dump_opts.array_nl, out->opts->dump_opts.array_size);
1263
+ }
1264
+ if (0 < out->opts->dump_opts.indent_size) {
1265
+ int i;
1266
+ for (i = d2; 0 < i; i--) {
1267
+ APPEND_CHARS(out->cur, out->opts->dump_opts.indent_str, out->opts->dump_opts.indent_size);
1268
+ }
1269
+ }
1270
+ } else {
1271
+ fill_indent(out, d2);
1272
+ }
1273
+ dump_rails_val(RARRAY_AREF(a, i), d2, out, true);
1274
+ if (i < cnt) {
1275
+ *out->cur++ = ',';
1276
+ }
1277
+ }
1278
+ size = depth * out->indent + 1;
1279
+ assure_size(out, size);
1280
+ if (out->opts->dump_opts.use) {
1281
+ if (0 < out->opts->dump_opts.array_size) {
1282
+ APPEND_CHARS(out->cur, out->opts->dump_opts.array_nl, out->opts->dump_opts.array_size);
1283
+ }
1284
+ if (0 < out->opts->dump_opts.indent_size) {
1285
+ int i;
1286
+
1287
+ for (i = depth; 0 < i; i--) {
1288
+ APPEND_CHARS(out->cur, out->opts->dump_opts.indent_str, out->opts->dump_opts.indent_size);
1289
+ }
1290
+ }
1291
+ } else {
1292
+ fill_indent(out, depth);
1293
+ }
1294
+ *out->cur++ = ']';
1295
+ }
1296
+ *out->cur = '\0';
1297
+ }
1298
+
1299
+ static int hash_cb(VALUE key, VALUE value, VALUE ov) {
1300
+ Out out = (Out)ov;
1301
+ int depth = out->depth;
1302
+ long size;
1303
+ int rtype = rb_type(key);
1304
+
1305
+ if (out->omit_nil && Qnil == value) {
1306
+ return ST_CONTINUE;
1307
+ }
1308
+ if (rtype != T_STRING && rtype != T_SYMBOL) {
1309
+ key = rb_funcall(key, oj_to_s_id, 0);
1310
+ rtype = rb_type(key);
1311
+ }
1312
+ if (!out->opts->dump_opts.use) {
1313
+ size = depth * out->indent + 1;
1314
+ assure_size(out, size);
1315
+ fill_indent(out, depth);
1316
+ if (rtype == T_STRING) {
1317
+ oj_dump_str(key, 0, out, false);
1318
+ } else {
1319
+ oj_dump_sym(key, 0, out, false);
1320
+ }
1321
+ *out->cur++ = ':';
1322
+ } else {
1323
+ size = depth * out->opts->dump_opts.indent_size + out->opts->dump_opts.hash_size + 1;
1324
+ assure_size(out, size);
1325
+ if (0 < out->opts->dump_opts.hash_size) {
1326
+ APPEND_CHARS(out->cur, out->opts->dump_opts.hash_nl, out->opts->dump_opts.hash_size);
1327
+ }
1328
+ if (0 < out->opts->dump_opts.indent_size) {
1329
+ int i;
1330
+ for (i = depth; 0 < i; i--) {
1331
+ APPEND_CHARS(out->cur, out->opts->dump_opts.indent_str, out->opts->dump_opts.indent_size);
1332
+ }
1333
+ }
1334
+ if (rtype == T_STRING) {
1335
+ oj_dump_str(key, 0, out, false);
1336
+ } else {
1337
+ oj_dump_sym(key, 0, out, false);
1338
+ }
1339
+ size = out->opts->dump_opts.before_size + out->opts->dump_opts.after_size + 2;
1340
+ assure_size(out, size);
1341
+ if (0 < out->opts->dump_opts.before_size) {
1342
+ APPEND_CHARS(out->cur, out->opts->dump_opts.before_sep, out->opts->dump_opts.before_size);
1343
+ }
1344
+ *out->cur++ = ':';
1345
+ if (0 < out->opts->dump_opts.after_size) {
1346
+ APPEND_CHARS(out->cur, out->opts->dump_opts.after_sep, out->opts->dump_opts.after_size);
1347
+ }
1348
+ }
1349
+ dump_rails_val(value, depth, out, true);
1350
+ out->depth = depth;
1351
+ *out->cur++ = ',';
1352
+
1353
+ return ST_CONTINUE;
1354
+ }
1355
+
1356
+ static void dump_hash(VALUE obj, int depth, Out out, bool as_ok) {
1357
+ int cnt;
1358
+ size_t size;
1359
+
1360
+ if (Yes == out->opts->circular) {
1361
+ if (0 > oj_check_circular(obj, out)) {
1362
+ oj_dump_nil(Qnil, 0, out, false);
1363
+ return;
1364
+ }
1365
+ }
1366
+ if ((!oj_rails_hash_opt || 0 < out->argc) && as_ok && rb_respond_to(obj, oj_as_json_id)) {
1367
+ dump_as_json(obj, depth, out, false);
1368
+ return;
1369
+ }
1370
+ cnt = (int)RHASH_SIZE(obj);
1371
+ size = depth * out->indent + 2;
1372
+ assure_size(out, 2);
1373
+ *out->cur++ = '{';
1374
+ if (0 == cnt) {
1375
+ *out->cur++ = '}';
1376
+ } else {
1377
+ out->depth = depth + 1;
1378
+ rb_hash_foreach(obj, hash_cb, (VALUE)out);
1379
+ if (',' == *(out->cur - 1)) {
1380
+ out->cur--; // backup to overwrite last comma
1381
+ }
1382
+ if (!out->opts->dump_opts.use) {
1383
+ assure_size(out, size);
1384
+ fill_indent(out, depth);
1385
+ } else {
1386
+ size = depth * out->opts->dump_opts.indent_size + out->opts->dump_opts.hash_size + 1;
1387
+ assure_size(out, size);
1388
+ if (0 < out->opts->dump_opts.hash_size) {
1389
+ APPEND_CHARS(out->cur, out->opts->dump_opts.hash_nl, out->opts->dump_opts.hash_size);
1390
+ }
1391
+ if (0 < out->opts->dump_opts.indent_size) {
1392
+ int i;
1393
+
1394
+ for (i = depth; 0 < i; i--) {
1395
+ APPEND_CHARS(out->cur, out->opts->dump_opts.indent_str, out->opts->dump_opts.indent_size);
1396
+ }
1397
+ }
1398
+ }
1399
+ *out->cur++ = '}';
1400
+ }
1401
+ *out->cur = '\0';
1402
+ }
1403
+
1404
+ static void dump_obj(VALUE obj, int depth, Out out, bool as_ok) {
1405
+ VALUE clas;
1406
+
1407
+ if (oj_code_dump(oj_compat_codes, obj, depth, out)) {
1408
+ out->argc = 0;
1409
+ return;
1410
+ }
1411
+ clas = rb_obj_class(obj);
1412
+ if (as_ok) {
1413
+ ROpt ro;
1414
+
1415
+ if (NULL != (ro = oj_rails_get_opt(out->ropts, clas)) && ro->on) {
1416
+ ro->dump(obj, depth, out, as_ok);
1417
+ } else if (Yes == out->opts->raw_json && rb_respond_to(obj, oj_raw_json_id)) {
1418
+ oj_dump_raw_json(obj, depth, out);
1419
+ } else if (rb_respond_to(obj, oj_as_json_id)) {
1420
+ dump_as_json(obj, depth, out, true);
1421
+ } else if (rb_respond_to(obj, oj_to_hash_id)) {
1422
+ dump_to_hash(obj, depth, out);
1423
+ } else if (oj_bigdecimal_class == clas) {
1424
+ dump_bigdecimal(obj, depth, out, false);
1425
+ } else {
1426
+ oj_dump_obj_to_s(obj, out);
1427
+ }
1428
+ } else if (Yes == out->opts->raw_json && rb_respond_to(obj, oj_raw_json_id)) {
1429
+ oj_dump_raw_json(obj, depth, out);
1430
+ } else if (rb_respond_to(obj, oj_to_hash_id)) {
1431
+ // Always attempt to_hash.
1432
+ dump_to_hash(obj, depth, out);
1433
+ } else if (oj_bigdecimal_class == clas) {
1434
+ dump_bigdecimal(obj, depth, out, false);
1435
+ } else {
1436
+ oj_dump_obj_to_s(obj, out);
1437
+ }
1438
+ }
1439
+
1440
+ static DumpFunc rails_funcs[] = {
1441
+ NULL, // RUBY_T_NONE = 0x00,
1442
+ dump_obj, // RUBY_T_OBJECT = 0x01,
1443
+ oj_dump_class, // RUBY_T_CLASS = 0x02,
1444
+ oj_dump_class, // RUBY_T_MODULE = 0x03,
1445
+ dump_float, // RUBY_T_FLOAT = 0x04,
1446
+ oj_dump_str, // RUBY_T_STRING = 0x05,
1447
+ dump_regexp, // RUBY_T_REGEXP = 0x06,
1448
+ // dump_as_string, // RUBY_T_REGEXP = 0x06,
1449
+ dump_array, // RUBY_T_ARRAY = 0x07,
1450
+ dump_hash, // RUBY_T_HASH = 0x08,
1451
+ dump_obj, // RUBY_T_STRUCT = 0x09,
1452
+ oj_dump_bignum, // RUBY_T_BIGNUM = 0x0a,
1453
+ dump_as_string, // RUBY_T_FILE = 0x0b,
1454
+ dump_obj, // RUBY_T_DATA = 0x0c,
1455
+ NULL, // RUBY_T_MATCH = 0x0d,
1456
+ // Rails raises a stack error on Complex and Rational. It also corrupts
1457
+ // something which causes a segfault on the next call. Oj will not mimic
1458
+ // that behavior.
1459
+ dump_as_string, // RUBY_T_COMPLEX = 0x0e,
1460
+ dump_as_string, // RUBY_T_RATIONAL = 0x0f,
1461
+ NULL, // 0x10
1462
+ oj_dump_nil, // RUBY_T_NIL = 0x11,
1463
+ oj_dump_true, // RUBY_T_TRUE = 0x12,
1464
+ oj_dump_false, // RUBY_T_FALSE = 0x13,
1465
+ oj_dump_sym, // RUBY_T_SYMBOL = 0x14,
1466
+ oj_dump_fixnum, // RUBY_T_FIXNUM = 0x15,
1467
+ };
1468
+
1469
+ static void dump_rails_val(VALUE obj, int depth, Out out, bool as_ok) {
1470
+ int type = rb_type(obj);
1471
+
1472
+ if (Yes == out->opts->trace) {
1473
+ oj_trace("dump", obj, __FILE__, __LINE__, depth, TraceIn);
1474
+ }
1475
+ if (MAX_DEPTH < depth) {
1476
+ rb_raise(rb_eNoMemError, "Too deeply nested.\n");
1477
+ }
1478
+ if (0 < type && type <= RUBY_T_FIXNUM) {
1479
+ DumpFunc f = rails_funcs[type];
1480
+
1481
+ if (NULL != f) {
1482
+ f(obj, depth, out, as_ok);
1483
+ if (Yes == out->opts->trace) {
1484
+ oj_trace("dump", obj, __FILE__, __LINE__, depth, TraceOut);
1485
+ }
1486
+ return;
1487
+ }
1488
+ }
1489
+ oj_dump_nil(Qnil, depth, out, false);
1490
+ if (Yes == out->opts->trace) {
1491
+ oj_trace("dump", Qnil, __FILE__, __LINE__, depth, TraceOut);
1492
+ }
1493
+ }
1494
+
1495
+ void oj_dump_rails_val(VALUE obj, int depth, Out out) {
1496
+ out->opts->str_rx.head = NULL;
1497
+ out->opts->str_rx.tail = NULL;
1498
+ if (escape_html) {
1499
+ out->opts->escape_mode = RailsXEsc;
1500
+ } else {
1501
+ out->opts->escape_mode = RailsEsc;
1502
+ }
1503
+ dump_rails_val(obj, depth, out, true);
1504
+ }