json 2.10.2 → 2.19.9

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.
@@ -1,11 +1,20 @@
1
- #include "ruby.h"
1
+ #include "../json.h"
2
2
  #include "../fbuffer/fbuffer.h"
3
+ #include "../vendor/fpconv.c"
3
4
 
4
5
  #include <math.h>
5
6
  #include <ctype.h>
6
7
 
8
+ #include "../simd/simd.h"
9
+
7
10
  /* ruby api and some helpers */
8
11
 
12
+ enum duplicate_key_action {
13
+ JSON_DEPRECATED = 0,
14
+ JSON_IGNORE,
15
+ JSON_RAISE,
16
+ };
17
+
9
18
  typedef struct JSON_Generator_StateStruct {
10
19
  VALUE indent;
11
20
  VALUE space;
@@ -18,20 +27,19 @@ typedef struct JSON_Generator_StateStruct {
18
27
  long depth;
19
28
  long buffer_initial_length;
20
29
 
30
+ enum duplicate_key_action on_duplicate_key;
31
+
32
+ bool as_json_single_arg;
21
33
  bool allow_nan;
22
34
  bool ascii_only;
23
35
  bool script_safe;
24
36
  bool strict;
25
37
  } JSON_Generator_State;
26
38
 
27
- #ifndef RB_UNLIKELY
28
- #define RB_UNLIKELY(cond) (cond)
29
- #endif
30
-
31
- static VALUE mJSON, cState, cFragment, mString_Extend, eGeneratorError, eNestingError, Encoding_UTF_8;
39
+ static VALUE mJSON, cState, cFragment, eGeneratorError, eNestingError, Encoding_UTF_8;
32
40
 
33
- static ID i_to_s, i_to_json, i_new, i_pack, i_unpack, i_create_id, i_extend, i_encode;
34
- static VALUE sym_indent, sym_space, sym_space_before, sym_object_nl, sym_array_nl, sym_max_nesting, sym_allow_nan,
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,
35
43
  sym_ascii_only, sym_depth, sym_buffer_initial_length, sym_script_safe, sym_escape_slash, sym_strict, sym_as_json;
36
44
 
37
45
 
@@ -44,7 +52,7 @@ static VALUE sym_indent, sym_space, sym_space_before, sym_object_nl, sym_array_n
44
52
 
45
53
  struct generate_json_data;
46
54
 
47
- typedef void (*generator_func)(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
55
+ typedef void (*generator_func)(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
48
56
 
49
57
  struct generate_json_data {
50
58
  FBuffer *buffer;
@@ -52,44 +60,39 @@ struct generate_json_data {
52
60
  JSON_Generator_State *state;
53
61
  VALUE obj;
54
62
  generator_func func;
63
+ long depth;
55
64
  };
56
65
 
66
+ static SIMD_Implementation simd_impl;
67
+
57
68
  static VALUE cState_from_state_s(VALUE self, VALUE opts);
58
69
  static VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func, VALUE io);
59
- static void generate_json(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
60
- static void generate_json_object(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
61
- static void generate_json_array(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
62
- static void generate_json_string(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
63
- static void generate_json_null(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
64
- static void generate_json_false(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
65
- static void generate_json_true(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
66
- #ifdef RUBY_INTEGER_UNIFICATION
67
- static void generate_json_integer(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
68
- #endif
69
- static void generate_json_fixnum(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
70
- static void generate_json_bignum(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
71
- static void generate_json_float(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
72
- static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj);
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);
73
81
 
74
82
  static int usascii_encindex, utf8_encindex, binary_encindex;
75
83
 
76
- #ifdef RBIMPL_ATTR_NORETURN
77
- RBIMPL_ATTR_NORETURN()
78
- #endif
79
- static void raise_generator_error_str(VALUE invalid_object, VALUE str)
84
+ NORETURN(static void) raise_generator_error_str(VALUE invalid_object, VALUE str)
80
85
  {
86
+ rb_enc_associate_index(str, utf8_encindex);
81
87
  VALUE exc = rb_exc_new_str(eGeneratorError, str);
82
88
  rb_ivar_set(exc, rb_intern("@invalid_object"), invalid_object);
83
89
  rb_exc_raise(exc);
84
90
  }
85
91
 
86
- #ifdef RBIMPL_ATTR_NORETURN
87
- RBIMPL_ATTR_NORETURN()
88
- #endif
89
92
  #ifdef RBIMPL_ATTR_FORMAT
90
93
  RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 3)
91
94
  #endif
92
- static void raise_generator_error(VALUE invalid_object, const char *fmt, ...)
95
+ NORETURN(static void) raise_generator_error(VALUE invalid_object, const char *fmt, ...)
93
96
  {
94
97
  va_list args;
95
98
  va_start(args, fmt);
@@ -108,12 +111,34 @@ typedef struct _search_state {
108
111
  const char *end;
109
112
  const char *cursor;
110
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 */
111
128
  } search_state;
112
129
 
113
- static inline void search_flush(search_state *search)
114
- {
115
- fbuffer_append(search->buffer, search->cursor, search->ptr - search->cursor);
116
- search->cursor = search->ptr;
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
+ }
117
142
  }
118
143
 
119
144
  static const unsigned char escape_table_basic[256] = {
@@ -143,7 +168,8 @@ static inline unsigned char search_escape_basic(search_state *search)
143
168
  return 0;
144
169
  }
145
170
 
146
- static inline void escape_UTF8_char_basic(search_state *search) {
171
+ ALWAYS_INLINE(static) void escape_UTF8_char_basic(search_state *search)
172
+ {
147
173
  const unsigned char ch = (unsigned char)*search->ptr;
148
174
  switch (ch) {
149
175
  case '"': fbuffer_append(search->buffer, "\\\"", 2); break;
@@ -183,14 +209,43 @@ static inline void escape_UTF8_char_basic(search_state *search) {
183
209
  * Everything else (should be UTF-8) is just passed through and
184
210
  * appended to the result.
185
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
+
186
222
  static inline void convert_UTF8_to_JSON(search_state *search)
187
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
+ }
188
236
  while (search_escape_basic(search)) {
189
237
  escape_UTF8_char_basic(search);
190
238
  }
239
+ #endif
240
+ #else
241
+ while (search_escape_basic(search)) {
242
+ escape_UTF8_char_basic(search);
243
+ }
244
+ #endif /* HAVE_SIMD */
191
245
  }
192
246
 
193
- static inline void escape_UTF8_char(search_state *search, unsigned char ch_len) {
247
+ static inline void escape_UTF8_char(search_state *search, unsigned char ch_len)
248
+ {
194
249
  const unsigned char ch = (unsigned char)*search->ptr;
195
250
  switch (ch_len) {
196
251
  case 1: {
@@ -226,6 +281,236 @@ static inline void escape_UTF8_char(search_state *search, unsigned char ch_len)
226
281
  search->cursor = (search->ptr += ch_len);
227
282
  }
228
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
+
229
514
  static const unsigned char script_safe_escape_table[256] = {
230
515
  // ASCII Control Characters
231
516
  9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
@@ -329,7 +614,8 @@ static inline unsigned char search_ascii_only_escape(search_state *search, const
329
614
  return 0;
330
615
  }
331
616
 
332
- static inline void full_escape_UTF8_char(search_state *search, unsigned char ch_len) {
617
+ static inline void full_escape_UTF8_char(search_state *search, unsigned char ch_len)
618
+ {
333
619
  const unsigned char ch = (unsigned char)*search->ptr;
334
620
  switch (ch_len) {
335
621
  case 1: {
@@ -359,7 +645,7 @@ static inline void full_escape_UTF8_char(search_state *search, unsigned char ch_
359
645
 
360
646
  uint32_t wchar = 0;
361
647
 
362
- switch(ch_len) {
648
+ switch (ch_len) {
363
649
  case 2:
364
650
  wchar = ch & 0x1F;
365
651
  break;
@@ -414,288 +700,6 @@ static void convert_UTF8_to_ASCII_only_JSON(search_state *search, const unsigned
414
700
  }
415
701
  }
416
702
 
417
- /*
418
- * Document-module: JSON::Ext::Generator
419
- *
420
- * This is the JSON generator implemented as a C extension. It can be
421
- * configured to be used by setting
422
- *
423
- * JSON.generator = JSON::Ext::Generator
424
- *
425
- * with the method generator= in JSON.
426
- *
427
- */
428
-
429
- /* Explanation of the following: that's the only way to not pollute
430
- * standard library's docs with GeneratorMethods::<ClassName> which
431
- * are uninformative and take a large place in a list of classes
432
- */
433
-
434
- /*
435
- * Document-module: JSON::Ext::Generator::GeneratorMethods
436
- * :nodoc:
437
- */
438
-
439
- /*
440
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Array
441
- * :nodoc:
442
- */
443
-
444
- /*
445
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Bignum
446
- * :nodoc:
447
- */
448
-
449
- /*
450
- * Document-module: JSON::Ext::Generator::GeneratorMethods::FalseClass
451
- * :nodoc:
452
- */
453
-
454
- /*
455
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Fixnum
456
- * :nodoc:
457
- */
458
-
459
- /*
460
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Float
461
- * :nodoc:
462
- */
463
-
464
- /*
465
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Hash
466
- * :nodoc:
467
- */
468
-
469
- /*
470
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Integer
471
- * :nodoc:
472
- */
473
-
474
- /*
475
- * Document-module: JSON::Ext::Generator::GeneratorMethods::NilClass
476
- * :nodoc:
477
- */
478
-
479
- /*
480
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Object
481
- * :nodoc:
482
- */
483
-
484
- /*
485
- * Document-module: JSON::Ext::Generator::GeneratorMethods::String
486
- * :nodoc:
487
- */
488
-
489
- /*
490
- * Document-module: JSON::Ext::Generator::GeneratorMethods::String::Extend
491
- * :nodoc:
492
- */
493
-
494
- /*
495
- * Document-module: JSON::Ext::Generator::GeneratorMethods::TrueClass
496
- * :nodoc:
497
- */
498
-
499
- /*
500
- * call-seq: to_json(state = nil)
501
- *
502
- * Returns a JSON string containing a JSON object, that is generated from
503
- * this Hash instance.
504
- * _state_ is a JSON::State object, that can also be used to configure the
505
- * produced JSON string output further.
506
- */
507
- static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self)
508
- {
509
- rb_check_arity(argc, 0, 1);
510
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
511
- return cState_partial_generate(Vstate, self, generate_json_object, Qfalse);
512
- }
513
-
514
- /*
515
- * call-seq: to_json(state = nil)
516
- *
517
- * Returns a JSON string containing a JSON array, that is generated from
518
- * this Array instance.
519
- * _state_ is a JSON::State object, that can also be used to configure the
520
- * produced JSON string output further.
521
- */
522
- static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self) {
523
- rb_check_arity(argc, 0, 1);
524
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
525
- return cState_partial_generate(Vstate, self, generate_json_array, Qfalse);
526
- }
527
-
528
- #ifdef RUBY_INTEGER_UNIFICATION
529
- /*
530
- * call-seq: to_json(*)
531
- *
532
- * Returns a JSON string representation for this Integer number.
533
- */
534
- static VALUE mInteger_to_json(int argc, VALUE *argv, VALUE self)
535
- {
536
- rb_check_arity(argc, 0, 1);
537
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
538
- return cState_partial_generate(Vstate, self, generate_json_integer, Qfalse);
539
- }
540
-
541
- #else
542
- /*
543
- * call-seq: to_json(*)
544
- *
545
- * Returns a JSON string representation for this Integer number.
546
- */
547
- static VALUE mFixnum_to_json(int argc, VALUE *argv, VALUE self)
548
- {
549
- rb_check_arity(argc, 0, 1);
550
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
551
- return cState_partial_generate(Vstate, self, generate_json_fixnum, Qfalse);
552
- }
553
-
554
- /*
555
- * call-seq: to_json(*)
556
- *
557
- * Returns a JSON string representation for this Integer number.
558
- */
559
- static VALUE mBignum_to_json(int argc, VALUE *argv, VALUE self)
560
- {
561
- rb_check_arity(argc, 0, 1);
562
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
563
- return cState_partial_generate(Vstate, self, generate_json_bignum, Qfalse);
564
- }
565
- #endif
566
-
567
- /*
568
- * call-seq: to_json(*)
569
- *
570
- * Returns a JSON string representation for this Float number.
571
- */
572
- static VALUE mFloat_to_json(int argc, VALUE *argv, VALUE self)
573
- {
574
- rb_check_arity(argc, 0, 1);
575
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
576
- return cState_partial_generate(Vstate, self, generate_json_float, Qfalse);
577
- }
578
-
579
- /*
580
- * call-seq: String.included(modul)
581
- *
582
- * Extends _modul_ with the String::Extend module.
583
- */
584
- static VALUE mString_included_s(VALUE self, VALUE modul) {
585
- VALUE result = rb_funcall(modul, i_extend, 1, mString_Extend);
586
- rb_call_super(1, &modul);
587
- return result;
588
- }
589
-
590
- /*
591
- * call-seq: to_json(*)
592
- *
593
- * This string should be encoded with UTF-8 A call to this method
594
- * returns a JSON string encoded with UTF16 big endian characters as
595
- * \u????.
596
- */
597
- static VALUE mString_to_json(int argc, VALUE *argv, VALUE self)
598
- {
599
- rb_check_arity(argc, 0, 1);
600
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
601
- return cState_partial_generate(Vstate, self, generate_json_string, Qfalse);
602
- }
603
-
604
- /*
605
- * call-seq: to_json_raw_object()
606
- *
607
- * This method creates a raw object hash, that can be nested into
608
- * other data structures and will be generated as a raw string. This
609
- * method should be used, if you want to convert raw strings to JSON
610
- * instead of UTF-8 strings, e. g. binary data.
611
- */
612
- static VALUE mString_to_json_raw_object(VALUE self)
613
- {
614
- VALUE ary;
615
- VALUE result = rb_hash_new();
616
- rb_hash_aset(result, rb_funcall(mJSON, i_create_id, 0), rb_class_name(rb_obj_class(self)));
617
- ary = rb_funcall(self, i_unpack, 1, rb_str_new2("C*"));
618
- rb_hash_aset(result, rb_utf8_str_new_lit("raw"), ary);
619
- return result;
620
- }
621
-
622
- /*
623
- * call-seq: to_json_raw(*args)
624
- *
625
- * This method creates a JSON text from the result of a call to
626
- * to_json_raw_object of this String.
627
- */
628
- static VALUE mString_to_json_raw(int argc, VALUE *argv, VALUE self)
629
- {
630
- VALUE obj = mString_to_json_raw_object(self);
631
- Check_Type(obj, T_HASH);
632
- return mHash_to_json(argc, argv, obj);
633
- }
634
-
635
- /*
636
- * call-seq: json_create(o)
637
- *
638
- * Raw Strings are JSON Objects (the raw bytes are stored in an array for the
639
- * key "raw"). The Ruby String can be created by this module method.
640
- */
641
- static VALUE mString_Extend_json_create(VALUE self, VALUE o)
642
- {
643
- VALUE ary;
644
- Check_Type(o, T_HASH);
645
- ary = rb_hash_aref(o, rb_str_new2("raw"));
646
- return rb_funcall(ary, i_pack, 1, rb_str_new2("C*"));
647
- }
648
-
649
- /*
650
- * call-seq: to_json(*)
651
- *
652
- * Returns a JSON string for true: 'true'.
653
- */
654
- static VALUE mTrueClass_to_json(int argc, VALUE *argv, VALUE self)
655
- {
656
- rb_check_arity(argc, 0, 1);
657
- return rb_utf8_str_new("true", 4);
658
- }
659
-
660
- /*
661
- * call-seq: to_json(*)
662
- *
663
- * Returns a JSON string for false: 'false'.
664
- */
665
- static VALUE mFalseClass_to_json(int argc, VALUE *argv, VALUE self)
666
- {
667
- rb_check_arity(argc, 0, 1);
668
- return rb_utf8_str_new("false", 5);
669
- }
670
-
671
- /*
672
- * call-seq: to_json(*)
673
- *
674
- * Returns a JSON string for nil: 'null'.
675
- */
676
- static VALUE mNilClass_to_json(int argc, VALUE *argv, VALUE self)
677
- {
678
- rb_check_arity(argc, 0, 1);
679
- return rb_utf8_str_new("null", 4);
680
- }
681
-
682
- /*
683
- * call-seq: to_json(*)
684
- *
685
- * Converts this object to a string (calling #to_s), converts
686
- * it to a JSON string, and returns the result. This is a fallback, if no
687
- * special method #to_json was defined for some object.
688
- */
689
- static VALUE mObject_to_json(int argc, VALUE *argv, VALUE self)
690
- {
691
- VALUE state;
692
- VALUE string = rb_funcall(self, i_to_s, 0);
693
- rb_scan_args(argc, argv, "01", &state);
694
- Check_Type(string, T_STRING);
695
- state = cState_from_state_s(cState, state);
696
- return cState_partial_generate(state, string, generate_json_string, Qfalse);
697
- }
698
-
699
703
  static void State_mark(void *ptr)
700
704
  {
701
705
  JSON_Generator_State *state = ptr;
@@ -718,32 +722,20 @@ static void State_compact(void *ptr)
718
722
  state->as_json = rb_gc_location(state->as_json);
719
723
  }
720
724
 
721
- static void State_free(void *ptr)
722
- {
723
- JSON_Generator_State *state = ptr;
724
- ruby_xfree(state);
725
- }
726
-
727
725
  static size_t State_memsize(const void *ptr)
728
726
  {
729
727
  return sizeof(JSON_Generator_State);
730
728
  }
731
729
 
732
- #ifndef HAVE_RB_EXT_RACTOR_SAFE
733
- # undef RUBY_TYPED_FROZEN_SHAREABLE
734
- # define RUBY_TYPED_FROZEN_SHAREABLE 0
735
- #endif
736
-
737
730
  static const rb_data_type_t JSON_Generator_State_type = {
738
- "JSON/Generator/State",
739
- {
731
+ .wrap_struct_name = "JSON/Generator/State",
732
+ .function = {
740
733
  .dmark = State_mark,
741
- .dfree = State_free,
734
+ .dfree = RUBY_DEFAULT_FREE,
742
735
  .dsize = State_memsize,
743
736
  .dcompact = State_compact,
744
737
  },
745
- 0, 0,
746
- RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE,
738
+ .flags = RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE | RUBY_TYPED_EMBEDDABLE,
747
739
  };
748
740
 
749
741
  static void state_init(JSON_Generator_State *state)
@@ -775,19 +767,193 @@ static void vstate_spill(struct generate_json_data *data)
775
767
  RB_OBJ_WRITTEN(vstate, Qundef, state->as_json);
776
768
  }
777
769
 
778
- static inline VALUE vstate_get(struct generate_json_data *data)
770
+ static inline VALUE json_call_to_json(struct generate_json_data *data, VALUE obj)
779
771
  {
780
772
  if (RB_UNLIKELY(!data->vstate)) {
781
773
  vstate_spill(data);
782
774
  }
783
- return data->vstate;
775
+ GET_STATE(data->vstate);
776
+ state->depth = data->depth;
777
+ VALUE tmp = rb_funcall(obj, i_to_json, 1, data->vstate);
778
+ // no need to restore state->depth, vstate is just a temporary State
779
+ return tmp;
780
+ }
781
+
782
+ static VALUE
783
+ json_call_as_json(JSON_Generator_State *state, VALUE object, VALUE is_key)
784
+ {
785
+ VALUE proc_args[2] = {object, is_key};
786
+ return rb_proc_call_with_block(state->as_json, 2, proc_args, Qnil);
787
+ }
788
+
789
+ static VALUE
790
+ convert_string_subclass(VALUE key)
791
+ {
792
+ VALUE key_to_s = rb_funcall(key, i_to_s, 0);
793
+
794
+ if (RB_UNLIKELY(!RB_TYPE_P(key_to_s, T_STRING))) {
795
+ VALUE cname = rb_obj_class(key);
796
+ rb_raise(rb_eTypeError,
797
+ "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")",
798
+ cname, "String", cname, "to_s", rb_obj_class(key_to_s));
799
+ }
800
+
801
+ return key_to_s;
802
+ }
803
+
804
+ static bool enc_utf8_compatible_p(int enc_idx)
805
+ {
806
+ if (enc_idx == usascii_encindex) return true;
807
+ if (enc_idx == utf8_encindex) return true;
808
+ return false;
809
+ }
810
+
811
+ static VALUE encode_json_string_try(VALUE str)
812
+ {
813
+ return rb_funcall(str, i_encode, 1, Encoding_UTF_8);
814
+ }
815
+
816
+ static VALUE encode_json_string_rescue(VALUE str, VALUE exception)
817
+ {
818
+ raise_generator_error_str(str, rb_funcall(exception, rb_intern("message"), 0));
819
+ return Qundef;
820
+ }
821
+
822
+ static inline int json_str_coderange(VALUE str) {
823
+ int coderange = RB_ENC_CODERANGE(str);
824
+ if (coderange == RUBY_ENC_CODERANGE_UNKNOWN) {
825
+ coderange = rb_enc_str_coderange(str);
826
+ }
827
+ return coderange;
828
+ }
829
+
830
+ static inline bool valid_json_string_p(VALUE str)
831
+ {
832
+ int coderange = json_str_coderange(str);
833
+
834
+ if (RB_LIKELY(coderange == ENC_CODERANGE_7BIT)) {
835
+ return true;
836
+ }
837
+
838
+ if (RB_LIKELY(coderange == ENC_CODERANGE_VALID)) {
839
+ return enc_utf8_compatible_p(RB_ENCODING_GET_INLINED(str));
840
+ }
841
+
842
+ return false;
843
+ }
844
+
845
+ NOINLINE(static) VALUE convert_invalid_encoding(struct generate_json_data *data, VALUE str, bool as_json_called, bool is_key)
846
+ {
847
+ if (!as_json_called && data->state->strict && RTEST(data->state->as_json)) {
848
+ VALUE coerced_str = json_call_as_json(data->state, str, Qfalse);
849
+ if (coerced_str != str) {
850
+ if (RB_TYPE_P(coerced_str, T_STRING)) {
851
+ if (!valid_json_string_p(coerced_str)) {
852
+ raise_generator_error(str, "source sequence is illegal/malformed utf-8");
853
+ }
854
+ } else {
855
+ // as_json could return another type than T_STRING
856
+ if (is_key) {
857
+ raise_generator_error(coerced_str, "%"PRIsVALUE" not allowed as object key in JSON", CLASS_OF(coerced_str));
858
+ }
859
+ }
860
+
861
+ return coerced_str;
862
+ }
863
+ }
864
+
865
+ if (RB_ENCODING_GET_INLINED(str) == binary_encindex) {
866
+ VALUE utf8_string = rb_enc_associate_index(rb_str_dup(str), utf8_encindex);
867
+ switch (rb_enc_str_coderange(utf8_string)) {
868
+ case ENC_CODERANGE_7BIT:
869
+ return utf8_string;
870
+ case ENC_CODERANGE_VALID:
871
+ // For historical reason, we silently reinterpret binary strings as UTF-8 if it would work.
872
+ // TODO: Raise in 3.0.0
873
+ rb_warn("JSON.generate: UTF-8 string passed as BINARY, this will raise an encoding error in json 3.0");
874
+ return utf8_string;
875
+ break;
876
+ }
877
+ }
878
+
879
+ return rb_rescue(encode_json_string_try, str, encode_json_string_rescue, str);
880
+ }
881
+
882
+ ALWAYS_INLINE(static) VALUE ensure_valid_encoding(struct generate_json_data *data, VALUE str, bool as_json_called, bool is_key)
883
+ {
884
+ if (RB_LIKELY(valid_json_string_p(str))) {
885
+ return str;
886
+ }
887
+ else {
888
+ return convert_invalid_encoding(data, str, as_json_called, is_key);
889
+ }
890
+ }
891
+
892
+ static void raw_generate_json_string(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
893
+ {
894
+ fbuffer_append_char(buffer, '"');
895
+
896
+ long len;
897
+ search_state search;
898
+ search.buffer = buffer;
899
+ RSTRING_GETMEM(obj, search.ptr, len);
900
+ search.cursor = search.ptr;
901
+ search.end = search.ptr + len;
902
+
903
+ #ifdef HAVE_SIMD
904
+ search.matches_mask = 0;
905
+ search.has_matches = false;
906
+ search.chunk_base = NULL;
907
+ search.chunk_end = NULL;
908
+ #endif /* HAVE_SIMD */
909
+
910
+ switch (json_str_coderange(obj)) {
911
+ case ENC_CODERANGE_7BIT:
912
+ case ENC_CODERANGE_VALID:
913
+ if (RB_UNLIKELY(data->state->ascii_only)) {
914
+ convert_UTF8_to_ASCII_only_JSON(&search, data->state->script_safe ? script_safe_escape_table : ascii_only_escape_table);
915
+ } else if (RB_UNLIKELY(data->state->script_safe)) {
916
+ convert_UTF8_to_script_safe_JSON(&search);
917
+ } else {
918
+ convert_UTF8_to_JSON(&search);
919
+ }
920
+ break;
921
+ default:
922
+ raise_generator_error(obj, "source sequence is illegal/malformed utf-8");
923
+ break;
924
+ }
925
+ fbuffer_append_char(buffer, '"');
926
+ }
927
+
928
+ static void generate_json_string(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
929
+ {
930
+ obj = ensure_valid_encoding(data, obj, false, false);
931
+ raw_generate_json_string(buffer, data, obj);
784
932
  }
785
933
 
786
934
  struct hash_foreach_arg {
935
+ VALUE hash;
787
936
  struct generate_json_data *data;
788
- int iter;
937
+ int first_key_type;
938
+ bool first;
939
+ bool mixed_keys_encountered;
789
940
  };
790
941
 
942
+ NOINLINE(static) void
943
+ json_inspect_hash_with_mixed_keys(struct hash_foreach_arg *arg)
944
+ {
945
+ if (arg->mixed_keys_encountered) {
946
+ return;
947
+ }
948
+ arg->mixed_keys_encountered = true;
949
+
950
+ JSON_Generator_State *state = arg->data->state;
951
+ if (state->on_duplicate_key != JSON_IGNORE) {
952
+ VALUE do_raise = state->on_duplicate_key == JSON_RAISE ? Qtrue : Qfalse;
953
+ rb_funcall(mJSON, rb_intern("on_mixed_keys_hash"), 2, arg->hash, do_raise);
954
+ }
955
+ }
956
+
791
957
  static int
792
958
  json_object_i(VALUE key, VALUE val, VALUE _arg)
793
959
  {
@@ -797,304 +963,257 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
797
963
  FBuffer *buffer = data->buffer;
798
964
  JSON_Generator_State *state = data->state;
799
965
 
800
- long depth = state->depth;
801
- int j;
966
+ long depth = data->depth;
967
+ int key_type = rb_type(key);
802
968
 
803
- if (arg->iter > 0) fbuffer_append_char(buffer, ',');
804
- if (RB_UNLIKELY(state->object_nl)) {
805
- fbuffer_append_str(buffer, state->object_nl);
969
+ if (arg->first) {
970
+ arg->first = false;
971
+ arg->first_key_type = key_type;
806
972
  }
807
- if (RB_UNLIKELY(state->indent)) {
808
- for (j = 0; j < depth; j++) {
809
- fbuffer_append_str(buffer, state->indent);
810
- }
973
+ else {
974
+ fbuffer_append_char(buffer, ',');
975
+ }
976
+
977
+ if (RB_UNLIKELY(data->state->object_nl)) {
978
+ fbuffer_append_str(buffer, data->state->object_nl);
979
+ }
980
+ if (RB_UNLIKELY(data->state->indent)) {
981
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
811
982
  }
812
983
 
813
984
  VALUE key_to_s;
814
- switch(rb_type(key)) {
985
+ bool as_json_called = false;
986
+
987
+ start:
988
+ switch (key_type) {
815
989
  case T_STRING:
990
+ if (RB_UNLIKELY(arg->first_key_type != T_STRING)) {
991
+ json_inspect_hash_with_mixed_keys(arg);
992
+ }
993
+
816
994
  if (RB_LIKELY(RBASIC_CLASS(key) == rb_cString)) {
817
995
  key_to_s = key;
818
996
  } else {
819
- key_to_s = rb_funcall(key, i_to_s, 0);
997
+ key_to_s = convert_string_subclass(key);
820
998
  }
821
999
  break;
822
1000
  case T_SYMBOL:
1001
+ if (RB_UNLIKELY(arg->first_key_type != T_SYMBOL)) {
1002
+ json_inspect_hash_with_mixed_keys(arg);
1003
+ }
1004
+
823
1005
  key_to_s = rb_sym2str(key);
824
1006
  break;
825
1007
  default:
1008
+ if (data->state->strict) {
1009
+ if (RTEST(data->state->as_json) && !as_json_called) {
1010
+ key = json_call_as_json(data->state, key, Qtrue);
1011
+ key_type = rb_type(key);
1012
+ as_json_called = true;
1013
+ goto start;
1014
+ } else {
1015
+ raise_generator_error(key, "%"PRIsVALUE" not allowed as object key in JSON", CLASS_OF(key));
1016
+ }
1017
+ }
826
1018
  key_to_s = rb_convert_type(key, T_STRING, "String", "to_s");
827
1019
  break;
828
1020
  }
829
1021
 
1022
+ key_to_s = ensure_valid_encoding(data, key_to_s, as_json_called, true);
1023
+
830
1024
  if (RB_LIKELY(RBASIC_CLASS(key_to_s) == rb_cString)) {
831
- generate_json_string(buffer, data, state, key_to_s);
1025
+ raw_generate_json_string(buffer, data, key_to_s);
832
1026
  } else {
833
- generate_json(buffer, data, state, key_to_s);
1027
+ generate_json(buffer, data, key_to_s);
834
1028
  }
835
- if (RB_UNLIKELY(state->space_before)) fbuffer_append_str(buffer, state->space_before);
1029
+ if (RB_UNLIKELY(state->space_before)) fbuffer_append_str(buffer, data->state->space_before);
836
1030
  fbuffer_append_char(buffer, ':');
837
- if (RB_UNLIKELY(state->space)) fbuffer_append_str(buffer, state->space);
838
- generate_json(buffer, data, state, val);
1031
+ if (RB_UNLIKELY(state->space)) fbuffer_append_str(buffer, data->state->space);
1032
+ generate_json(buffer, data, val);
839
1033
 
840
- arg->iter++;
841
1034
  return ST_CONTINUE;
842
1035
  }
843
1036
 
844
- static inline long increase_depth(JSON_Generator_State *state)
1037
+ static inline long increase_depth(struct generate_json_data *data)
845
1038
  {
846
- long depth = ++state->depth;
1039
+ JSON_Generator_State *state = data->state;
1040
+ long depth = ++data->depth;
847
1041
  if (RB_UNLIKELY(depth > state->max_nesting && state->max_nesting)) {
848
- rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
1042
+ rb_raise(eNestingError, "nesting of %ld is too deep. Did you try to serialize objects with circular references?", --data->depth);
849
1043
  }
850
1044
  return depth;
851
1045
  }
852
1046
 
853
- static void generate_json_object(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1047
+ static void generate_json_object(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
854
1048
  {
855
- int j;
856
- long depth = increase_depth(state);
1049
+ long depth = increase_depth(data);
857
1050
 
858
1051
  if (RHASH_SIZE(obj) == 0) {
859
1052
  fbuffer_append(buffer, "{}", 2);
860
- --state->depth;
1053
+ --data->depth;
861
1054
  return;
862
1055
  }
863
1056
 
864
1057
  fbuffer_append_char(buffer, '{');
865
1058
 
866
1059
  struct hash_foreach_arg arg = {
1060
+ .hash = obj,
867
1061
  .data = data,
868
- .iter = 0,
1062
+ .first = true,
869
1063
  };
870
1064
  rb_hash_foreach(obj, json_object_i, (VALUE)&arg);
871
1065
 
872
- depth = --state->depth;
873
- if (RB_UNLIKELY(state->object_nl)) {
874
- fbuffer_append_str(buffer, state->object_nl);
875
- if (RB_UNLIKELY(state->indent)) {
876
- for (j = 0; j < depth; j++) {
877
- fbuffer_append_str(buffer, state->indent);
878
- }
1066
+ depth = --data->depth;
1067
+ if (RB_UNLIKELY(data->state->object_nl)) {
1068
+ fbuffer_append_str(buffer, data->state->object_nl);
1069
+ if (RB_UNLIKELY(data->state->indent)) {
1070
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
879
1071
  }
880
1072
  }
881
1073
  fbuffer_append_char(buffer, '}');
882
1074
  }
883
1075
 
884
- static void generate_json_array(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1076
+ static void generate_json_array(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
885
1077
  {
886
- int i, j;
887
- long depth = increase_depth(state);
1078
+ long depth = increase_depth(data);
888
1079
 
889
1080
  if (RARRAY_LEN(obj) == 0) {
890
1081
  fbuffer_append(buffer, "[]", 2);
891
- --state->depth;
1082
+ --data->depth;
892
1083
  return;
893
1084
  }
894
1085
 
895
1086
  fbuffer_append_char(buffer, '[');
896
- if (RB_UNLIKELY(state->array_nl)) fbuffer_append_str(buffer, state->array_nl);
897
- for(i = 0; i < RARRAY_LEN(obj); i++) {
1087
+ if (RB_UNLIKELY(data->state->array_nl)) fbuffer_append_str(buffer, data->state->array_nl);
1088
+ for (int i = 0; i < RARRAY_LEN(obj); i++) {
898
1089
  if (i > 0) {
899
1090
  fbuffer_append_char(buffer, ',');
900
- if (RB_UNLIKELY(state->array_nl)) fbuffer_append_str(buffer, state->array_nl);
1091
+ if (RB_UNLIKELY(data->state->array_nl)) fbuffer_append_str(buffer, data->state->array_nl);
901
1092
  }
902
- if (RB_UNLIKELY(state->indent)) {
903
- for (j = 0; j < depth; j++) {
904
- fbuffer_append_str(buffer, state->indent);
905
- }
1093
+ if (RB_UNLIKELY(data->state->indent)) {
1094
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
906
1095
  }
907
- generate_json(buffer, data, state, RARRAY_AREF(obj, i));
1096
+ generate_json(buffer, data, RARRAY_AREF(obj, i));
908
1097
  }
909
- state->depth = --depth;
910
- if (RB_UNLIKELY(state->array_nl)) {
911
- fbuffer_append_str(buffer, state->array_nl);
912
- if (RB_UNLIKELY(state->indent)) {
913
- for (j = 0; j < depth; j++) {
914
- fbuffer_append_str(buffer, state->indent);
915
- }
1098
+ data->depth = --depth;
1099
+ if (RB_UNLIKELY(data->state->array_nl)) {
1100
+ fbuffer_append_str(buffer, data->state->array_nl);
1101
+ if (RB_UNLIKELY(data->state->indent)) {
1102
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
916
1103
  }
917
1104
  }
918
1105
  fbuffer_append_char(buffer, ']');
919
1106
  }
920
1107
 
921
- static inline int enc_utf8_compatible_p(int enc_idx)
922
- {
923
- if (enc_idx == usascii_encindex) return 1;
924
- if (enc_idx == utf8_encindex) return 1;
925
- return 0;
926
- }
927
-
928
- static VALUE encode_json_string_try(VALUE str)
929
- {
930
- return rb_funcall(str, i_encode, 1, Encoding_UTF_8);
931
- }
932
-
933
- static VALUE encode_json_string_rescue(VALUE str, VALUE exception)
934
- {
935
- raise_generator_error_str(str, rb_funcall(exception, rb_intern("message"), 0));
936
- return Qundef;
937
- }
938
-
939
- static inline VALUE ensure_valid_encoding(VALUE str)
940
- {
941
- int encindex = RB_ENCODING_GET(str);
942
- VALUE utf8_string;
943
- if (RB_UNLIKELY(!enc_utf8_compatible_p(encindex))) {
944
- if (encindex == binary_encindex) {
945
- utf8_string = rb_enc_associate_index(rb_str_dup(str), utf8_encindex);
946
- switch (rb_enc_str_coderange(utf8_string)) {
947
- case ENC_CODERANGE_7BIT:
948
- return utf8_string;
949
- case ENC_CODERANGE_VALID:
950
- // For historical reason, we silently reinterpret binary strings as UTF-8 if it would work.
951
- // TODO: Raise in 3.0.0
952
- rb_warn("JSON.generate: UTF-8 string passed as BINARY, this will raise an encoding error in json 3.0");
953
- return utf8_string;
954
- break;
955
- }
956
- }
957
-
958
- str = rb_rescue(encode_json_string_try, str, encode_json_string_rescue, str);
959
- }
960
- return str;
961
- }
962
-
963
- static void generate_json_string(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
964
- {
965
- obj = ensure_valid_encoding(obj);
966
-
967
- fbuffer_append_char(buffer, '"');
968
-
969
- long len;
970
- search_state search;
971
- search.buffer = buffer;
972
- RSTRING_GETMEM(obj, search.ptr, len);
973
- search.cursor = search.ptr;
974
- search.end = search.ptr + len;
975
-
976
- switch(rb_enc_str_coderange(obj)) {
977
- case ENC_CODERANGE_7BIT:
978
- case ENC_CODERANGE_VALID:
979
- if (RB_UNLIKELY(state->ascii_only)) {
980
- convert_UTF8_to_ASCII_only_JSON(&search, state->script_safe ? script_safe_escape_table : ascii_only_escape_table);
981
- } else if (RB_UNLIKELY(state->script_safe)) {
982
- convert_UTF8_to_script_safe_JSON(&search);
983
- } else {
984
- convert_UTF8_to_JSON(&search);
985
- }
986
- break;
987
- default:
988
- raise_generator_error(obj, "source sequence is illegal/malformed utf-8");
989
- break;
990
- }
991
- fbuffer_append_char(buffer, '"');
992
- }
993
-
994
- static void generate_json_fallback(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1108
+ static void generate_json_fallback(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
995
1109
  {
996
1110
  VALUE tmp;
997
1111
  if (rb_respond_to(obj, i_to_json)) {
998
- tmp = rb_funcall(obj, i_to_json, 1, vstate_get(data));
1112
+ tmp = json_call_to_json(data, obj);
999
1113
  Check_Type(tmp, T_STRING);
1000
1114
  fbuffer_append_str(buffer, tmp);
1001
1115
  } else {
1002
1116
  tmp = rb_funcall(obj, i_to_s, 0);
1003
1117
  Check_Type(tmp, T_STRING);
1004
- generate_json_string(buffer, data, state, tmp);
1118
+ generate_json_string(buffer, data, tmp);
1005
1119
  }
1006
1120
  }
1007
1121
 
1008
- static inline void generate_json_symbol(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1122
+ static inline void generate_json_symbol(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1009
1123
  {
1010
- if (state->strict) {
1011
- generate_json_string(buffer, data, state, rb_sym2str(obj));
1124
+ if (data->state->strict) {
1125
+ generate_json_string(buffer, data, rb_sym2str(obj));
1012
1126
  } else {
1013
- generate_json_fallback(buffer, data, state, obj);
1127
+ generate_json_fallback(buffer, data, obj);
1014
1128
  }
1015
1129
  }
1016
1130
 
1017
- static void generate_json_null(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1131
+ static void generate_json_null(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1018
1132
  {
1019
1133
  fbuffer_append(buffer, "null", 4);
1020
1134
  }
1021
1135
 
1022
- static void generate_json_false(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1136
+ static void generate_json_false(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1023
1137
  {
1024
1138
  fbuffer_append(buffer, "false", 5);
1025
1139
  }
1026
1140
 
1027
- static void generate_json_true(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1141
+ static void generate_json_true(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1028
1142
  {
1029
1143
  fbuffer_append(buffer, "true", 4);
1030
1144
  }
1031
1145
 
1032
- static void generate_json_fixnum(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1146
+ static void generate_json_fixnum(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1033
1147
  {
1034
1148
  fbuffer_append_long(buffer, FIX2LONG(obj));
1035
1149
  }
1036
1150
 
1037
- static void generate_json_bignum(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1151
+ static void generate_json_bignum(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1038
1152
  {
1039
1153
  VALUE tmp = rb_funcall(obj, i_to_s, 0);
1040
- fbuffer_append_str(buffer, tmp);
1154
+ fbuffer_append_str(buffer, StringValue(tmp));
1041
1155
  }
1042
1156
 
1043
- #ifdef RUBY_INTEGER_UNIFICATION
1044
- static void generate_json_integer(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1045
- {
1046
- if (FIXNUM_P(obj))
1047
- generate_json_fixnum(buffer, data, state, obj);
1048
- else
1049
- generate_json_bignum(buffer, data, state, obj);
1050
- }
1051
- #endif
1052
-
1053
- static void generate_json_float(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1157
+ static void generate_json_float(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1054
1158
  {
1055
1159
  double value = RFLOAT_VALUE(obj);
1056
- char allow_nan = state->allow_nan;
1057
- if (!allow_nan) {
1058
- if (isinf(value) || isnan(value)) {
1059
- if (state->strict && state->as_json) {
1060
- VALUE casted_obj = rb_proc_call_with_block(state->as_json, 1, &obj, Qnil);
1160
+ char allow_nan = data->state->allow_nan;
1161
+ if (isinf(value) || isnan(value)) {
1162
+ /* for NaN and Infinity values we either raise an error or rely on Float#to_s. */
1163
+ if (!allow_nan) {
1164
+ if (data->state->strict && data->state->as_json) {
1165
+ VALUE casted_obj = json_call_as_json(data->state, obj, Qfalse);
1061
1166
  if (casted_obj != obj) {
1062
- increase_depth(state);
1063
- generate_json(buffer, data, state, casted_obj);
1064
- state->depth--;
1167
+ increase_depth(data);
1168
+ generate_json(buffer, data, casted_obj);
1169
+ data->depth--;
1065
1170
  return;
1066
1171
  }
1067
1172
  }
1068
1173
  raise_generator_error(obj, "%"PRIsVALUE" not allowed in JSON", rb_funcall(obj, i_to_s, 0));
1069
1174
  }
1175
+
1176
+ VALUE tmp = rb_funcall(obj, i_to_s, 0);
1177
+ fbuffer_append_str(buffer, tmp);
1178
+ return;
1070
1179
  }
1071
- fbuffer_append_str(buffer, rb_funcall(obj, i_to_s, 0));
1180
+
1181
+ /* This implementation writes directly into the buffer. We reserve
1182
+ * the 32 characters that fpconv_dtoa states as its maximum.
1183
+ */
1184
+ fbuffer_inc_capa(buffer, 32);
1185
+ char* d = buffer->ptr + buffer->len;
1186
+ int len = fpconv_dtoa(value, d);
1187
+ /* fpconv_dtoa converts a float to its shortest string representation,
1188
+ * but it adds a ".0" if this is a plain integer.
1189
+ */
1190
+ fbuffer_consumed(buffer, len);
1072
1191
  }
1073
1192
 
1074
- static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1193
+ static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1075
1194
  {
1076
1195
  VALUE fragment = RSTRUCT_GET(obj, 0);
1077
1196
  Check_Type(fragment, T_STRING);
1078
1197
  fbuffer_append_str(buffer, fragment);
1079
1198
  }
1080
1199
 
1081
- static void generate_json(FBuffer *buffer, struct generate_json_data *data, JSON_Generator_State *state, VALUE obj)
1200
+ static inline void generate_json_general(FBuffer *buffer, struct generate_json_data *data, VALUE obj, bool fallback)
1082
1201
  {
1083
1202
  bool as_json_called = false;
1084
1203
  start:
1085
1204
  if (obj == Qnil) {
1086
- generate_json_null(buffer, data, state, obj);
1205
+ generate_json_null(buffer, data, obj);
1087
1206
  } else if (obj == Qfalse) {
1088
- generate_json_false(buffer, data, state, obj);
1207
+ generate_json_false(buffer, data, obj);
1089
1208
  } else if (obj == Qtrue) {
1090
- generate_json_true(buffer, data, state, obj);
1209
+ generate_json_true(buffer, data, obj);
1091
1210
  } else if (RB_SPECIAL_CONST_P(obj)) {
1092
1211
  if (RB_FIXNUM_P(obj)) {
1093
- generate_json_fixnum(buffer, data, state, obj);
1212
+ generate_json_fixnum(buffer, data, obj);
1094
1213
  } else if (RB_FLONUM_P(obj)) {
1095
- generate_json_float(buffer, data, state, obj);
1214
+ generate_json_float(buffer, data, obj);
1096
1215
  } else if (RB_STATIC_SYM_P(obj)) {
1097
- generate_json_symbol(buffer, data, state, obj);
1216
+ generate_json_symbol(buffer, data, obj);
1098
1217
  } else {
1099
1218
  goto general;
1100
1219
  }
@@ -1102,87 +1221,101 @@ start:
1102
1221
  VALUE klass = RBASIC_CLASS(obj);
1103
1222
  switch (RB_BUILTIN_TYPE(obj)) {
1104
1223
  case T_BIGNUM:
1105
- generate_json_bignum(buffer, data, state, obj);
1224
+ generate_json_bignum(buffer, data, obj);
1106
1225
  break;
1107
1226
  case T_HASH:
1108
- if (klass != rb_cHash) goto general;
1109
- generate_json_object(buffer, data, state, obj);
1227
+ if (fallback && klass != rb_cHash) goto general;
1228
+ generate_json_object(buffer, data, obj);
1110
1229
  break;
1111
1230
  case T_ARRAY:
1112
- if (klass != rb_cArray) goto general;
1113
- generate_json_array(buffer, data, state, obj);
1231
+ if (fallback && klass != rb_cArray) goto general;
1232
+ generate_json_array(buffer, data, obj);
1114
1233
  break;
1115
1234
  case T_STRING:
1116
- if (klass != rb_cString) goto general;
1117
- generate_json_string(buffer, data, state, obj);
1235
+ if (fallback && klass != rb_cString) goto general;
1236
+
1237
+ if (RB_LIKELY(valid_json_string_p(obj))) {
1238
+ raw_generate_json_string(buffer, data, obj);
1239
+ } else if (as_json_called) {
1240
+ raise_generator_error(obj, "source sequence is illegal/malformed utf-8");
1241
+ } else {
1242
+ obj = ensure_valid_encoding(data, obj, false, false);
1243
+ as_json_called = true;
1244
+ goto start;
1245
+ }
1118
1246
  break;
1119
1247
  case T_SYMBOL:
1120
- generate_json_symbol(buffer, data, state, obj);
1248
+ generate_json_symbol(buffer, data, obj);
1121
1249
  break;
1122
1250
  case T_FLOAT:
1123
- if (klass != rb_cFloat) goto general;
1124
- generate_json_float(buffer, data, state, obj);
1251
+ if (fallback && klass != rb_cFloat) goto general;
1252
+ generate_json_float(buffer, data, obj);
1125
1253
  break;
1126
1254
  case T_STRUCT:
1127
1255
  if (klass != cFragment) goto general;
1128
- generate_json_fragment(buffer, data, state, obj);
1256
+ generate_json_fragment(buffer, data, obj);
1129
1257
  break;
1130
1258
  default:
1131
1259
  general:
1132
- if (state->strict) {
1133
- if (RTEST(state->as_json) && !as_json_called) {
1134
- obj = rb_proc_call_with_block(state->as_json, 1, &obj, Qnil);
1260
+ if (data->state->strict) {
1261
+ if (RTEST(data->state->as_json) && !as_json_called) {
1262
+ obj = json_call_as_json(data->state, obj, Qfalse);
1135
1263
  as_json_called = true;
1136
1264
  goto start;
1137
1265
  } else {
1138
1266
  raise_generator_error(obj, "%"PRIsVALUE" not allowed in JSON", CLASS_OF(obj));
1139
1267
  }
1140
1268
  } else {
1141
- generate_json_fallback(buffer, data, state, obj);
1269
+ generate_json_fallback(buffer, data, obj);
1142
1270
  }
1143
1271
  }
1144
1272
  }
1145
1273
  }
1146
1274
 
1275
+ static void generate_json(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1276
+ {
1277
+ generate_json_general(buffer, data, obj, true);
1278
+ }
1279
+
1280
+ static void generate_json_no_fallback(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1281
+ {
1282
+ generate_json_general(buffer, data, obj, false);
1283
+ }
1284
+
1147
1285
  static VALUE generate_json_try(VALUE d)
1148
1286
  {
1149
1287
  struct generate_json_data *data = (struct generate_json_data *)d;
1150
1288
 
1151
- data->func(data->buffer, data, data->state, data->obj);
1289
+ data->func(data->buffer, data, data->obj);
1152
1290
 
1153
- return Qnil;
1291
+ return fbuffer_finalize(data->buffer);
1154
1292
  }
1155
1293
 
1156
- static VALUE generate_json_rescue(VALUE d, VALUE exc)
1294
+ static VALUE generate_json_ensure(VALUE d)
1157
1295
  {
1158
1296
  struct generate_json_data *data = (struct generate_json_data *)d;
1159
1297
  fbuffer_free(data->buffer);
1160
1298
 
1161
- rb_exc_raise(exc);
1162
-
1163
1299
  return Qundef;
1164
1300
  }
1165
1301
 
1166
- static VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func func, VALUE io)
1302
+ static inline VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func func, VALUE io)
1167
1303
  {
1168
1304
  GET_STATE(self);
1169
1305
 
1170
1306
  char stack_buffer[FBUFFER_STACK_SIZE];
1171
- FBuffer buffer = {
1172
- .io = RTEST(io) ? io : Qfalse,
1173
- };
1174
- fbuffer_stack_init(&buffer, state->buffer_initial_length, stack_buffer, FBUFFER_STACK_SIZE);
1307
+ FBuffer buffer = { 0 };
1308
+ fbuffer_init(&buffer, state->buffer_initial_length, io, stack_buffer, FBUFFER_STACK_SIZE);
1175
1309
 
1176
1310
  struct generate_json_data data = {
1177
1311
  .buffer = &buffer,
1178
- .vstate = self,
1312
+ .vstate = Qfalse, // don't use self as it may be frozen and its depth is mutated when calling to_json
1179
1313
  .state = state,
1314
+ .depth = state->depth,
1180
1315
  .obj = obj,
1181
1316
  .func = func
1182
1317
  };
1183
- rb_rescue(generate_json_try, (VALUE)&data, generate_json_rescue, (VALUE)&data);
1184
-
1185
- return fbuffer_finalize(&buffer);
1318
+ return rb_ensure(generate_json_try, (VALUE)&data, generate_json_ensure, (VALUE)&data);
1186
1319
  }
1187
1320
 
1188
1321
  /* call-seq:
@@ -1198,10 +1331,16 @@ static VALUE cState_generate(int argc, VALUE *argv, VALUE self)
1198
1331
  rb_check_arity(argc, 1, 2);
1199
1332
  VALUE obj = argv[0];
1200
1333
  VALUE io = argc > 1 ? argv[1] : Qnil;
1201
- VALUE result = cState_partial_generate(self, obj, generate_json, io);
1202
- GET_STATE(self);
1203
- (void)state;
1204
- return result;
1334
+ return cState_partial_generate(self, obj, generate_json, io);
1335
+ }
1336
+
1337
+ /* :nodoc: */
1338
+ static VALUE cState_generate_no_fallback(int argc, VALUE *argv, VALUE self)
1339
+ {
1340
+ rb_check_arity(argc, 1, 2);
1341
+ VALUE obj = argv[0];
1342
+ VALUE io = argc > 1 ? argv[1] : Qnil;
1343
+ return cState_partial_generate(self, obj, generate_json_no_fallback, io);
1205
1344
  }
1206
1345
 
1207
1346
  static VALUE cState_initialize(int argc, VALUE *argv, VALUE self)
@@ -1226,12 +1365,14 @@ static VALUE cState_init_copy(VALUE obj, VALUE orig)
1226
1365
  if (!objState) rb_raise(rb_eArgError, "unallocated JSON::State");
1227
1366
 
1228
1367
  MEMCPY(objState, origState, JSON_Generator_State, 1);
1229
- objState->indent = origState->indent;
1230
- objState->space = origState->space;
1231
- objState->space_before = origState->space_before;
1232
- objState->object_nl = origState->object_nl;
1233
- objState->array_nl = origState->array_nl;
1234
- objState->as_json = origState->as_json;
1368
+
1369
+ RB_OBJ_WRITTEN(obj, Qundef, objState->indent);
1370
+ RB_OBJ_WRITTEN(obj, Qundef, objState->space);
1371
+ RB_OBJ_WRITTEN(obj, Qundef, objState->space_before);
1372
+ RB_OBJ_WRITTEN(obj, Qundef, objState->object_nl);
1373
+ RB_OBJ_WRITTEN(obj, Qundef, objState->array_nl);
1374
+ RB_OBJ_WRITTEN(obj, Qundef, objState->as_json);
1375
+
1235
1376
  return obj;
1236
1377
  }
1237
1378
 
@@ -1282,6 +1423,7 @@ static VALUE string_config(VALUE config)
1282
1423
  */
1283
1424
  static VALUE cState_indent_set(VALUE self, VALUE indent)
1284
1425
  {
1426
+ rb_check_frozen(self);
1285
1427
  GET_STATE(self);
1286
1428
  RB_OBJ_WRITE(self, &state->indent, string_config(indent));
1287
1429
  return Qnil;
@@ -1307,6 +1449,7 @@ static VALUE cState_space(VALUE self)
1307
1449
  */
1308
1450
  static VALUE cState_space_set(VALUE self, VALUE space)
1309
1451
  {
1452
+ rb_check_frozen(self);
1310
1453
  GET_STATE(self);
1311
1454
  RB_OBJ_WRITE(self, &state->space, string_config(space));
1312
1455
  return Qnil;
@@ -1330,6 +1473,7 @@ static VALUE cState_space_before(VALUE self)
1330
1473
  */
1331
1474
  static VALUE cState_space_before_set(VALUE self, VALUE space_before)
1332
1475
  {
1476
+ rb_check_frozen(self);
1333
1477
  GET_STATE(self);
1334
1478
  RB_OBJ_WRITE(self, &state->space_before, string_config(space_before));
1335
1479
  return Qnil;
@@ -1355,6 +1499,7 @@ static VALUE cState_object_nl(VALUE self)
1355
1499
  */
1356
1500
  static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)
1357
1501
  {
1502
+ rb_check_frozen(self);
1358
1503
  GET_STATE(self);
1359
1504
  RB_OBJ_WRITE(self, &state->object_nl, string_config(object_nl));
1360
1505
  return Qnil;
@@ -1378,6 +1523,7 @@ static VALUE cState_array_nl(VALUE self)
1378
1523
  */
1379
1524
  static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)
1380
1525
  {
1526
+ rb_check_frozen(self);
1381
1527
  GET_STATE(self);
1382
1528
  RB_OBJ_WRITE(self, &state->array_nl, string_config(array_nl));
1383
1529
  return Qnil;
@@ -1401,6 +1547,7 @@ static VALUE cState_as_json(VALUE self)
1401
1547
  */
1402
1548
  static VALUE cState_as_json_set(VALUE self, VALUE as_json)
1403
1549
  {
1550
+ rb_check_frozen(self);
1404
1551
  GET_STATE(self);
1405
1552
  RB_OBJ_WRITE(self, &state->as_json, rb_convert_type(as_json, T_DATA, "Proc", "to_proc"));
1406
1553
  return Qnil;
@@ -1432,7 +1579,21 @@ static VALUE cState_max_nesting(VALUE self)
1432
1579
 
1433
1580
  static long long_config(VALUE num)
1434
1581
  {
1435
- return RTEST(num) ? FIX2LONG(num) : 0;
1582
+ return RTEST(num) ? NUM2LONG(num) : 0;
1583
+ }
1584
+
1585
+ // depth must never be negative; reject early with a clear error.
1586
+ static long depth_config(VALUE num)
1587
+ {
1588
+ if (!RTEST(num)) return 0;
1589
+ long d = NUM2LONG(num);
1590
+ if (RB_UNLIKELY(d < 0)) {
1591
+ rb_raise(rb_eArgError, "depth must be >= 0 (got %ld)", d);
1592
+ }
1593
+ if (RB_UNLIKELY(d > INT_MAX)) {
1594
+ rb_raise(rb_eArgError, "depth is too large (got %ld)", d);
1595
+ }
1596
+ return d;
1436
1597
  }
1437
1598
 
1438
1599
  /*
@@ -1443,6 +1604,7 @@ static long long_config(VALUE num)
1443
1604
  */
1444
1605
  static VALUE cState_max_nesting_set(VALUE self, VALUE depth)
1445
1606
  {
1607
+ rb_check_frozen(self);
1446
1608
  GET_STATE(self);
1447
1609
  state->max_nesting = long_config(depth);
1448
1610
  return Qnil;
@@ -1468,6 +1630,7 @@ static VALUE cState_script_safe(VALUE self)
1468
1630
  */
1469
1631
  static VALUE cState_script_safe_set(VALUE self, VALUE enable)
1470
1632
  {
1633
+ rb_check_frozen(self);
1471
1634
  GET_STATE(self);
1472
1635
  state->script_safe = RTEST(enable);
1473
1636
  return Qnil;
@@ -1499,6 +1662,7 @@ static VALUE cState_strict(VALUE self)
1499
1662
  */
1500
1663
  static VALUE cState_strict_set(VALUE self, VALUE enable)
1501
1664
  {
1665
+ rb_check_frozen(self);
1502
1666
  GET_STATE(self);
1503
1667
  state->strict = RTEST(enable);
1504
1668
  return Qnil;
@@ -1523,6 +1687,7 @@ static VALUE cState_allow_nan_p(VALUE self)
1523
1687
  */
1524
1688
  static VALUE cState_allow_nan_set(VALUE self, VALUE enable)
1525
1689
  {
1690
+ rb_check_frozen(self);
1526
1691
  GET_STATE(self);
1527
1692
  state->allow_nan = RTEST(enable);
1528
1693
  return Qnil;
@@ -1547,11 +1712,25 @@ static VALUE cState_ascii_only_p(VALUE self)
1547
1712
  */
1548
1713
  static VALUE cState_ascii_only_set(VALUE self, VALUE enable)
1549
1714
  {
1715
+ rb_check_frozen(self);
1550
1716
  GET_STATE(self);
1551
1717
  state->ascii_only = RTEST(enable);
1552
1718
  return Qnil;
1553
1719
  }
1554
1720
 
1721
+ static VALUE cState_allow_duplicate_key_p(VALUE self)
1722
+ {
1723
+ GET_STATE(self);
1724
+ switch (state->on_duplicate_key) {
1725
+ case JSON_IGNORE:
1726
+ return Qtrue;
1727
+ case JSON_DEPRECATED:
1728
+ return Qnil;
1729
+ default:
1730
+ return Qfalse;
1731
+ }
1732
+ }
1733
+
1555
1734
  /*
1556
1735
  * call-seq: depth
1557
1736
  *
@@ -1571,8 +1750,9 @@ static VALUE cState_depth(VALUE self)
1571
1750
  */
1572
1751
  static VALUE cState_depth_set(VALUE self, VALUE depth)
1573
1752
  {
1753
+ rb_check_frozen(self);
1574
1754
  GET_STATE(self);
1575
- state->depth = long_config(depth);
1755
+ state->depth = depth_config(depth);
1576
1756
  return Qnil;
1577
1757
  }
1578
1758
 
@@ -1604,33 +1784,54 @@ static void buffer_initial_length_set(JSON_Generator_State *state, VALUE buffer_
1604
1784
  */
1605
1785
  static VALUE cState_buffer_initial_length_set(VALUE self, VALUE buffer_initial_length)
1606
1786
  {
1787
+ rb_check_frozen(self);
1607
1788
  GET_STATE(self);
1608
1789
  buffer_initial_length_set(state, buffer_initial_length);
1609
1790
  return Qnil;
1610
1791
  }
1611
1792
 
1793
+ struct configure_state_data {
1794
+ JSON_Generator_State *state;
1795
+ VALUE vstate; // Ruby object that owns the state, or Qfalse if stack-allocated
1796
+ };
1797
+
1798
+ static inline void state_write_value(struct configure_state_data *data, VALUE *field, VALUE value)
1799
+ {
1800
+ if (RTEST(data->vstate)) {
1801
+ RB_OBJ_WRITE(data->vstate, field, value);
1802
+ } else {
1803
+ *field = value;
1804
+ }
1805
+ }
1806
+
1612
1807
  static int configure_state_i(VALUE key, VALUE val, VALUE _arg)
1613
1808
  {
1614
- JSON_Generator_State *state = (JSON_Generator_State *)_arg;
1809
+ struct configure_state_data *data = (struct configure_state_data *)_arg;
1810
+ JSON_Generator_State *state = data->state;
1615
1811
 
1616
- if (key == sym_indent) { state->indent = string_config(val); }
1617
- else if (key == sym_space) { state->space = string_config(val); }
1618
- else if (key == sym_space_before) { state->space_before = string_config(val); }
1619
- else if (key == sym_object_nl) { state->object_nl = string_config(val); }
1620
- else if (key == sym_array_nl) { state->array_nl = string_config(val); }
1812
+ if (key == sym_indent) { state_write_value(data, &state->indent, string_config(val)); }
1813
+ else if (key == sym_space) { state_write_value(data, &state->space, string_config(val)); }
1814
+ else if (key == sym_space_before) { state_write_value(data, &state->space_before, string_config(val)); }
1815
+ else if (key == sym_object_nl) { state_write_value(data, &state->object_nl, string_config(val)); }
1816
+ else if (key == sym_array_nl) { state_write_value(data, &state->array_nl, string_config(val)); }
1621
1817
  else if (key == sym_max_nesting) { state->max_nesting = long_config(val); }
1622
1818
  else if (key == sym_allow_nan) { state->allow_nan = RTEST(val); }
1623
1819
  else if (key == sym_ascii_only) { state->ascii_only = RTEST(val); }
1624
- else if (key == sym_depth) { state->depth = long_config(val); }
1820
+ else if (key == sym_depth) { state->depth = depth_config(val); }
1625
1821
  else if (key == sym_buffer_initial_length) { buffer_initial_length_set(state, val); }
1626
1822
  else if (key == sym_script_safe) { state->script_safe = RTEST(val); }
1627
1823
  else if (key == sym_escape_slash) { state->script_safe = RTEST(val); }
1628
1824
  else if (key == sym_strict) { state->strict = RTEST(val); }
1629
- else if (key == sym_as_json) { state->as_json = RTEST(val) ? rb_convert_type(val, T_DATA, "Proc", "to_proc") : Qfalse; }
1825
+ else if (key == sym_allow_duplicate_key) { state->on_duplicate_key = RTEST(val) ? JSON_IGNORE : JSON_RAISE; }
1826
+ else if (key == sym_as_json) {
1827
+ VALUE proc = RTEST(val) ? rb_convert_type(val, T_DATA, "Proc", "to_proc") : Qfalse;
1828
+ state->as_json_single_arg = proc && rb_proc_arity(proc) == 1;
1829
+ state_write_value(data, &state->as_json, proc);
1830
+ }
1630
1831
  return ST_CONTINUE;
1631
1832
  }
1632
1833
 
1633
- static void configure_state(JSON_Generator_State *state, VALUE config)
1834
+ static void configure_state(JSON_Generator_State *state, VALUE vstate, VALUE config)
1634
1835
  {
1635
1836
  if (!RTEST(config)) return;
1636
1837
 
@@ -1638,45 +1839,55 @@ static void configure_state(JSON_Generator_State *state, VALUE config)
1638
1839
 
1639
1840
  if (!RHASH_SIZE(config)) return;
1640
1841
 
1842
+ struct configure_state_data data = {
1843
+ .state = state,
1844
+ .vstate = vstate
1845
+ };
1846
+
1641
1847
  // We assume in most cases few keys are set so it's faster to go over
1642
1848
  // the provided keys than to check all possible keys.
1643
- rb_hash_foreach(config, configure_state_i, (VALUE)state);
1849
+ rb_hash_foreach(config, configure_state_i, (VALUE)&data);
1644
1850
  }
1645
1851
 
1646
1852
  static VALUE cState_configure(VALUE self, VALUE opts)
1647
1853
  {
1854
+ rb_check_frozen(self);
1648
1855
  GET_STATE(self);
1649
- configure_state(state, opts);
1856
+ configure_state(state, self, opts);
1650
1857
  return self;
1651
1858
  }
1652
1859
 
1653
- static VALUE cState_m_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1860
+ static VALUE cState_m_do_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io, generator_func func)
1654
1861
  {
1655
1862
  JSON_Generator_State state = {0};
1656
1863
  state_init(&state);
1657
- configure_state(&state, opts);
1864
+ configure_state(&state, Qfalse, opts);
1658
1865
 
1659
1866
  char stack_buffer[FBUFFER_STACK_SIZE];
1660
- FBuffer buffer = {
1661
- .io = RTEST(io) ? io : Qfalse,
1662
- };
1663
- fbuffer_stack_init(&buffer, state.buffer_initial_length, stack_buffer, FBUFFER_STACK_SIZE);
1867
+ FBuffer buffer = { 0 };
1868
+ fbuffer_init(&buffer, state.buffer_initial_length, io, stack_buffer, FBUFFER_STACK_SIZE);
1664
1869
 
1665
1870
  struct generate_json_data data = {
1666
1871
  .buffer = &buffer,
1667
1872
  .vstate = Qfalse,
1668
1873
  .state = &state,
1874
+ .depth = state.depth,
1669
1875
  .obj = obj,
1670
- .func = generate_json,
1876
+ .func = func,
1671
1877
  };
1672
- rb_rescue(generate_json_try, (VALUE)&data, generate_json_rescue, (VALUE)&data);
1878
+ return rb_ensure(generate_json_try, (VALUE)&data, generate_json_ensure, (VALUE)&data);
1879
+ }
1673
1880
 
1674
- return fbuffer_finalize(&buffer);
1881
+ static VALUE cState_m_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1882
+ {
1883
+ return cState_m_do_generate(klass, obj, opts, io, generate_json);
1884
+ }
1885
+
1886
+ static VALUE cState_m_generate_no_fallback(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1887
+ {
1888
+ return cState_m_do_generate(klass, obj, opts, io, generate_json_no_fallback);
1675
1889
  }
1676
1890
 
1677
- /*
1678
- *
1679
- */
1680
1891
  void Init_generator(void)
1681
1892
  {
1682
1893
  #ifdef HAVE_RB_EXT_RACTOR_SAFE
@@ -1741,51 +1952,12 @@ void Init_generator(void)
1741
1952
  rb_define_method(cState, "buffer_initial_length", cState_buffer_initial_length, 0);
1742
1953
  rb_define_method(cState, "buffer_initial_length=", cState_buffer_initial_length_set, 1);
1743
1954
  rb_define_method(cState, "generate", cState_generate, -1);
1744
- rb_define_alias(cState, "generate_new", "generate"); // :nodoc:
1955
+ rb_define_method(cState, "_generate_no_fallback", cState_generate_no_fallback, -1);
1745
1956
 
1746
- rb_define_singleton_method(cState, "generate", cState_m_generate, 3);
1747
-
1748
- VALUE mGeneratorMethods = rb_define_module_under(mGenerator, "GeneratorMethods");
1749
-
1750
- VALUE mObject = rb_define_module_under(mGeneratorMethods, "Object");
1751
- rb_define_method(mObject, "to_json", mObject_to_json, -1);
1752
-
1753
- VALUE mHash = rb_define_module_under(mGeneratorMethods, "Hash");
1754
- rb_define_method(mHash, "to_json", mHash_to_json, -1);
1957
+ rb_define_private_method(cState, "allow_duplicate_key?", cState_allow_duplicate_key_p, 0);
1755
1958
 
1756
- VALUE mArray = rb_define_module_under(mGeneratorMethods, "Array");
1757
- rb_define_method(mArray, "to_json", mArray_to_json, -1);
1758
-
1759
- #ifdef RUBY_INTEGER_UNIFICATION
1760
- VALUE mInteger = rb_define_module_under(mGeneratorMethods, "Integer");
1761
- rb_define_method(mInteger, "to_json", mInteger_to_json, -1);
1762
- #else
1763
- VALUE mFixnum = rb_define_module_under(mGeneratorMethods, "Fixnum");
1764
- rb_define_method(mFixnum, "to_json", mFixnum_to_json, -1);
1765
-
1766
- VALUE mBignum = rb_define_module_under(mGeneratorMethods, "Bignum");
1767
- rb_define_method(mBignum, "to_json", mBignum_to_json, -1);
1768
- #endif
1769
- VALUE mFloat = rb_define_module_under(mGeneratorMethods, "Float");
1770
- rb_define_method(mFloat, "to_json", mFloat_to_json, -1);
1771
-
1772
- VALUE mString = rb_define_module_under(mGeneratorMethods, "String");
1773
- rb_define_singleton_method(mString, "included", mString_included_s, 1);
1774
- rb_define_method(mString, "to_json", mString_to_json, -1);
1775
- rb_define_method(mString, "to_json_raw", mString_to_json_raw, -1);
1776
- rb_define_method(mString, "to_json_raw_object", mString_to_json_raw_object, 0);
1777
-
1778
- mString_Extend = rb_define_module_under(mString, "Extend");
1779
- rb_define_method(mString_Extend, "json_create", mString_Extend_json_create, 1);
1780
-
1781
- VALUE mTrueClass = rb_define_module_under(mGeneratorMethods, "TrueClass");
1782
- rb_define_method(mTrueClass, "to_json", mTrueClass_to_json, -1);
1783
-
1784
- VALUE mFalseClass = rb_define_module_under(mGeneratorMethods, "FalseClass");
1785
- rb_define_method(mFalseClass, "to_json", mFalseClass_to_json, -1);
1786
-
1787
- VALUE mNilClass = rb_define_module_under(mGeneratorMethods, "NilClass");
1788
- rb_define_method(mNilClass, "to_json", mNilClass_to_json, -1);
1959
+ rb_define_singleton_method(cState, "generate", cState_m_generate, 3);
1960
+ rb_define_singleton_method(cState, "_generate_no_fallback", cState_m_generate_no_fallback, 3);
1789
1961
 
1790
1962
  rb_global_variable(&Encoding_UTF_8);
1791
1963
  Encoding_UTF_8 = rb_const_get(rb_path2class("Encoding"), rb_intern("UTF_8"));
@@ -1793,10 +1965,6 @@ void Init_generator(void)
1793
1965
  i_to_s = rb_intern("to_s");
1794
1966
  i_to_json = rb_intern("to_json");
1795
1967
  i_new = rb_intern("new");
1796
- i_pack = rb_intern("pack");
1797
- i_unpack = rb_intern("unpack");
1798
- i_create_id = rb_intern("create_id");
1799
- i_extend = rb_intern("extend");
1800
1968
  i_encode = rb_intern("encode");
1801
1969
 
1802
1970
  sym_indent = ID2SYM(rb_intern("indent"));
@@ -1813,10 +1981,13 @@ void Init_generator(void)
1813
1981
  sym_escape_slash = ID2SYM(rb_intern("escape_slash"));
1814
1982
  sym_strict = ID2SYM(rb_intern("strict"));
1815
1983
  sym_as_json = ID2SYM(rb_intern("as_json"));
1984
+ sym_allow_duplicate_key = ID2SYM(rb_intern("allow_duplicate_key"));
1816
1985
 
1817
1986
  usascii_encindex = rb_usascii_encindex();
1818
1987
  utf8_encindex = rb_utf8_encindex();
1819
1988
  binary_encindex = rb_ascii8bit_encindex();
1820
1989
 
1821
1990
  rb_require("json/ext/generator/state");
1991
+
1992
+ simd_impl = find_simd_implementation();
1822
1993
  }