json-extended 2.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1997 @@
1
+ #include "../json.h"
2
+ #include "../fbuffer/fbuffer.h"
3
+ #include "../vendor/fpconv.c"
4
+
5
+ #include <math.h>
6
+ #include <ctype.h>
7
+
8
+ #include "../simd/simd.h"
9
+
10
+ /* ruby api and some helpers */
11
+
12
+ enum duplicate_key_action {
13
+ JSON_DEPRECATED = 0,
14
+ JSON_IGNORE,
15
+ JSON_RAISE,
16
+ };
17
+
18
+ typedef struct JSON_Generator_StateStruct {
19
+ VALUE indent;
20
+ VALUE space;
21
+ VALUE space_before;
22
+ VALUE object_nl;
23
+ VALUE array_nl;
24
+ VALUE as_json;
25
+
26
+ long max_nesting;
27
+ long depth;
28
+ long buffer_initial_length;
29
+
30
+ enum duplicate_key_action on_duplicate_key;
31
+
32
+ bool as_json_single_arg;
33
+ bool allow_nan;
34
+ bool ascii_only;
35
+ bool script_safe;
36
+ bool strict;
37
+ } JSON_Generator_State;
38
+
39
+ static VALUE mJSON, cState, cFragment, eGeneratorError, eNestingError, Encoding_UTF_8;
40
+
41
+ static ID i_to_s, i_to_json, i_new, i_encode;
42
+ static VALUE sym_indent, sym_space, sym_space_before, sym_object_nl, sym_array_nl, sym_max_nesting, sym_allow_nan, sym_allow_duplicate_key,
43
+ sym_ascii_only, sym_depth, sym_buffer_initial_length, sym_script_safe, sym_escape_slash, sym_strict, sym_as_json;
44
+
45
+
46
+ #define GET_STATE_TO(self, state) \
47
+ TypedData_Get_Struct(self, JSON_Generator_State, &JSON_Generator_State_type, state)
48
+
49
+ #define GET_STATE(self) \
50
+ JSON_Generator_State *state; \
51
+ GET_STATE_TO(self, state)
52
+
53
+ struct generate_json_data;
54
+
55
+ typedef void (*generator_func)(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
56
+
57
+ struct generate_json_data {
58
+ FBuffer *buffer;
59
+ VALUE vstate;
60
+ JSON_Generator_State *state;
61
+ VALUE obj;
62
+ generator_func func;
63
+ long depth;
64
+ };
65
+
66
+ static SIMD_Implementation simd_impl;
67
+
68
+ static VALUE cState_from_state_s(VALUE self, VALUE opts);
69
+ static VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func, VALUE io);
70
+ static void generate_json(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
71
+ static void generate_json_object(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
72
+ static void generate_json_array(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
73
+ static void generate_json_string(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
74
+ static void generate_json_null(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
75
+ static void generate_json_false(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
76
+ static void generate_json_true(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
77
+ static void generate_json_fixnum(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
78
+ static void generate_json_bignum(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
79
+ static void generate_json_float(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
80
+ static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
81
+
82
+ static int usascii_encindex, utf8_encindex, binary_encindex;
83
+
84
+ NORETURN(static void) raise_generator_error_str(VALUE invalid_object, VALUE str)
85
+ {
86
+ rb_enc_associate_index(str, utf8_encindex);
87
+ VALUE exc = rb_exc_new_str(eGeneratorError, str);
88
+ rb_ivar_set(exc, rb_intern("@invalid_object"), invalid_object);
89
+ rb_exc_raise(exc);
90
+ }
91
+
92
+ #ifdef RBIMPL_ATTR_FORMAT
93
+ RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 3)
94
+ #endif
95
+ NORETURN(static void) raise_generator_error(VALUE invalid_object, const char *fmt, ...)
96
+ {
97
+ va_list args;
98
+ va_start(args, fmt);
99
+ VALUE str = rb_vsprintf(fmt, args);
100
+ va_end(args);
101
+ raise_generator_error_str(invalid_object, str);
102
+ }
103
+
104
+ // 0 - single byte char that don't need to be escaped.
105
+ // (x | 8) - char that needs to be escaped.
106
+ static const unsigned char CHAR_LENGTH_MASK = 7;
107
+ static const unsigned char ESCAPE_MASK = 8;
108
+
109
+ typedef struct _search_state {
110
+ const char *ptr;
111
+ const char *end;
112
+ const char *cursor;
113
+ FBuffer *buffer;
114
+
115
+ #ifdef HAVE_SIMD
116
+ const char *chunk_base;
117
+ const char *chunk_end;
118
+ bool has_matches;
119
+
120
+ #if defined(HAVE_SIMD_NEON)
121
+ uint64_t matches_mask;
122
+ #elif defined(HAVE_SIMD_SSE2)
123
+ int matches_mask;
124
+ #else
125
+ #error "Unknown SIMD Implementation."
126
+ #endif /* HAVE_SIMD_NEON */
127
+ #endif /* HAVE_SIMD */
128
+ } search_state;
129
+
130
+ ALWAYS_INLINE(static) void search_flush(search_state *search)
131
+ {
132
+ // Do not remove this conditional without profiling, specifically escape-heavy text.
133
+ // escape_UTF8_char_basic will advance search->ptr and search->cursor (effectively a search_flush).
134
+ // For back-to-back characters that need to be escaped, specifically for the SIMD code paths, this method
135
+ // will be called just before calling escape_UTF8_char_basic. There will be no characters to append for the
136
+ // consecutive characters that need to be escaped. While the fbuffer_append is a no-op if
137
+ // nothing needs to be flushed, we can save a few memory references with this conditional.
138
+ if (search->ptr > search->cursor) {
139
+ fbuffer_append(search->buffer, search->cursor, search->ptr - search->cursor);
140
+ search->cursor = search->ptr;
141
+ }
142
+ }
143
+
144
+ static const unsigned char escape_table_basic[256] = {
145
+ // ASCII Control Characters
146
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
147
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
148
+ // ASCII Characters
149
+ 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // '"'
150
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
151
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
152
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, // '\\'
153
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
154
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
155
+ };
156
+
157
+ static inline unsigned char search_escape_basic(search_state *search)
158
+ {
159
+ while (search->ptr < search->end) {
160
+ if (RB_UNLIKELY(escape_table_basic[(const unsigned char)*search->ptr])) {
161
+ search_flush(search);
162
+ return 1;
163
+ } else {
164
+ search->ptr++;
165
+ }
166
+ }
167
+ search_flush(search);
168
+ return 0;
169
+ }
170
+
171
+ ALWAYS_INLINE(static) void escape_UTF8_char_basic(search_state *search)
172
+ {
173
+ const unsigned char ch = (unsigned char)*search->ptr;
174
+ switch (ch) {
175
+ case '"': fbuffer_append(search->buffer, "\\\"", 2); break;
176
+ case '\\': fbuffer_append(search->buffer, "\\\\", 2); break;
177
+ case '/': fbuffer_append(search->buffer, "\\/", 2); break;
178
+ case '\b': fbuffer_append(search->buffer, "\\b", 2); break;
179
+ case '\f': fbuffer_append(search->buffer, "\\f", 2); break;
180
+ case '\n': fbuffer_append(search->buffer, "\\n", 2); break;
181
+ case '\r': fbuffer_append(search->buffer, "\\r", 2); break;
182
+ case '\t': fbuffer_append(search->buffer, "\\t", 2); break;
183
+ default: {
184
+ const char *hexdig = "0123456789abcdef";
185
+ char scratch[6] = { '\\', 'u', '0', '0', 0, 0 };
186
+ scratch[4] = hexdig[(ch >> 4) & 0xf];
187
+ scratch[5] = hexdig[ch & 0xf];
188
+ fbuffer_append(search->buffer, scratch, 6);
189
+ break;
190
+ }
191
+ }
192
+ search->ptr++;
193
+ search->cursor = search->ptr;
194
+ }
195
+
196
+ /* Converts in_string to a JSON string (without the wrapping '"'
197
+ * characters) in FBuffer out_buffer.
198
+ *
199
+ * Character are JSON-escaped according to:
200
+ *
201
+ * - Always: ASCII control characters (0x00-0x1F), dquote, and
202
+ * backslash.
203
+ *
204
+ * - If out_ascii_only: non-ASCII characters (>0x7F)
205
+ *
206
+ * - If script_safe: forwardslash (/), line separator (U+2028), and
207
+ * paragraph separator (U+2029)
208
+ *
209
+ * Everything else (should be UTF-8) is just passed through and
210
+ * appended to the result.
211
+ */
212
+
213
+
214
+ #if defined(HAVE_SIMD_NEON)
215
+ static inline unsigned char search_escape_basic_neon(search_state *search);
216
+ #elif defined(HAVE_SIMD_SSE2)
217
+ static inline unsigned char search_escape_basic_sse2(search_state *search);
218
+ #endif
219
+
220
+ static inline unsigned char search_escape_basic(search_state *search);
221
+
222
+ static inline void convert_UTF8_to_JSON(search_state *search)
223
+ {
224
+ #ifdef HAVE_SIMD
225
+ #if defined(HAVE_SIMD_NEON)
226
+ while (search_escape_basic_neon(search)) {
227
+ escape_UTF8_char_basic(search);
228
+ }
229
+ #elif defined(HAVE_SIMD_SSE2)
230
+ if (simd_impl == SIMD_SSE2) {
231
+ while (search_escape_basic_sse2(search)) {
232
+ escape_UTF8_char_basic(search);
233
+ }
234
+ return;
235
+ }
236
+ while (search_escape_basic(search)) {
237
+ escape_UTF8_char_basic(search);
238
+ }
239
+ #endif
240
+ #else
241
+ while (search_escape_basic(search)) {
242
+ escape_UTF8_char_basic(search);
243
+ }
244
+ #endif /* HAVE_SIMD */
245
+ }
246
+
247
+ static inline void escape_UTF8_char(search_state *search, unsigned char ch_len)
248
+ {
249
+ const unsigned char ch = (unsigned char)*search->ptr;
250
+ switch (ch_len) {
251
+ case 1: {
252
+ switch (ch) {
253
+ case '"': fbuffer_append(search->buffer, "\\\"", 2); break;
254
+ case '\\': fbuffer_append(search->buffer, "\\\\", 2); break;
255
+ case '/': fbuffer_append(search->buffer, "\\/", 2); break;
256
+ case '\b': fbuffer_append(search->buffer, "\\b", 2); break;
257
+ case '\f': fbuffer_append(search->buffer, "\\f", 2); break;
258
+ case '\n': fbuffer_append(search->buffer, "\\n", 2); break;
259
+ case '\r': fbuffer_append(search->buffer, "\\r", 2); break;
260
+ case '\t': fbuffer_append(search->buffer, "\\t", 2); break;
261
+ default: {
262
+ const char *hexdig = "0123456789abcdef";
263
+ char scratch[6] = { '\\', 'u', '0', '0', 0, 0 };
264
+ scratch[4] = hexdig[(ch >> 4) & 0xf];
265
+ scratch[5] = hexdig[ch & 0xf];
266
+ fbuffer_append(search->buffer, scratch, 6);
267
+ break;
268
+ }
269
+ }
270
+ break;
271
+ }
272
+ case 3: {
273
+ if (search->ptr[2] & 1) {
274
+ fbuffer_append(search->buffer, "\\u2029", 6);
275
+ } else {
276
+ fbuffer_append(search->buffer, "\\u2028", 6);
277
+ }
278
+ break;
279
+ }
280
+ }
281
+ search->cursor = (search->ptr += ch_len);
282
+ }
283
+
284
+ #ifdef HAVE_SIMD
285
+
286
+ ALWAYS_INLINE(static) char *copy_remaining_bytes(search_state *search, unsigned long vec_len, unsigned long len)
287
+ {
288
+ RBIMPL_ASSERT_OR_ASSUME(len < vec_len);
289
+
290
+ // Flush the buffer so everything up until the last 'len' characters are unflushed.
291
+ search_flush(search);
292
+
293
+ FBuffer *buf = search->buffer;
294
+ fbuffer_inc_capa(buf, vec_len);
295
+
296
+ char *s = (buf->ptr + buf->len);
297
+
298
+ // Pad the buffer with dummy characters that won't need escaping.
299
+ // This seem wasteful at first sight, but memset of vector length is very fast.
300
+ // This is a space as it can be directly represented as an immediate on AArch64.
301
+ memset(s, ' ', vec_len);
302
+
303
+ // Optimistically copy the remaining 'len' characters to the output FBuffer. If there are no characters
304
+ // to escape, then everything ends up in the correct spot. Otherwise it was convenient temporary storage.
305
+ if (vec_len == 16) {
306
+ RBIMPL_ASSERT_OR_ASSUME(len >= SIMD_MINIMUM_THRESHOLD);
307
+ json_fast_memcpy16(s, search->ptr, len);
308
+ } else {
309
+ MEMCPY(s, search->ptr, char, len);
310
+ }
311
+
312
+ return s;
313
+ }
314
+
315
+ #ifdef HAVE_SIMD_NEON
316
+
317
+ ALWAYS_INLINE(static) unsigned char neon_next_match(search_state *search)
318
+ {
319
+ uint64_t mask = search->matches_mask;
320
+ uint32_t index = trailing_zeros64(mask) >> 2;
321
+
322
+ // It is assumed escape_UTF8_char_basic will only ever increase search->ptr by at most one character.
323
+ // If we want to use a similar approach for full escaping we'll need to ensure:
324
+ // search->chunk_base + index >= search->ptr
325
+ // However, since we know escape_UTF8_char_basic only increases search->ptr by one, if the next match
326
+ // is one byte after the previous match then:
327
+ // search->chunk_base + index == search->ptr
328
+ search->ptr = search->chunk_base + index;
329
+ mask &= mask - 1;
330
+ search->matches_mask = mask;
331
+ search_flush(search);
332
+ return 1;
333
+ }
334
+
335
+ static inline unsigned char search_escape_basic_neon(search_state *search)
336
+ {
337
+ if (RB_UNLIKELY(search->has_matches)) {
338
+ // There are more matches if search->matches_mask > 0.
339
+ if (search->matches_mask > 0) {
340
+ return neon_next_match(search);
341
+ } else {
342
+ // neon_next_match will only advance search->ptr up to the last matching character.
343
+ // Skip over any characters in the last chunk that occur after the last match.
344
+ search->has_matches = false;
345
+ search->ptr = search->chunk_end;
346
+ }
347
+ }
348
+
349
+ /*
350
+ * The code below implements an SIMD-based algorithm to determine if N bytes at a time
351
+ * need to be escaped.
352
+ *
353
+ * Assume the ptr = "Te\sting!" (the double quotes are included in the string)
354
+ *
355
+ * The explanation will be limited to the first 8 bytes of the string for simplicity. However
356
+ * the vector insructions may work on larger vectors.
357
+ *
358
+ * First, we load three constants 'lower_bound', 'backslash' and 'dblquote" in vector registers.
359
+ *
360
+ * lower_bound: [20 20 20 20 20 20 20 20]
361
+ * backslash: [5C 5C 5C 5C 5C 5C 5C 5C]
362
+ * dblquote: [22 22 22 22 22 22 22 22]
363
+ *
364
+ * Next we load the first chunk of the ptr:
365
+ * [22 54 65 5C 73 74 69 6E] (" T e \ s t i n)
366
+ *
367
+ * First we check if any byte in chunk is less than 32 (0x20). This returns the following vector
368
+ * as no bytes are less than 32 (0x20):
369
+ * [0 0 0 0 0 0 0 0]
370
+ *
371
+ * Next, we check if any byte in chunk is equal to a backslash:
372
+ * [0 0 0 FF 0 0 0 0]
373
+ *
374
+ * Finally we check if any byte in chunk is equal to a double quote:
375
+ * [FF 0 0 0 0 0 0 0]
376
+ *
377
+ * Now we have three vectors where each byte indicates if the corresponding byte in chunk
378
+ * needs to be escaped. We combine these vectors with a series of logical OR instructions.
379
+ * This is the needs_escape vector and it is equal to:
380
+ * [FF 0 0 FF 0 0 0 0]
381
+ *
382
+ * Next we compute the bitwise AND between each byte and 0x1 and compute the horizontal sum of
383
+ * the values in the vector. This computes how many bytes need to be escaped within this chunk.
384
+ *
385
+ * Finally we compute a mask that indicates which bytes need to be escaped. If the mask is 0 then,
386
+ * no bytes need to be escaped and we can continue to the next chunk. If the mask is not 0 then we
387
+ * have at least one byte that needs to be escaped.
388
+ */
389
+
390
+ if (string_scan_simd_neon(&search->ptr, search->end, &search->matches_mask)) {
391
+ search->has_matches = true;
392
+ search->chunk_base = search->ptr;
393
+ search->chunk_end = search->ptr + sizeof(uint8x16_t);
394
+ return neon_next_match(search);
395
+ }
396
+
397
+ // There are fewer than 16 bytes left.
398
+ unsigned long remaining = (search->end - search->ptr);
399
+ if (remaining >= SIMD_MINIMUM_THRESHOLD) {
400
+ char *s = copy_remaining_bytes(search, sizeof(uint8x16_t), remaining);
401
+
402
+ uint64_t mask = compute_chunk_mask_neon(s);
403
+
404
+ if (!mask) {
405
+ // Nothing to escape, ensure search_flush doesn't do anything by setting
406
+ // search->cursor to search->ptr.
407
+ fbuffer_consumed(search->buffer, remaining);
408
+ search->ptr = search->end;
409
+ search->cursor = search->end;
410
+ return 0;
411
+ }
412
+
413
+ search->matches_mask = mask;
414
+ search->has_matches = true;
415
+ search->chunk_end = search->end;
416
+ search->chunk_base = search->ptr;
417
+ return neon_next_match(search);
418
+ }
419
+
420
+ if (search->ptr < search->end) {
421
+ return search_escape_basic(search);
422
+ }
423
+
424
+ search_flush(search);
425
+ return 0;
426
+ }
427
+ #endif /* HAVE_SIMD_NEON */
428
+
429
+ #ifdef HAVE_SIMD_SSE2
430
+
431
+ ALWAYS_INLINE(static) unsigned char sse2_next_match(search_state *search)
432
+ {
433
+ int mask = search->matches_mask;
434
+ int index = trailing_zeros(mask);
435
+
436
+ // It is assumed escape_UTF8_char_basic will only ever increase search->ptr by at most one character.
437
+ // If we want to use a similar approach for full escaping we'll need to ensure:
438
+ // search->chunk_base + index >= search->ptr
439
+ // However, since we know escape_UTF8_char_basic only increases search->ptr by one, if the next match
440
+ // is one byte after the previous match then:
441
+ // search->chunk_base + index == search->ptr
442
+ search->ptr = search->chunk_base + index;
443
+ mask &= mask - 1;
444
+ search->matches_mask = mask;
445
+ search_flush(search);
446
+ return 1;
447
+ }
448
+
449
+ #if defined(__clang__) || defined(__GNUC__)
450
+ #define TARGET_SSE2 __attribute__((target("sse2")))
451
+ #else
452
+ #define TARGET_SSE2
453
+ #endif
454
+
455
+ ALWAYS_INLINE(static) TARGET_SSE2 unsigned char search_escape_basic_sse2(search_state *search)
456
+ {
457
+ if (RB_UNLIKELY(search->has_matches)) {
458
+ // There are more matches if search->matches_mask > 0.
459
+ if (search->matches_mask > 0) {
460
+ return sse2_next_match(search);
461
+ } else {
462
+ // sse2_next_match will only advance search->ptr up to the last matching character.
463
+ // Skip over any characters in the last chunk that occur after the last match.
464
+ search->has_matches = false;
465
+ if (RB_UNLIKELY(search->chunk_base + sizeof(__m128i) >= search->end)) {
466
+ search->ptr = search->end;
467
+ } else {
468
+ search->ptr = search->chunk_base + sizeof(__m128i);
469
+ }
470
+ }
471
+ }
472
+
473
+ if (string_scan_simd_sse2(&search->ptr, search->end, &search->matches_mask)) {
474
+ search->has_matches = true;
475
+ search->chunk_base = search->ptr;
476
+ search->chunk_end = search->ptr + sizeof(__m128i);
477
+ return sse2_next_match(search);
478
+ }
479
+
480
+ // There are fewer than 16 bytes left.
481
+ unsigned long remaining = (search->end - search->ptr);
482
+ if (remaining >= SIMD_MINIMUM_THRESHOLD) {
483
+ char *s = copy_remaining_bytes(search, sizeof(__m128i), remaining);
484
+
485
+ int needs_escape_mask = compute_chunk_mask_sse2(s);
486
+
487
+ if (needs_escape_mask == 0) {
488
+ // Nothing to escape, ensure search_flush doesn't do anything by setting
489
+ // search->cursor to search->ptr.
490
+ fbuffer_consumed(search->buffer, remaining);
491
+ search->ptr = search->end;
492
+ search->cursor = search->end;
493
+ return 0;
494
+ }
495
+
496
+ search->has_matches = true;
497
+ search->matches_mask = needs_escape_mask;
498
+ search->chunk_base = search->ptr;
499
+ return sse2_next_match(search);
500
+ }
501
+
502
+ if (search->ptr < search->end) {
503
+ return search_escape_basic(search);
504
+ }
505
+
506
+ search_flush(search);
507
+ return 0;
508
+ }
509
+
510
+ #endif /* HAVE_SIMD_SSE2 */
511
+
512
+ #endif /* HAVE_SIMD */
513
+
514
+ static const unsigned char script_safe_escape_table[256] = {
515
+ // ASCII Control Characters
516
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
517
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
518
+ // ASCII Characters
519
+ 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, // '"' and '/'
520
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
521
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
522
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, // '\\'
523
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
524
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
525
+ // Continuation byte
526
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
527
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
528
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
529
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
530
+ // First byte of a 2-byte code point
531
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
532
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
533
+ // First byte of a 3-byte code point
534
+ 3, 3,11, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xE2 is the start of \u2028 and \u2029
535
+ //First byte of a 4+ byte code point
536
+ 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 9, 9,
537
+ };
538
+
539
+ static inline unsigned char search_script_safe_escape(search_state *search)
540
+ {
541
+ while (search->ptr < search->end) {
542
+ unsigned char ch = (unsigned char)*search->ptr;
543
+ unsigned char ch_len = script_safe_escape_table[ch];
544
+
545
+ if (RB_UNLIKELY(ch_len)) {
546
+ if (ch_len & ESCAPE_MASK) {
547
+ if (RB_UNLIKELY(ch_len == 11)) {
548
+ const unsigned char *uptr = (const unsigned char *)search->ptr;
549
+ if (!(uptr[1] == 0x80 && (uptr[2] >> 1) == 0x54)) {
550
+ search->ptr += 3;
551
+ continue;
552
+ }
553
+ }
554
+ search_flush(search);
555
+ return ch_len & CHAR_LENGTH_MASK;
556
+ } else {
557
+ search->ptr += ch_len;
558
+ }
559
+ } else {
560
+ search->ptr++;
561
+ }
562
+ }
563
+ search_flush(search);
564
+ return 0;
565
+ }
566
+
567
+ static void convert_UTF8_to_script_safe_JSON(search_state *search)
568
+ {
569
+ unsigned char ch_len;
570
+ while ((ch_len = search_script_safe_escape(search))) {
571
+ escape_UTF8_char(search, ch_len);
572
+ }
573
+ }
574
+
575
+ static const unsigned char ascii_only_escape_table[256] = {
576
+ // ASCII Control Characters
577
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
578
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
579
+ // ASCII Characters
580
+ 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // '"'
581
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
582
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
583
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, // '\\'
584
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
585
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
586
+ // Continuation byte
587
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
588
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
589
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
590
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
591
+ // First byte of a 2-byte code point
592
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
593
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
594
+ // First byte of a 3-byte code point
595
+ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
596
+ //First byte of a 4+ byte code point
597
+ 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 9, 9,
598
+ };
599
+
600
+ static inline unsigned char search_ascii_only_escape(search_state *search, const unsigned char escape_table[256])
601
+ {
602
+ while (search->ptr < search->end) {
603
+ unsigned char ch = (unsigned char)*search->ptr;
604
+ unsigned char ch_len = escape_table[ch];
605
+
606
+ if (RB_UNLIKELY(ch_len)) {
607
+ search_flush(search);
608
+ return ch_len & CHAR_LENGTH_MASK;
609
+ } else {
610
+ search->ptr++;
611
+ }
612
+ }
613
+ search_flush(search);
614
+ return 0;
615
+ }
616
+
617
+ static inline void full_escape_UTF8_char(search_state *search, unsigned char ch_len)
618
+ {
619
+ const unsigned char ch = (unsigned char)*search->ptr;
620
+ switch (ch_len) {
621
+ case 1: {
622
+ switch (ch) {
623
+ case '"': fbuffer_append(search->buffer, "\\\"", 2); break;
624
+ case '\\': fbuffer_append(search->buffer, "\\\\", 2); break;
625
+ case '/': fbuffer_append(search->buffer, "\\/", 2); break;
626
+ case '\b': fbuffer_append(search->buffer, "\\b", 2); break;
627
+ case '\f': fbuffer_append(search->buffer, "\\f", 2); break;
628
+ case '\n': fbuffer_append(search->buffer, "\\n", 2); break;
629
+ case '\r': fbuffer_append(search->buffer, "\\r", 2); break;
630
+ case '\t': fbuffer_append(search->buffer, "\\t", 2); break;
631
+ default: {
632
+ const char *hexdig = "0123456789abcdef";
633
+ char scratch[6] = { '\\', 'u', '0', '0', 0, 0 };
634
+ scratch[4] = hexdig[(ch >> 4) & 0xf];
635
+ scratch[5] = hexdig[ch & 0xf];
636
+ fbuffer_append(search->buffer, scratch, 6);
637
+ break;
638
+ }
639
+ }
640
+ break;
641
+ }
642
+ default: {
643
+ const char *hexdig = "0123456789abcdef";
644
+ char scratch[12] = { '\\', 'u', 0, 0, 0, 0, '\\', 'u' };
645
+
646
+ uint32_t wchar = 0;
647
+
648
+ switch (ch_len) {
649
+ case 2:
650
+ wchar = ch & 0x1F;
651
+ break;
652
+ case 3:
653
+ wchar = ch & 0x0F;
654
+ break;
655
+ case 4:
656
+ wchar = ch & 0x07;
657
+ break;
658
+ }
659
+
660
+ for (short i = 1; i < ch_len; i++) {
661
+ wchar = (wchar << 6) | (search->ptr[i] & 0x3F);
662
+ }
663
+
664
+ if (wchar <= 0xFFFF) {
665
+ scratch[2] = hexdig[wchar >> 12];
666
+ scratch[3] = hexdig[(wchar >> 8) & 0xf];
667
+ scratch[4] = hexdig[(wchar >> 4) & 0xf];
668
+ scratch[5] = hexdig[wchar & 0xf];
669
+ fbuffer_append(search->buffer, scratch, 6);
670
+ } else {
671
+ uint16_t hi, lo;
672
+ wchar -= 0x10000;
673
+ hi = 0xD800 + (uint16_t)(wchar >> 10);
674
+ lo = 0xDC00 + (uint16_t)(wchar & 0x3FF);
675
+
676
+ scratch[2] = hexdig[hi >> 12];
677
+ scratch[3] = hexdig[(hi >> 8) & 0xf];
678
+ scratch[4] = hexdig[(hi >> 4) & 0xf];
679
+ scratch[5] = hexdig[hi & 0xf];
680
+
681
+ scratch[8] = hexdig[lo >> 12];
682
+ scratch[9] = hexdig[(lo >> 8) & 0xf];
683
+ scratch[10] = hexdig[(lo >> 4) & 0xf];
684
+ scratch[11] = hexdig[lo & 0xf];
685
+
686
+ fbuffer_append(search->buffer, scratch, 12);
687
+ }
688
+
689
+ break;
690
+ }
691
+ }
692
+ search->cursor = (search->ptr += ch_len);
693
+ }
694
+
695
+ static void convert_UTF8_to_ASCII_only_JSON(search_state *search, const unsigned char escape_table[256])
696
+ {
697
+ unsigned char ch_len;
698
+ while ((ch_len = search_ascii_only_escape(search, escape_table))) {
699
+ full_escape_UTF8_char(search, ch_len);
700
+ }
701
+ }
702
+
703
+ static void State_mark(void *ptr)
704
+ {
705
+ JSON_Generator_State *state = ptr;
706
+ rb_gc_mark_movable(state->indent);
707
+ rb_gc_mark_movable(state->space);
708
+ rb_gc_mark_movable(state->space_before);
709
+ rb_gc_mark_movable(state->object_nl);
710
+ rb_gc_mark_movable(state->array_nl);
711
+ rb_gc_mark_movable(state->as_json);
712
+ }
713
+
714
+ static void State_compact(void *ptr)
715
+ {
716
+ JSON_Generator_State *state = ptr;
717
+ state->indent = rb_gc_location(state->indent);
718
+ state->space = rb_gc_location(state->space);
719
+ state->space_before = rb_gc_location(state->space_before);
720
+ state->object_nl = rb_gc_location(state->object_nl);
721
+ state->array_nl = rb_gc_location(state->array_nl);
722
+ state->as_json = rb_gc_location(state->as_json);
723
+ }
724
+
725
+ static size_t State_memsize(const void *ptr)
726
+ {
727
+ #ifdef HAVE_RUBY_TYPED_EMBEDDABLE
728
+ return 0;
729
+ #else
730
+ return sizeof(JSON_Generator_State);
731
+ #endif
732
+ }
733
+
734
+ static const rb_data_type_t JSON_Generator_State_type = {
735
+ .wrap_struct_name = "JSON/Generator/State",
736
+ .function = {
737
+ .dmark = State_mark,
738
+ .dfree = RUBY_DEFAULT_FREE,
739
+ .dsize = State_memsize,
740
+ .dcompact = State_compact,
741
+ },
742
+ .flags = RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE | RUBY_TYPED_EMBEDDABLE,
743
+ };
744
+
745
+ static void state_init(JSON_Generator_State *state)
746
+ {
747
+ state->max_nesting = 100;
748
+ state->buffer_initial_length = FBUFFER_INITIAL_LENGTH_DEFAULT;
749
+ }
750
+
751
+ static VALUE cState_s_allocate(VALUE klass)
752
+ {
753
+ JSON_Generator_State *state;
754
+ VALUE obj = TypedData_Make_Struct(klass, JSON_Generator_State, &JSON_Generator_State_type, state);
755
+ state_init(state);
756
+ return obj;
757
+ }
758
+
759
+ static void vstate_spill(struct generate_json_data *data)
760
+ {
761
+ VALUE vstate = cState_s_allocate(cState);
762
+ GET_STATE(vstate);
763
+ MEMCPY(state, data->state, JSON_Generator_State, 1);
764
+ data->state = state;
765
+ data->vstate = vstate;
766
+ RB_OBJ_WRITTEN(vstate, Qundef, state->indent);
767
+ RB_OBJ_WRITTEN(vstate, Qundef, state->space);
768
+ RB_OBJ_WRITTEN(vstate, Qundef, state->space_before);
769
+ RB_OBJ_WRITTEN(vstate, Qundef, state->object_nl);
770
+ RB_OBJ_WRITTEN(vstate, Qundef, state->array_nl);
771
+ RB_OBJ_WRITTEN(vstate, Qundef, state->as_json);
772
+ }
773
+
774
+ static inline VALUE json_call_to_json(struct generate_json_data *data, VALUE obj)
775
+ {
776
+ if (RB_UNLIKELY(!data->vstate)) {
777
+ vstate_spill(data);
778
+ }
779
+ GET_STATE(data->vstate);
780
+ state->depth = data->depth;
781
+ VALUE tmp = rb_funcall(obj, i_to_json, 1, data->vstate);
782
+ // no need to restore state->depth, vstate is just a temporary State
783
+ return tmp;
784
+ }
785
+
786
+ static VALUE
787
+ json_call_as_json(JSON_Generator_State *state, VALUE object, VALUE is_key)
788
+ {
789
+ VALUE proc_args[2] = {object, is_key};
790
+ return rb_proc_call_with_block(state->as_json, 2, proc_args, Qnil);
791
+ }
792
+
793
+ static VALUE
794
+ convert_string_subclass(VALUE key)
795
+ {
796
+ VALUE key_to_s = rb_funcall(key, i_to_s, 0);
797
+
798
+ if (RB_UNLIKELY(!RB_TYPE_P(key_to_s, T_STRING))) {
799
+ VALUE cname = rb_obj_class(key);
800
+ rb_raise(rb_eTypeError,
801
+ "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")",
802
+ cname, "String", cname, "to_s", rb_obj_class(key_to_s));
803
+ }
804
+
805
+ return key_to_s;
806
+ }
807
+
808
+ static bool enc_utf8_compatible_p(int enc_idx)
809
+ {
810
+ if (enc_idx == usascii_encindex) return true;
811
+ if (enc_idx == utf8_encindex) return true;
812
+ return false;
813
+ }
814
+
815
+ static VALUE encode_json_string_try(VALUE str)
816
+ {
817
+ return rb_funcall(str, i_encode, 1, Encoding_UTF_8);
818
+ }
819
+
820
+ static VALUE encode_json_string_rescue(VALUE str, VALUE exception)
821
+ {
822
+ raise_generator_error_str(str, rb_funcall(exception, rb_intern("message"), 0));
823
+ return Qundef;
824
+ }
825
+
826
+ static inline int json_str_coderange(VALUE str) {
827
+ int coderange = RB_ENC_CODERANGE(str);
828
+ if (coderange == RUBY_ENC_CODERANGE_UNKNOWN) {
829
+ coderange = rb_enc_str_coderange(str);
830
+ }
831
+ return coderange;
832
+ }
833
+
834
+ static inline bool valid_json_string_p(VALUE str)
835
+ {
836
+ int coderange = json_str_coderange(str);
837
+
838
+ if (RB_LIKELY(coderange == ENC_CODERANGE_7BIT)) {
839
+ return true;
840
+ }
841
+
842
+ if (RB_LIKELY(coderange == ENC_CODERANGE_VALID)) {
843
+ return enc_utf8_compatible_p(RB_ENCODING_GET_INLINED(str));
844
+ }
845
+
846
+ return false;
847
+ }
848
+
849
+ NOINLINE(static) VALUE convert_invalid_encoding(struct generate_json_data *data, VALUE str, bool as_json_called, bool is_key)
850
+ {
851
+ if (!as_json_called && data->state->strict && RTEST(data->state->as_json)) {
852
+ VALUE coerced_str = json_call_as_json(data->state, str, Qfalse);
853
+ if (coerced_str != str) {
854
+ if (RB_TYPE_P(coerced_str, T_STRING)) {
855
+ if (!valid_json_string_p(coerced_str)) {
856
+ raise_generator_error(str, "source sequence is illegal/malformed utf-8");
857
+ }
858
+ } else {
859
+ // as_json could return another type than T_STRING
860
+ if (is_key) {
861
+ raise_generator_error(coerced_str, "%"PRIsVALUE" not allowed as object key in JSON", CLASS_OF(coerced_str));
862
+ }
863
+ }
864
+
865
+ return coerced_str;
866
+ }
867
+ }
868
+
869
+ if (RB_ENCODING_GET_INLINED(str) == binary_encindex) {
870
+ VALUE utf8_string = rb_enc_associate_index(rb_str_dup(str), utf8_encindex);
871
+ switch (rb_enc_str_coderange(utf8_string)) {
872
+ case ENC_CODERANGE_7BIT:
873
+ return utf8_string;
874
+ case ENC_CODERANGE_VALID:
875
+ // For historical reason, we silently reinterpret binary strings as UTF-8 if it would work.
876
+ // TODO: Raise in 3.0.0
877
+ rb_warn("JSON.generate: UTF-8 string passed as BINARY, this will raise an encoding error in json 3.0");
878
+ return utf8_string;
879
+ break;
880
+ }
881
+ }
882
+
883
+ return rb_rescue(encode_json_string_try, str, encode_json_string_rescue, str);
884
+ }
885
+
886
+ ALWAYS_INLINE(static) VALUE ensure_valid_encoding(struct generate_json_data *data, VALUE str, bool as_json_called, bool is_key)
887
+ {
888
+ if (RB_LIKELY(valid_json_string_p(str))) {
889
+ return str;
890
+ }
891
+ else {
892
+ return convert_invalid_encoding(data, str, as_json_called, is_key);
893
+ }
894
+ }
895
+
896
+ static void raw_generate_json_string(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
897
+ {
898
+ fbuffer_append_char(buffer, '"');
899
+
900
+ long len;
901
+ search_state search;
902
+ search.buffer = buffer;
903
+ RSTRING_GETMEM(obj, search.ptr, len);
904
+ search.cursor = search.ptr;
905
+ search.end = search.ptr + len;
906
+
907
+ #ifdef HAVE_SIMD
908
+ search.matches_mask = 0;
909
+ search.has_matches = false;
910
+ search.chunk_base = NULL;
911
+ search.chunk_end = NULL;
912
+ #endif /* HAVE_SIMD */
913
+
914
+ switch (json_str_coderange(obj)) {
915
+ case ENC_CODERANGE_7BIT:
916
+ case ENC_CODERANGE_VALID:
917
+ if (RB_UNLIKELY(data->state->ascii_only)) {
918
+ convert_UTF8_to_ASCII_only_JSON(&search, data->state->script_safe ? script_safe_escape_table : ascii_only_escape_table);
919
+ } else if (RB_UNLIKELY(data->state->script_safe)) {
920
+ convert_UTF8_to_script_safe_JSON(&search);
921
+ } else {
922
+ convert_UTF8_to_JSON(&search);
923
+ }
924
+ break;
925
+ default:
926
+ raise_generator_error(obj, "source sequence is illegal/malformed utf-8");
927
+ break;
928
+ }
929
+ fbuffer_append_char(buffer, '"');
930
+ }
931
+
932
+ static void generate_json_string(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
933
+ {
934
+ obj = ensure_valid_encoding(data, obj, false, false);
935
+ raw_generate_json_string(buffer, data, obj);
936
+ }
937
+
938
+ struct hash_foreach_arg {
939
+ VALUE hash;
940
+ struct generate_json_data *data;
941
+ int first_key_type;
942
+ bool first;
943
+ bool mixed_keys_encountered;
944
+ };
945
+
946
+ NOINLINE(static) void
947
+ json_inspect_hash_with_mixed_keys(struct hash_foreach_arg *arg)
948
+ {
949
+ if (arg->mixed_keys_encountered) {
950
+ return;
951
+ }
952
+ arg->mixed_keys_encountered = true;
953
+
954
+ JSON_Generator_State *state = arg->data->state;
955
+ if (state->on_duplicate_key != JSON_IGNORE) {
956
+ VALUE do_raise = state->on_duplicate_key == JSON_RAISE ? Qtrue : Qfalse;
957
+ rb_funcall(mJSON, rb_intern("on_mixed_keys_hash"), 2, arg->hash, do_raise);
958
+ }
959
+ }
960
+
961
+ static int
962
+ json_object_i(VALUE key, VALUE val, VALUE _arg)
963
+ {
964
+ struct hash_foreach_arg *arg = (struct hash_foreach_arg *)_arg;
965
+ struct generate_json_data *data = arg->data;
966
+
967
+ FBuffer *buffer = data->buffer;
968
+ JSON_Generator_State *state = data->state;
969
+
970
+ long depth = data->depth;
971
+ int key_type = rb_type(key);
972
+
973
+ if (arg->first) {
974
+ arg->first = false;
975
+ arg->first_key_type = key_type;
976
+ }
977
+ else {
978
+ fbuffer_append_char(buffer, ',');
979
+ }
980
+
981
+ if (RB_UNLIKELY(data->state->object_nl)) {
982
+ fbuffer_append_str(buffer, data->state->object_nl);
983
+ }
984
+ if (RB_UNLIKELY(data->state->indent)) {
985
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
986
+ }
987
+
988
+ VALUE key_to_s;
989
+ bool as_json_called = false;
990
+
991
+ start:
992
+ switch (key_type) {
993
+ case T_STRING:
994
+ if (RB_UNLIKELY(arg->first_key_type != T_STRING)) {
995
+ json_inspect_hash_with_mixed_keys(arg);
996
+ }
997
+
998
+ if (RB_LIKELY(RBASIC_CLASS(key) == rb_cString)) {
999
+ key_to_s = key;
1000
+ } else {
1001
+ key_to_s = convert_string_subclass(key);
1002
+ }
1003
+ break;
1004
+ case T_SYMBOL:
1005
+ if (RB_UNLIKELY(arg->first_key_type != T_SYMBOL)) {
1006
+ json_inspect_hash_with_mixed_keys(arg);
1007
+ }
1008
+
1009
+ key_to_s = rb_sym2str(key);
1010
+ break;
1011
+ default:
1012
+ if (data->state->strict) {
1013
+ if (RTEST(data->state->as_json) && !as_json_called) {
1014
+ key = json_call_as_json(data->state, key, Qtrue);
1015
+ key_type = rb_type(key);
1016
+ as_json_called = true;
1017
+ goto start;
1018
+ } else {
1019
+ raise_generator_error(key, "%"PRIsVALUE" not allowed as object key in JSON", CLASS_OF(key));
1020
+ }
1021
+ }
1022
+ key_to_s = rb_convert_type(key, T_STRING, "String", "to_s");
1023
+ break;
1024
+ }
1025
+
1026
+ key_to_s = ensure_valid_encoding(data, key_to_s, as_json_called, true);
1027
+
1028
+ if (RB_LIKELY(RBASIC_CLASS(key_to_s) == rb_cString)) {
1029
+ raw_generate_json_string(buffer, data, key_to_s);
1030
+ } else {
1031
+ generate_json(buffer, data, key_to_s);
1032
+ }
1033
+ if (RB_UNLIKELY(state->space_before)) fbuffer_append_str(buffer, data->state->space_before);
1034
+ fbuffer_append_char(buffer, ':');
1035
+ if (RB_UNLIKELY(state->space)) fbuffer_append_str(buffer, data->state->space);
1036
+ generate_json(buffer, data, val);
1037
+
1038
+ return ST_CONTINUE;
1039
+ }
1040
+
1041
+ static inline long increase_depth(struct generate_json_data *data)
1042
+ {
1043
+ JSON_Generator_State *state = data->state;
1044
+ long depth = ++data->depth;
1045
+ if (RB_UNLIKELY(depth > state->max_nesting && state->max_nesting)) {
1046
+ rb_raise(eNestingError, "nesting of %ld is too deep. Did you try to serialize objects with circular references?", --data->depth);
1047
+ }
1048
+ return depth;
1049
+ }
1050
+
1051
+ static void generate_json_object(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1052
+ {
1053
+ long depth = increase_depth(data);
1054
+
1055
+ if (RHASH_SIZE(obj) == 0) {
1056
+ fbuffer_append(buffer, "{}", 2);
1057
+ --data->depth;
1058
+ return;
1059
+ }
1060
+
1061
+ fbuffer_append_char(buffer, '{');
1062
+
1063
+ struct hash_foreach_arg arg = {
1064
+ .hash = obj,
1065
+ .data = data,
1066
+ .first = true,
1067
+ };
1068
+ rb_hash_foreach(obj, json_object_i, (VALUE)&arg);
1069
+
1070
+ depth = --data->depth;
1071
+ if (RB_UNLIKELY(data->state->object_nl)) {
1072
+ fbuffer_append_str(buffer, data->state->object_nl);
1073
+ if (RB_UNLIKELY(data->state->indent)) {
1074
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
1075
+ }
1076
+ }
1077
+ fbuffer_append_char(buffer, '}');
1078
+ }
1079
+
1080
+ static void generate_json_array(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1081
+ {
1082
+ long depth = increase_depth(data);
1083
+
1084
+ if (RARRAY_LEN(obj) == 0) {
1085
+ fbuffer_append(buffer, "[]", 2);
1086
+ --data->depth;
1087
+ return;
1088
+ }
1089
+
1090
+ fbuffer_append_char(buffer, '[');
1091
+ if (RB_UNLIKELY(data->state->array_nl)) fbuffer_append_str(buffer, data->state->array_nl);
1092
+ for (int i = 0; i < RARRAY_LEN(obj); i++) {
1093
+ if (i > 0) {
1094
+ fbuffer_append_char(buffer, ',');
1095
+ if (RB_UNLIKELY(data->state->array_nl)) fbuffer_append_str(buffer, data->state->array_nl);
1096
+ }
1097
+ if (RB_UNLIKELY(data->state->indent)) {
1098
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
1099
+ }
1100
+ generate_json(buffer, data, RARRAY_AREF(obj, i));
1101
+ }
1102
+ data->depth = --depth;
1103
+ if (RB_UNLIKELY(data->state->array_nl)) {
1104
+ fbuffer_append_str(buffer, data->state->array_nl);
1105
+ if (RB_UNLIKELY(data->state->indent)) {
1106
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
1107
+ }
1108
+ }
1109
+ fbuffer_append_char(buffer, ']');
1110
+ }
1111
+
1112
+ static void generate_json_fallback(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1113
+ {
1114
+ VALUE tmp;
1115
+ if (rb_respond_to(obj, i_to_json)) {
1116
+ tmp = json_call_to_json(data, obj);
1117
+ Check_Type(tmp, T_STRING);
1118
+ fbuffer_append_str(buffer, tmp);
1119
+ } else {
1120
+ tmp = rb_funcall(obj, i_to_s, 0);
1121
+ Check_Type(tmp, T_STRING);
1122
+ generate_json_string(buffer, data, tmp);
1123
+ }
1124
+ }
1125
+
1126
+ static inline void generate_json_symbol(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1127
+ {
1128
+ if (data->state->strict) {
1129
+ generate_json_string(buffer, data, rb_sym2str(obj));
1130
+ } else {
1131
+ generate_json_fallback(buffer, data, obj);
1132
+ }
1133
+ }
1134
+
1135
+ static void generate_json_null(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1136
+ {
1137
+ fbuffer_append(buffer, "null", 4);
1138
+ }
1139
+
1140
+ static void generate_json_false(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1141
+ {
1142
+ fbuffer_append(buffer, "false", 5);
1143
+ }
1144
+
1145
+ static void generate_json_true(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1146
+ {
1147
+ fbuffer_append(buffer, "true", 4);
1148
+ }
1149
+
1150
+ static void generate_json_fixnum(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1151
+ {
1152
+ fbuffer_append_long(buffer, FIX2LONG(obj));
1153
+ }
1154
+
1155
+ static void generate_json_bignum(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1156
+ {
1157
+ VALUE tmp = rb_funcall(obj, i_to_s, 0);
1158
+ fbuffer_append_str(buffer, StringValue(tmp));
1159
+ }
1160
+
1161
+ static void generate_json_float(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1162
+ {
1163
+ double value = RFLOAT_VALUE(obj);
1164
+ char allow_nan = data->state->allow_nan;
1165
+ if (isinf(value) || isnan(value)) {
1166
+ /* for NaN and Infinity values we either raise an error or rely on Float#to_s. */
1167
+ if (!allow_nan) {
1168
+ if (data->state->strict && data->state->as_json) {
1169
+ VALUE casted_obj = json_call_as_json(data->state, obj, Qfalse);
1170
+ if (casted_obj != obj) {
1171
+ increase_depth(data);
1172
+ generate_json(buffer, data, casted_obj);
1173
+ data->depth--;
1174
+ return;
1175
+ }
1176
+ }
1177
+ raise_generator_error(obj, "%"PRIsVALUE" not allowed in JSON", rb_funcall(obj, i_to_s, 0));
1178
+ }
1179
+
1180
+ VALUE tmp = rb_funcall(obj, i_to_s, 0);
1181
+ fbuffer_append_str(buffer, tmp);
1182
+ return;
1183
+ }
1184
+
1185
+ /* This implementation writes directly into the buffer. We reserve
1186
+ * the 32 characters that fpconv_dtoa states as its maximum.
1187
+ */
1188
+ fbuffer_inc_capa(buffer, 32);
1189
+ char* d = buffer->ptr + buffer->len;
1190
+ int len = fpconv_dtoa(value, d);
1191
+ /* fpconv_dtoa converts a float to its shortest string representation,
1192
+ * but it adds a ".0" if this is a plain integer.
1193
+ */
1194
+ fbuffer_consumed(buffer, len);
1195
+ }
1196
+
1197
+ static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1198
+ {
1199
+ VALUE fragment = RSTRUCT_GET(obj, 0);
1200
+ Check_Type(fragment, T_STRING);
1201
+ fbuffer_append_str(buffer, fragment);
1202
+ }
1203
+
1204
+ static inline void generate_json_general(FBuffer *buffer, struct generate_json_data *data, VALUE obj, bool fallback)
1205
+ {
1206
+ bool as_json_called = false;
1207
+ start:
1208
+ if (obj == Qnil) {
1209
+ generate_json_null(buffer, data, obj);
1210
+ } else if (obj == Qfalse) {
1211
+ generate_json_false(buffer, data, obj);
1212
+ } else if (obj == Qtrue) {
1213
+ generate_json_true(buffer, data, obj);
1214
+ } else if (RB_SPECIAL_CONST_P(obj)) {
1215
+ if (RB_FIXNUM_P(obj)) {
1216
+ generate_json_fixnum(buffer, data, obj);
1217
+ } else if (RB_FLONUM_P(obj)) {
1218
+ generate_json_float(buffer, data, obj);
1219
+ } else if (RB_STATIC_SYM_P(obj)) {
1220
+ generate_json_symbol(buffer, data, obj);
1221
+ } else {
1222
+ goto general;
1223
+ }
1224
+ } else {
1225
+ VALUE klass = RBASIC_CLASS(obj);
1226
+ switch (RB_BUILTIN_TYPE(obj)) {
1227
+ case T_BIGNUM:
1228
+ generate_json_bignum(buffer, data, obj);
1229
+ break;
1230
+ case T_HASH:
1231
+ if (fallback && klass != rb_cHash) goto general;
1232
+ generate_json_object(buffer, data, obj);
1233
+ break;
1234
+ case T_ARRAY:
1235
+ if (fallback && klass != rb_cArray) goto general;
1236
+ generate_json_array(buffer, data, obj);
1237
+ break;
1238
+ case T_STRING:
1239
+ if (fallback && klass != rb_cString) goto general;
1240
+
1241
+ if (RB_LIKELY(valid_json_string_p(obj))) {
1242
+ raw_generate_json_string(buffer, data, obj);
1243
+ } else if (as_json_called) {
1244
+ raise_generator_error(obj, "source sequence is illegal/malformed utf-8");
1245
+ } else {
1246
+ obj = ensure_valid_encoding(data, obj, false, false);
1247
+ as_json_called = true;
1248
+ goto start;
1249
+ }
1250
+ break;
1251
+ case T_SYMBOL:
1252
+ generate_json_symbol(buffer, data, obj);
1253
+ break;
1254
+ case T_FLOAT:
1255
+ if (fallback && klass != rb_cFloat) goto general;
1256
+ generate_json_float(buffer, data, obj);
1257
+ break;
1258
+ case T_STRUCT:
1259
+ if (klass != cFragment) goto general;
1260
+ generate_json_fragment(buffer, data, obj);
1261
+ break;
1262
+ default:
1263
+ general:
1264
+ if (data->state->strict) {
1265
+ if (RTEST(data->state->as_json) && !as_json_called) {
1266
+ obj = json_call_as_json(data->state, obj, Qfalse);
1267
+ as_json_called = true;
1268
+ goto start;
1269
+ } else {
1270
+ raise_generator_error(obj, "%"PRIsVALUE" not allowed in JSON", CLASS_OF(obj));
1271
+ }
1272
+ } else {
1273
+ generate_json_fallback(buffer, data, obj);
1274
+ }
1275
+ }
1276
+ }
1277
+ }
1278
+
1279
+ static void generate_json(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1280
+ {
1281
+ generate_json_general(buffer, data, obj, true);
1282
+ }
1283
+
1284
+ static void generate_json_no_fallback(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1285
+ {
1286
+ generate_json_general(buffer, data, obj, false);
1287
+ }
1288
+
1289
+ static VALUE generate_json_try(VALUE d)
1290
+ {
1291
+ struct generate_json_data *data = (struct generate_json_data *)d;
1292
+
1293
+ data->func(data->buffer, data, data->obj);
1294
+
1295
+ return fbuffer_finalize(data->buffer);
1296
+ }
1297
+
1298
+ static VALUE generate_json_ensure(VALUE d)
1299
+ {
1300
+ struct generate_json_data *data = (struct generate_json_data *)d;
1301
+ fbuffer_free(data->buffer);
1302
+
1303
+ return Qundef;
1304
+ }
1305
+
1306
+ static inline VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func func, VALUE io)
1307
+ {
1308
+ GET_STATE(self);
1309
+
1310
+ char stack_buffer[FBUFFER_STACK_SIZE];
1311
+ FBuffer buffer = { 0 };
1312
+ fbuffer_init(&buffer, state->buffer_initial_length, io, stack_buffer, FBUFFER_STACK_SIZE);
1313
+
1314
+ struct generate_json_data data = {
1315
+ .buffer = &buffer,
1316
+ .vstate = Qfalse, // don't use self as it may be frozen and its depth is mutated when calling to_json
1317
+ .state = state,
1318
+ .depth = state->depth,
1319
+ .obj = obj,
1320
+ .func = func
1321
+ };
1322
+ return rb_ensure(generate_json_try, (VALUE)&data, generate_json_ensure, (VALUE)&data);
1323
+ }
1324
+
1325
+ /* call-seq:
1326
+ * generate(obj) -> String
1327
+ * generate(obj, anIO) -> anIO
1328
+ *
1329
+ * Generates a valid JSON document from object +obj+ and returns the
1330
+ * result. If no valid JSON document can be created this method raises a
1331
+ * GeneratorError exception.
1332
+ */
1333
+ static VALUE cState_generate(int argc, VALUE *argv, VALUE self)
1334
+ {
1335
+ rb_check_arity(argc, 1, 2);
1336
+ VALUE obj = argv[0];
1337
+ VALUE io = argc > 1 ? argv[1] : Qnil;
1338
+ return cState_partial_generate(self, obj, generate_json, io);
1339
+ }
1340
+
1341
+ /* :nodoc: */
1342
+ static VALUE cState_generate_no_fallback(int argc, VALUE *argv, VALUE self)
1343
+ {
1344
+ rb_check_arity(argc, 1, 2);
1345
+ VALUE obj = argv[0];
1346
+ VALUE io = argc > 1 ? argv[1] : Qnil;
1347
+ return cState_partial_generate(self, obj, generate_json_no_fallback, io);
1348
+ }
1349
+
1350
+ static VALUE cState_initialize(int argc, VALUE *argv, VALUE self)
1351
+ {
1352
+ rb_warn("The json gem extension was loaded with the stdlib ruby code. You should upgrade rubygems with `gem update --system`");
1353
+ return self;
1354
+ }
1355
+
1356
+ /*
1357
+ * call-seq: initialize_copy(orig)
1358
+ *
1359
+ * Initializes this object from orig if it can be duplicated/cloned and returns
1360
+ * it.
1361
+ */
1362
+ static VALUE cState_init_copy(VALUE obj, VALUE orig)
1363
+ {
1364
+ JSON_Generator_State *objState, *origState;
1365
+
1366
+ if (obj == orig) return obj;
1367
+ GET_STATE_TO(obj, objState);
1368
+ GET_STATE_TO(orig, origState);
1369
+ if (!objState) rb_raise(rb_eArgError, "unallocated JSON::State");
1370
+
1371
+ MEMCPY(objState, origState, JSON_Generator_State, 1);
1372
+
1373
+ RB_OBJ_WRITTEN(obj, Qundef, objState->indent);
1374
+ RB_OBJ_WRITTEN(obj, Qundef, objState->space);
1375
+ RB_OBJ_WRITTEN(obj, Qundef, objState->space_before);
1376
+ RB_OBJ_WRITTEN(obj, Qundef, objState->object_nl);
1377
+ RB_OBJ_WRITTEN(obj, Qundef, objState->array_nl);
1378
+ RB_OBJ_WRITTEN(obj, Qundef, objState->as_json);
1379
+
1380
+ return obj;
1381
+ }
1382
+
1383
+ /*
1384
+ * call-seq: from_state(opts)
1385
+ *
1386
+ * Creates a State object from _opts_, which ought to be Hash to create a
1387
+ * new State instance configured by _opts_, something else to create an
1388
+ * unconfigured instance. If _opts_ is a State object, it is just returned.
1389
+ */
1390
+ static VALUE cState_from_state_s(VALUE self, VALUE opts)
1391
+ {
1392
+ if (rb_obj_is_kind_of(opts, self)) {
1393
+ return opts;
1394
+ } else if (rb_obj_is_kind_of(opts, rb_cHash)) {
1395
+ return rb_funcall(self, i_new, 1, opts);
1396
+ } else {
1397
+ return rb_class_new_instance(0, NULL, cState);
1398
+ }
1399
+ }
1400
+
1401
+ /*
1402
+ * call-seq: indent()
1403
+ *
1404
+ * Returns the string that is used to indent levels in the JSON text.
1405
+ */
1406
+ static VALUE cState_indent(VALUE self)
1407
+ {
1408
+ GET_STATE(self);
1409
+ return state->indent ? state->indent : rb_str_freeze(rb_utf8_str_new("", 0));
1410
+ }
1411
+
1412
+ static VALUE string_config(VALUE config)
1413
+ {
1414
+ if (RTEST(config)) {
1415
+ Check_Type(config, T_STRING);
1416
+ if (RSTRING_LEN(config)) {
1417
+ return rb_str_new_frozen(config);
1418
+ }
1419
+ }
1420
+ return Qfalse;
1421
+ }
1422
+
1423
+ /*
1424
+ * call-seq: indent=(indent)
1425
+ *
1426
+ * Sets the string that is used to indent levels in the JSON text.
1427
+ */
1428
+ static VALUE cState_indent_set(VALUE self, VALUE indent)
1429
+ {
1430
+ rb_check_frozen(self);
1431
+ GET_STATE(self);
1432
+ RB_OBJ_WRITE(self, &state->indent, string_config(indent));
1433
+ return Qnil;
1434
+ }
1435
+
1436
+ /*
1437
+ * call-seq: space()
1438
+ *
1439
+ * Returns the string that is used to insert a space between the tokens in a JSON
1440
+ * string.
1441
+ */
1442
+ static VALUE cState_space(VALUE self)
1443
+ {
1444
+ GET_STATE(self);
1445
+ return state->space ? state->space : rb_str_freeze(rb_utf8_str_new("", 0));
1446
+ }
1447
+
1448
+ /*
1449
+ * call-seq: space=(space)
1450
+ *
1451
+ * Sets _space_ to the string that is used to insert a space between the tokens in a JSON
1452
+ * string.
1453
+ */
1454
+ static VALUE cState_space_set(VALUE self, VALUE space)
1455
+ {
1456
+ rb_check_frozen(self);
1457
+ GET_STATE(self);
1458
+ RB_OBJ_WRITE(self, &state->space, string_config(space));
1459
+ return Qnil;
1460
+ }
1461
+
1462
+ /*
1463
+ * call-seq: space_before()
1464
+ *
1465
+ * Returns the string that is used to insert a space before the ':' in JSON objects.
1466
+ */
1467
+ static VALUE cState_space_before(VALUE self)
1468
+ {
1469
+ GET_STATE(self);
1470
+ return state->space_before ? state->space_before : rb_str_freeze(rb_utf8_str_new("", 0));
1471
+ }
1472
+
1473
+ /*
1474
+ * call-seq: space_before=(space_before)
1475
+ *
1476
+ * Sets the string that is used to insert a space before the ':' in JSON objects.
1477
+ */
1478
+ static VALUE cState_space_before_set(VALUE self, VALUE space_before)
1479
+ {
1480
+ rb_check_frozen(self);
1481
+ GET_STATE(self);
1482
+ RB_OBJ_WRITE(self, &state->space_before, string_config(space_before));
1483
+ return Qnil;
1484
+ }
1485
+
1486
+ /*
1487
+ * call-seq: object_nl()
1488
+ *
1489
+ * This string is put at the end of a line that holds a JSON object (or
1490
+ * Hash).
1491
+ */
1492
+ static VALUE cState_object_nl(VALUE self)
1493
+ {
1494
+ GET_STATE(self);
1495
+ return state->object_nl ? state->object_nl : rb_str_freeze(rb_utf8_str_new("", 0));
1496
+ }
1497
+
1498
+ /*
1499
+ * call-seq: object_nl=(object_nl)
1500
+ *
1501
+ * This string is put at the end of a line that holds a JSON object (or
1502
+ * Hash).
1503
+ */
1504
+ static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)
1505
+ {
1506
+ rb_check_frozen(self);
1507
+ GET_STATE(self);
1508
+ RB_OBJ_WRITE(self, &state->object_nl, string_config(object_nl));
1509
+ return Qnil;
1510
+ }
1511
+
1512
+ /*
1513
+ * call-seq: array_nl()
1514
+ *
1515
+ * This string is put at the end of a line that holds a JSON array.
1516
+ */
1517
+ static VALUE cState_array_nl(VALUE self)
1518
+ {
1519
+ GET_STATE(self);
1520
+ return state->array_nl ? state->array_nl : rb_str_freeze(rb_utf8_str_new("", 0));
1521
+ }
1522
+
1523
+ /*
1524
+ * call-seq: array_nl=(array_nl)
1525
+ *
1526
+ * This string is put at the end of a line that holds a JSON array.
1527
+ */
1528
+ static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)
1529
+ {
1530
+ rb_check_frozen(self);
1531
+ GET_STATE(self);
1532
+ RB_OBJ_WRITE(self, &state->array_nl, string_config(array_nl));
1533
+ return Qnil;
1534
+ }
1535
+
1536
+ /*
1537
+ * call-seq: as_json()
1538
+ *
1539
+ * This string is put at the end of a line that holds a JSON array.
1540
+ */
1541
+ static VALUE cState_as_json(VALUE self)
1542
+ {
1543
+ GET_STATE(self);
1544
+ return state->as_json;
1545
+ }
1546
+
1547
+ /*
1548
+ * call-seq: as_json=(as_json)
1549
+ *
1550
+ * This string is put at the end of a line that holds a JSON array.
1551
+ */
1552
+ static VALUE cState_as_json_set(VALUE self, VALUE as_json)
1553
+ {
1554
+ rb_check_frozen(self);
1555
+ GET_STATE(self);
1556
+ RB_OBJ_WRITE(self, &state->as_json, rb_convert_type(as_json, T_DATA, "Proc", "to_proc"));
1557
+ return Qnil;
1558
+ }
1559
+
1560
+ /*
1561
+ * call-seq: check_circular?
1562
+ *
1563
+ * Returns true, if circular data structures should be checked,
1564
+ * otherwise returns false.
1565
+ */
1566
+ static VALUE cState_check_circular_p(VALUE self)
1567
+ {
1568
+ GET_STATE(self);
1569
+ return state->max_nesting ? Qtrue : Qfalse;
1570
+ }
1571
+
1572
+ /*
1573
+ * call-seq: max_nesting
1574
+ *
1575
+ * This integer returns the maximum level of data structure nesting in
1576
+ * the generated JSON, max_nesting = 0 if no maximum is checked.
1577
+ */
1578
+ static VALUE cState_max_nesting(VALUE self)
1579
+ {
1580
+ GET_STATE(self);
1581
+ return LONG2FIX(state->max_nesting);
1582
+ }
1583
+
1584
+ static long long_config(VALUE num)
1585
+ {
1586
+ return RTEST(num) ? NUM2LONG(num) : 0;
1587
+ }
1588
+
1589
+ // depth must never be negative; reject early with a clear error.
1590
+ static long depth_config(VALUE num)
1591
+ {
1592
+ if (!RTEST(num)) return 0;
1593
+ long d = NUM2LONG(num);
1594
+ if (RB_UNLIKELY(d < 0)) {
1595
+ rb_raise(rb_eArgError, "depth must be >= 0 (got %ld)", d);
1596
+ }
1597
+ if (RB_UNLIKELY(d > INT_MAX)) {
1598
+ rb_raise(rb_eArgError, "depth is too large (got %ld)", d);
1599
+ }
1600
+ return d;
1601
+ }
1602
+
1603
+ /*
1604
+ * call-seq: max_nesting=(depth)
1605
+ *
1606
+ * This sets the maximum level of data structure nesting in the generated JSON
1607
+ * to the integer depth, max_nesting = 0 if no maximum should be checked.
1608
+ */
1609
+ static VALUE cState_max_nesting_set(VALUE self, VALUE depth)
1610
+ {
1611
+ rb_check_frozen(self);
1612
+ GET_STATE(self);
1613
+ state->max_nesting = long_config(depth);
1614
+ return Qnil;
1615
+ }
1616
+
1617
+ /*
1618
+ * call-seq: script_safe
1619
+ *
1620
+ * If this boolean is true, the forward slashes will be escaped in
1621
+ * the json output.
1622
+ */
1623
+ static VALUE cState_script_safe(VALUE self)
1624
+ {
1625
+ GET_STATE(self);
1626
+ return state->script_safe ? Qtrue : Qfalse;
1627
+ }
1628
+
1629
+ /*
1630
+ * call-seq: script_safe=(enable)
1631
+ *
1632
+ * This sets whether or not the forward slashes will be escaped in
1633
+ * the json output.
1634
+ */
1635
+ static VALUE cState_script_safe_set(VALUE self, VALUE enable)
1636
+ {
1637
+ rb_check_frozen(self);
1638
+ GET_STATE(self);
1639
+ state->script_safe = RTEST(enable);
1640
+ return Qnil;
1641
+ }
1642
+
1643
+ /*
1644
+ * call-seq: strict
1645
+ *
1646
+ * If this boolean is false, types unsupported by the JSON format will
1647
+ * be serialized as strings.
1648
+ * If this boolean is true, types unsupported by the JSON format will
1649
+ * raise a JSON::GeneratorError.
1650
+ */
1651
+ static VALUE cState_strict(VALUE self)
1652
+ {
1653
+ GET_STATE(self);
1654
+ return state->strict ? Qtrue : Qfalse;
1655
+ }
1656
+
1657
+ /*
1658
+ * call-seq: strict=(enable)
1659
+ *
1660
+ * This sets whether or not to serialize types unsupported by the
1661
+ * JSON format as strings.
1662
+ * If this boolean is false, types unsupported by the JSON format will
1663
+ * be serialized as strings.
1664
+ * If this boolean is true, types unsupported by the JSON format will
1665
+ * raise a JSON::GeneratorError.
1666
+ */
1667
+ static VALUE cState_strict_set(VALUE self, VALUE enable)
1668
+ {
1669
+ rb_check_frozen(self);
1670
+ GET_STATE(self);
1671
+ state->strict = RTEST(enable);
1672
+ return Qnil;
1673
+ }
1674
+
1675
+ /*
1676
+ * call-seq: allow_nan?
1677
+ *
1678
+ * Returns true, if NaN, Infinity, and -Infinity should be generated, otherwise
1679
+ * returns false.
1680
+ */
1681
+ static VALUE cState_allow_nan_p(VALUE self)
1682
+ {
1683
+ GET_STATE(self);
1684
+ return state->allow_nan ? Qtrue : Qfalse;
1685
+ }
1686
+
1687
+ /*
1688
+ * call-seq: allow_nan=(enable)
1689
+ *
1690
+ * This sets whether or not to serialize NaN, Infinity, and -Infinity
1691
+ */
1692
+ static VALUE cState_allow_nan_set(VALUE self, VALUE enable)
1693
+ {
1694
+ rb_check_frozen(self);
1695
+ GET_STATE(self);
1696
+ state->allow_nan = RTEST(enable);
1697
+ return Qnil;
1698
+ }
1699
+
1700
+ /*
1701
+ * call-seq: ascii_only?
1702
+ *
1703
+ * Returns true, if only ASCII characters should be generated. Otherwise
1704
+ * returns false.
1705
+ */
1706
+ static VALUE cState_ascii_only_p(VALUE self)
1707
+ {
1708
+ GET_STATE(self);
1709
+ return state->ascii_only ? Qtrue : Qfalse;
1710
+ }
1711
+
1712
+ /*
1713
+ * call-seq: ascii_only=(enable)
1714
+ *
1715
+ * This sets whether only ASCII characters should be generated.
1716
+ */
1717
+ static VALUE cState_ascii_only_set(VALUE self, VALUE enable)
1718
+ {
1719
+ rb_check_frozen(self);
1720
+ GET_STATE(self);
1721
+ state->ascii_only = RTEST(enable);
1722
+ return Qnil;
1723
+ }
1724
+
1725
+ static VALUE cState_allow_duplicate_key_p(VALUE self)
1726
+ {
1727
+ GET_STATE(self);
1728
+ switch (state->on_duplicate_key) {
1729
+ case JSON_IGNORE:
1730
+ return Qtrue;
1731
+ case JSON_DEPRECATED:
1732
+ return Qnil;
1733
+ default:
1734
+ return Qfalse;
1735
+ }
1736
+ }
1737
+
1738
+ /*
1739
+ * call-seq: depth
1740
+ *
1741
+ * This integer returns the current depth of data structure nesting.
1742
+ */
1743
+ static VALUE cState_depth(VALUE self)
1744
+ {
1745
+ GET_STATE(self);
1746
+ return LONG2FIX(state->depth);
1747
+ }
1748
+
1749
+ /*
1750
+ * call-seq: depth=(depth)
1751
+ *
1752
+ * This sets the maximum level of data structure nesting in the generated JSON
1753
+ * to the integer depth, max_nesting = 0 if no maximum should be checked.
1754
+ */
1755
+ static VALUE cState_depth_set(VALUE self, VALUE depth)
1756
+ {
1757
+ rb_check_frozen(self);
1758
+ GET_STATE(self);
1759
+ state->depth = depth_config(depth);
1760
+ return Qnil;
1761
+ }
1762
+
1763
+ /*
1764
+ * call-seq: buffer_initial_length
1765
+ *
1766
+ * This integer returns the current initial length of the buffer.
1767
+ */
1768
+ static VALUE cState_buffer_initial_length(VALUE self)
1769
+ {
1770
+ GET_STATE(self);
1771
+ return LONG2FIX(state->buffer_initial_length);
1772
+ }
1773
+
1774
+ static void buffer_initial_length_set(JSON_Generator_State *state, VALUE buffer_initial_length)
1775
+ {
1776
+ Check_Type(buffer_initial_length, T_FIXNUM);
1777
+ long initial_length = FIX2LONG(buffer_initial_length);
1778
+ if (initial_length > 0) {
1779
+ state->buffer_initial_length = initial_length;
1780
+ }
1781
+ }
1782
+
1783
+ /*
1784
+ * call-seq: buffer_initial_length=(length)
1785
+ *
1786
+ * This sets the initial length of the buffer to +length+, if +length+ > 0,
1787
+ * otherwise its value isn't changed.
1788
+ */
1789
+ static VALUE cState_buffer_initial_length_set(VALUE self, VALUE buffer_initial_length)
1790
+ {
1791
+ rb_check_frozen(self);
1792
+ GET_STATE(self);
1793
+ buffer_initial_length_set(state, buffer_initial_length);
1794
+ return Qnil;
1795
+ }
1796
+
1797
+ struct configure_state_data {
1798
+ JSON_Generator_State *state;
1799
+ VALUE vstate; // Ruby object that owns the state, or Qfalse if stack-allocated
1800
+ };
1801
+
1802
+ static inline void state_write_value(struct configure_state_data *data, VALUE *field, VALUE value)
1803
+ {
1804
+ if (RTEST(data->vstate)) {
1805
+ RB_OBJ_WRITE(data->vstate, field, value);
1806
+ } else {
1807
+ *field = value;
1808
+ }
1809
+ }
1810
+
1811
+ static int configure_state_i(VALUE key, VALUE val, VALUE _arg)
1812
+ {
1813
+ struct configure_state_data *data = (struct configure_state_data *)_arg;
1814
+ JSON_Generator_State *state = data->state;
1815
+
1816
+ if (key == sym_indent) { state_write_value(data, &state->indent, string_config(val)); }
1817
+ else if (key == sym_space) { state_write_value(data, &state->space, string_config(val)); }
1818
+ else if (key == sym_space_before) { state_write_value(data, &state->space_before, string_config(val)); }
1819
+ else if (key == sym_object_nl) { state_write_value(data, &state->object_nl, string_config(val)); }
1820
+ else if (key == sym_array_nl) { state_write_value(data, &state->array_nl, string_config(val)); }
1821
+ else if (key == sym_max_nesting) { state->max_nesting = long_config(val); }
1822
+ else if (key == sym_allow_nan) { state->allow_nan = RTEST(val); }
1823
+ else if (key == sym_ascii_only) { state->ascii_only = RTEST(val); }
1824
+ else if (key == sym_depth) { state->depth = depth_config(val); }
1825
+ else if (key == sym_buffer_initial_length) { buffer_initial_length_set(state, val); }
1826
+ else if (key == sym_script_safe) { state->script_safe = RTEST(val); }
1827
+ else if (key == sym_escape_slash) { state->script_safe = RTEST(val); }
1828
+ else if (key == sym_strict) { state->strict = RTEST(val); }
1829
+ else if (key == sym_allow_duplicate_key) { state->on_duplicate_key = RTEST(val) ? JSON_IGNORE : JSON_RAISE; }
1830
+ else if (key == sym_as_json) {
1831
+ VALUE proc = RTEST(val) ? rb_convert_type(val, T_DATA, "Proc", "to_proc") : Qfalse;
1832
+ state->as_json_single_arg = proc && rb_proc_arity(proc) == 1;
1833
+ state_write_value(data, &state->as_json, proc);
1834
+ }
1835
+ return ST_CONTINUE;
1836
+ }
1837
+
1838
+ static void configure_state(JSON_Generator_State *state, VALUE vstate, VALUE config)
1839
+ {
1840
+ if (!RTEST(config)) return;
1841
+
1842
+ Check_Type(config, T_HASH);
1843
+
1844
+ if (!RHASH_SIZE(config)) return;
1845
+
1846
+ struct configure_state_data data = {
1847
+ .state = state,
1848
+ .vstate = vstate
1849
+ };
1850
+
1851
+ // We assume in most cases few keys are set so it's faster to go over
1852
+ // the provided keys than to check all possible keys.
1853
+ rb_hash_foreach(config, configure_state_i, (VALUE)&data);
1854
+ }
1855
+
1856
+ static VALUE cState_configure(VALUE self, VALUE opts)
1857
+ {
1858
+ rb_check_frozen(self);
1859
+ GET_STATE(self);
1860
+ configure_state(state, self, opts);
1861
+ return self;
1862
+ }
1863
+
1864
+ static VALUE cState_m_do_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io, generator_func func)
1865
+ {
1866
+ JSON_Generator_State state = {0};
1867
+ state_init(&state);
1868
+ configure_state(&state, Qfalse, opts);
1869
+
1870
+ char stack_buffer[FBUFFER_STACK_SIZE];
1871
+ FBuffer buffer = { 0 };
1872
+ fbuffer_init(&buffer, state.buffer_initial_length, io, stack_buffer, FBUFFER_STACK_SIZE);
1873
+
1874
+ struct generate_json_data data = {
1875
+ .buffer = &buffer,
1876
+ .vstate = Qfalse,
1877
+ .state = &state,
1878
+ .depth = state.depth,
1879
+ .obj = obj,
1880
+ .func = func,
1881
+ };
1882
+ return rb_ensure(generate_json_try, (VALUE)&data, generate_json_ensure, (VALUE)&data);
1883
+ }
1884
+
1885
+ static VALUE cState_m_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1886
+ {
1887
+ return cState_m_do_generate(klass, obj, opts, io, generate_json);
1888
+ }
1889
+
1890
+ static VALUE cState_m_generate_no_fallback(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1891
+ {
1892
+ return cState_m_do_generate(klass, obj, opts, io, generate_json_no_fallback);
1893
+ }
1894
+
1895
+ void Init_generator(void)
1896
+ {
1897
+ #ifdef HAVE_RB_EXT_RACTOR_SAFE
1898
+ rb_ext_ractor_safe(true);
1899
+ #endif
1900
+
1901
+ #undef rb_intern
1902
+ rb_require("json/common");
1903
+
1904
+ mJSON = rb_define_module("JSON");
1905
+
1906
+ rb_global_variable(&cFragment);
1907
+ cFragment = rb_const_get(mJSON, rb_intern("Fragment"));
1908
+
1909
+ VALUE mExt = rb_define_module_under(mJSON, "Ext");
1910
+ VALUE mGenerator = rb_define_module_under(mExt, "Generator");
1911
+
1912
+ rb_global_variable(&eGeneratorError);
1913
+ eGeneratorError = rb_path2class("JSON::GeneratorError");
1914
+
1915
+ rb_global_variable(&eNestingError);
1916
+ eNestingError = rb_path2class("JSON::NestingError");
1917
+
1918
+ cState = rb_define_class_under(mGenerator, "State", rb_cObject);
1919
+ rb_define_alloc_func(cState, cState_s_allocate);
1920
+ rb_define_singleton_method(cState, "from_state", cState_from_state_s, 1);
1921
+ rb_define_method(cState, "initialize", cState_initialize, -1);
1922
+ rb_define_alias(cState, "initialize", "initialize"); // avoid method redefinition warnings
1923
+ rb_define_private_method(cState, "_configure", cState_configure, 1);
1924
+
1925
+ rb_define_method(cState, "initialize_copy", cState_init_copy, 1);
1926
+ rb_define_method(cState, "indent", cState_indent, 0);
1927
+ rb_define_method(cState, "indent=", cState_indent_set, 1);
1928
+ rb_define_method(cState, "space", cState_space, 0);
1929
+ rb_define_method(cState, "space=", cState_space_set, 1);
1930
+ rb_define_method(cState, "space_before", cState_space_before, 0);
1931
+ rb_define_method(cState, "space_before=", cState_space_before_set, 1);
1932
+ rb_define_method(cState, "object_nl", cState_object_nl, 0);
1933
+ rb_define_method(cState, "object_nl=", cState_object_nl_set, 1);
1934
+ rb_define_method(cState, "array_nl", cState_array_nl, 0);
1935
+ rb_define_method(cState, "array_nl=", cState_array_nl_set, 1);
1936
+ rb_define_method(cState, "as_json", cState_as_json, 0);
1937
+ rb_define_method(cState, "as_json=", cState_as_json_set, 1);
1938
+ rb_define_method(cState, "max_nesting", cState_max_nesting, 0);
1939
+ rb_define_method(cState, "max_nesting=", cState_max_nesting_set, 1);
1940
+ rb_define_method(cState, "script_safe", cState_script_safe, 0);
1941
+ rb_define_method(cState, "script_safe?", cState_script_safe, 0);
1942
+ rb_define_method(cState, "script_safe=", cState_script_safe_set, 1);
1943
+ rb_define_alias(cState, "escape_slash", "script_safe");
1944
+ rb_define_alias(cState, "escape_slash?", "script_safe?");
1945
+ rb_define_alias(cState, "escape_slash=", "script_safe=");
1946
+ rb_define_method(cState, "strict", cState_strict, 0);
1947
+ rb_define_method(cState, "strict?", cState_strict, 0);
1948
+ rb_define_method(cState, "strict=", cState_strict_set, 1);
1949
+ rb_define_method(cState, "check_circular?", cState_check_circular_p, 0);
1950
+ rb_define_method(cState, "allow_nan?", cState_allow_nan_p, 0);
1951
+ rb_define_method(cState, "allow_nan=", cState_allow_nan_set, 1);
1952
+ rb_define_method(cState, "ascii_only?", cState_ascii_only_p, 0);
1953
+ rb_define_method(cState, "ascii_only=", cState_ascii_only_set, 1);
1954
+ rb_define_method(cState, "depth", cState_depth, 0);
1955
+ rb_define_method(cState, "depth=", cState_depth_set, 1);
1956
+ rb_define_method(cState, "buffer_initial_length", cState_buffer_initial_length, 0);
1957
+ rb_define_method(cState, "buffer_initial_length=", cState_buffer_initial_length_set, 1);
1958
+ rb_define_method(cState, "generate", cState_generate, -1);
1959
+ rb_define_method(cState, "_generate_no_fallback", cState_generate_no_fallback, -1);
1960
+
1961
+ rb_define_private_method(cState, "allow_duplicate_key?", cState_allow_duplicate_key_p, 0);
1962
+
1963
+ rb_define_singleton_method(cState, "generate", cState_m_generate, 3);
1964
+ rb_define_singleton_method(cState, "_generate_no_fallback", cState_m_generate_no_fallback, 3);
1965
+
1966
+ rb_global_variable(&Encoding_UTF_8);
1967
+ Encoding_UTF_8 = rb_const_get(rb_path2class("Encoding"), rb_intern("UTF_8"));
1968
+
1969
+ i_to_s = rb_intern("to_s");
1970
+ i_to_json = rb_intern("to_json");
1971
+ i_new = rb_intern("new");
1972
+ i_encode = rb_intern("encode");
1973
+
1974
+ sym_indent = ID2SYM(rb_intern("indent"));
1975
+ sym_space = ID2SYM(rb_intern("space"));
1976
+ sym_space_before = ID2SYM(rb_intern("space_before"));
1977
+ sym_object_nl = ID2SYM(rb_intern("object_nl"));
1978
+ sym_array_nl = ID2SYM(rb_intern("array_nl"));
1979
+ sym_max_nesting = ID2SYM(rb_intern("max_nesting"));
1980
+ sym_allow_nan = ID2SYM(rb_intern("allow_nan"));
1981
+ sym_ascii_only = ID2SYM(rb_intern("ascii_only"));
1982
+ sym_depth = ID2SYM(rb_intern("depth"));
1983
+ sym_buffer_initial_length = ID2SYM(rb_intern("buffer_initial_length"));
1984
+ sym_script_safe = ID2SYM(rb_intern("script_safe"));
1985
+ sym_escape_slash = ID2SYM(rb_intern("escape_slash"));
1986
+ sym_strict = ID2SYM(rb_intern("strict"));
1987
+ sym_as_json = ID2SYM(rb_intern("as_json"));
1988
+ sym_allow_duplicate_key = ID2SYM(rb_intern("allow_duplicate_key"));
1989
+
1990
+ usascii_encindex = rb_usascii_encindex();
1991
+ utf8_encindex = rb_utf8_encindex();
1992
+ binary_encindex = rb_ascii8bit_encindex();
1993
+
1994
+ rb_require("json/ext/generator/state");
1995
+
1996
+ simd_impl = find_simd_implementation();
1997
+ }