json 2.11.3 → 2.21.2

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,12 +1,20 @@
1
- #include "ruby.h"
1
+ #include "../json.h"
2
2
  #include "../fbuffer/fbuffer.h"
3
3
  #include "../vendor/fpconv.c"
4
4
 
5
5
  #include <math.h>
6
6
  #include <ctype.h>
7
7
 
8
+ #include "../simd/simd.h"
9
+
8
10
  /* ruby api and some helpers */
9
11
 
12
+ enum duplicate_key_action {
13
+ JSON_DEPRECATED = 0,
14
+ JSON_IGNORE,
15
+ JSON_RAISE,
16
+ };
17
+
10
18
  typedef struct JSON_Generator_StateStruct {
11
19
  VALUE indent;
12
20
  VALUE space;
@@ -19,21 +27,21 @@ typedef struct JSON_Generator_StateStruct {
19
27
  long depth;
20
28
  long buffer_initial_length;
21
29
 
30
+ enum duplicate_key_action on_duplicate_key;
31
+
32
+ bool as_json_single_arg;
22
33
  bool allow_nan;
23
34
  bool ascii_only;
24
35
  bool script_safe;
25
36
  bool strict;
37
+ VALUE sort_keys;
26
38
  } JSON_Generator_State;
27
39
 
28
- #ifndef RB_UNLIKELY
29
- #define RB_UNLIKELY(cond) (cond)
30
- #endif
31
-
32
- static VALUE mJSON, cState, cFragment, mString_Extend, eGeneratorError, eNestingError, Encoding_UTF_8;
40
+ static VALUE mJSON, cState, cFragment, eGeneratorError, eNestingError, Encoding_UTF_8, default_sort_keys_proc;
33
41
 
34
- static ID i_to_s, i_to_json, i_new, i_pack, i_unpack, i_create_id, i_extend, i_encode;
35
- static VALUE sym_indent, sym_space, sym_space_before, sym_object_nl, sym_array_nl, sym_max_nesting, sym_allow_nan,
36
- sym_ascii_only, sym_depth, sym_buffer_initial_length, sym_script_safe, sym_escape_slash, sym_strict, sym_as_json;
42
+ static ID i_to_s, i_to_json, i_new, i_encode;
43
+ 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,
44
+ sym_ascii_only, sym_depth, sym_buffer_initial_length, sym_script_safe, sym_escape_slash, sym_strict, sym_as_json, sym_sort_keys;
37
45
 
38
46
 
39
47
  #define GET_STATE_TO(self, state) \
@@ -53,8 +61,11 @@ struct generate_json_data {
53
61
  JSON_Generator_State *state;
54
62
  VALUE obj;
55
63
  generator_func func;
64
+ long depth;
56
65
  };
57
66
 
67
+ static SIMD_Implementation simd_impl;
68
+
58
69
  static VALUE cState_from_state_s(VALUE self, VALUE opts);
59
70
  static VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func, VALUE io);
60
71
  static void generate_json(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
@@ -64,9 +75,6 @@ static void generate_json_string(FBuffer *buffer, struct generate_json_data *dat
64
75
  static void generate_json_null(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
65
76
  static void generate_json_false(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
66
77
  static void generate_json_true(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
67
- #ifdef RUBY_INTEGER_UNIFICATION
68
- static void generate_json_integer(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
69
- #endif
70
78
  static void generate_json_fixnum(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
71
79
  static void generate_json_bignum(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
72
80
  static void generate_json_float(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
@@ -74,23 +82,18 @@ static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *d
74
82
 
75
83
  static int usascii_encindex, utf8_encindex, binary_encindex;
76
84
 
77
- #ifdef RBIMPL_ATTR_NORETURN
78
- RBIMPL_ATTR_NORETURN()
79
- #endif
80
- static void raise_generator_error_str(VALUE invalid_object, VALUE str)
85
+ NORETURN(static void) raise_generator_error_str(VALUE invalid_object, VALUE str)
81
86
  {
87
+ rb_enc_associate_index(str, utf8_encindex);
82
88
  VALUE exc = rb_exc_new_str(eGeneratorError, str);
83
89
  rb_ivar_set(exc, rb_intern("@invalid_object"), invalid_object);
84
90
  rb_exc_raise(exc);
85
91
  }
86
92
 
87
- #ifdef RBIMPL_ATTR_NORETURN
88
- RBIMPL_ATTR_NORETURN()
89
- #endif
90
93
  #ifdef RBIMPL_ATTR_FORMAT
91
94
  RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 3)
92
95
  #endif
93
- static void raise_generator_error(VALUE invalid_object, const char *fmt, ...)
96
+ NORETURN(static void) raise_generator_error(VALUE invalid_object, const char *fmt, ...)
94
97
  {
95
98
  va_list args;
96
99
  va_start(args, fmt);
@@ -109,12 +112,34 @@ typedef struct _search_state {
109
112
  const char *end;
110
113
  const char *cursor;
111
114
  FBuffer *buffer;
115
+
116
+ #ifdef HAVE_SIMD
117
+ const char *chunk_base;
118
+ const char *chunk_end;
119
+ bool has_matches;
120
+
121
+ #if defined(HAVE_SIMD_NEON)
122
+ uint64_t matches_mask;
123
+ #elif defined(HAVE_SIMD_SSE2)
124
+ int matches_mask;
125
+ #else
126
+ #error "Unknown SIMD Implementation."
127
+ #endif /* HAVE_SIMD_NEON */
128
+ #endif /* HAVE_SIMD */
112
129
  } search_state;
113
130
 
114
- static inline void search_flush(search_state *search)
115
- {
116
- fbuffer_append(search->buffer, search->cursor, search->ptr - search->cursor);
117
- search->cursor = search->ptr;
131
+ ALWAYS_INLINE(static) void search_flush(search_state *search)
132
+ {
133
+ // Do not remove this conditional without profiling, specifically escape-heavy text.
134
+ // escape_UTF8_char_basic will advance search->ptr and search->cursor (effectively a search_flush).
135
+ // For back-to-back characters that need to be escaped, specifically for the SIMD code paths, this method
136
+ // will be called just before calling escape_UTF8_char_basic. There will be no characters to append for the
137
+ // consecutive characters that need to be escaped. While the fbuffer_append is a no-op if
138
+ // nothing needs to be flushed, we can save a few memory references with this conditional.
139
+ if (search->ptr > search->cursor) {
140
+ fbuffer_append(search->buffer, search->cursor, search->ptr - search->cursor);
141
+ search->cursor = search->ptr;
142
+ }
118
143
  }
119
144
 
120
145
  static const unsigned char escape_table_basic[256] = {
@@ -144,7 +169,8 @@ static inline unsigned char search_escape_basic(search_state *search)
144
169
  return 0;
145
170
  }
146
171
 
147
- static inline void escape_UTF8_char_basic(search_state *search) {
172
+ ALWAYS_INLINE(static) void escape_UTF8_char_basic(search_state *search)
173
+ {
148
174
  const unsigned char ch = (unsigned char)*search->ptr;
149
175
  switch (ch) {
150
176
  case '"': fbuffer_append(search->buffer, "\\\"", 2); break;
@@ -184,14 +210,43 @@ static inline void escape_UTF8_char_basic(search_state *search) {
184
210
  * Everything else (should be UTF-8) is just passed through and
185
211
  * appended to the result.
186
212
  */
213
+
214
+
215
+ #if defined(HAVE_SIMD_NEON)
216
+ static inline unsigned char search_escape_basic_neon(search_state *search);
217
+ #elif defined(HAVE_SIMD_SSE2)
218
+ static inline unsigned char search_escape_basic_sse2(search_state *search);
219
+ #endif
220
+
221
+ static inline unsigned char search_escape_basic(search_state *search);
222
+
187
223
  static inline void convert_UTF8_to_JSON(search_state *search)
188
224
  {
225
+ #ifdef HAVE_SIMD
226
+ #if defined(HAVE_SIMD_NEON)
227
+ while (search_escape_basic_neon(search)) {
228
+ escape_UTF8_char_basic(search);
229
+ }
230
+ #elif defined(HAVE_SIMD_SSE2)
231
+ if (simd_impl == SIMD_SSE2) {
232
+ while (search_escape_basic_sse2(search)) {
233
+ escape_UTF8_char_basic(search);
234
+ }
235
+ return;
236
+ }
189
237
  while (search_escape_basic(search)) {
190
238
  escape_UTF8_char_basic(search);
191
239
  }
240
+ #endif
241
+ #else
242
+ while (search_escape_basic(search)) {
243
+ escape_UTF8_char_basic(search);
244
+ }
245
+ #endif /* HAVE_SIMD */
192
246
  }
193
247
 
194
- static inline void escape_UTF8_char(search_state *search, unsigned char ch_len) {
248
+ static inline void escape_UTF8_char(search_state *search, unsigned char ch_len)
249
+ {
195
250
  const unsigned char ch = (unsigned char)*search->ptr;
196
251
  switch (ch_len) {
197
252
  case 1: {
@@ -227,6 +282,236 @@ static inline void escape_UTF8_char(search_state *search, unsigned char ch_len)
227
282
  search->cursor = (search->ptr += ch_len);
228
283
  }
229
284
 
285
+ #ifdef HAVE_SIMD
286
+
287
+ ALWAYS_INLINE(static) char *copy_remaining_bytes(search_state *search, unsigned long vec_len, unsigned long len)
288
+ {
289
+ RBIMPL_ASSERT_OR_ASSUME(len < vec_len);
290
+
291
+ // Flush the buffer so everything up until the last 'len' characters are unflushed.
292
+ search_flush(search);
293
+
294
+ FBuffer *buf = search->buffer;
295
+ fbuffer_inc_capa(buf, vec_len);
296
+
297
+ char *s = (buf->ptr + buf->len);
298
+
299
+ // Pad the buffer with dummy characters that won't need escaping.
300
+ // This seem wasteful at first sight, but memset of vector length is very fast.
301
+ // This is a space as it can be directly represented as an immediate on AArch64.
302
+ memset(s, ' ', vec_len);
303
+
304
+ // Optimistically copy the remaining 'len' characters to the output FBuffer. If there are no characters
305
+ // to escape, then everything ends up in the correct spot. Otherwise it was convenient temporary storage.
306
+ if (vec_len == 16) {
307
+ RBIMPL_ASSERT_OR_ASSUME(len >= SIMD_MINIMUM_THRESHOLD);
308
+ json_fast_memcpy16(s, search->ptr, len);
309
+ } else {
310
+ MEMCPY(s, search->ptr, char, len);
311
+ }
312
+
313
+ return s;
314
+ }
315
+
316
+ #ifdef HAVE_SIMD_NEON
317
+
318
+ ALWAYS_INLINE(static) unsigned char neon_next_match(search_state *search)
319
+ {
320
+ uint64_t mask = search->matches_mask;
321
+ uint32_t index = trailing_zeros64(mask) >> 2;
322
+
323
+ // It is assumed escape_UTF8_char_basic will only ever increase search->ptr by at most one character.
324
+ // If we want to use a similar approach for full escaping we'll need to ensure:
325
+ // search->chunk_base + index >= search->ptr
326
+ // However, since we know escape_UTF8_char_basic only increases search->ptr by one, if the next match
327
+ // is one byte after the previous match then:
328
+ // search->chunk_base + index == search->ptr
329
+ search->ptr = search->chunk_base + index;
330
+ mask &= mask - 1;
331
+ search->matches_mask = mask;
332
+ search_flush(search);
333
+ return 1;
334
+ }
335
+
336
+ static inline unsigned char search_escape_basic_neon(search_state *search)
337
+ {
338
+ if (RB_UNLIKELY(search->has_matches)) {
339
+ // There are more matches if search->matches_mask > 0.
340
+ if (search->matches_mask > 0) {
341
+ return neon_next_match(search);
342
+ } else {
343
+ // neon_next_match will only advance search->ptr up to the last matching character.
344
+ // Skip over any characters in the last chunk that occur after the last match.
345
+ search->has_matches = false;
346
+ search->ptr = search->chunk_end;
347
+ }
348
+ }
349
+
350
+ /*
351
+ * The code below implements an SIMD-based algorithm to determine if N bytes at a time
352
+ * need to be escaped.
353
+ *
354
+ * Assume the ptr = "Te\sting!" (the double quotes are included in the string)
355
+ *
356
+ * The explanation will be limited to the first 8 bytes of the string for simplicity. However
357
+ * the vector insructions may work on larger vectors.
358
+ *
359
+ * First, we load three constants 'lower_bound', 'backslash' and 'dblquote" in vector registers.
360
+ *
361
+ * lower_bound: [20 20 20 20 20 20 20 20]
362
+ * backslash: [5C 5C 5C 5C 5C 5C 5C 5C]
363
+ * dblquote: [22 22 22 22 22 22 22 22]
364
+ *
365
+ * Next we load the first chunk of the ptr:
366
+ * [22 54 65 5C 73 74 69 6E] (" T e \ s t i n)
367
+ *
368
+ * First we check if any byte in chunk is less than 32 (0x20). This returns the following vector
369
+ * as no bytes are less than 32 (0x20):
370
+ * [0 0 0 0 0 0 0 0]
371
+ *
372
+ * Next, we check if any byte in chunk is equal to a backslash:
373
+ * [0 0 0 FF 0 0 0 0]
374
+ *
375
+ * Finally we check if any byte in chunk is equal to a double quote:
376
+ * [FF 0 0 0 0 0 0 0]
377
+ *
378
+ * Now we have three vectors where each byte indicates if the corresponding byte in chunk
379
+ * needs to be escaped. We combine these vectors with a series of logical OR instructions.
380
+ * This is the needs_escape vector and it is equal to:
381
+ * [FF 0 0 FF 0 0 0 0]
382
+ *
383
+ * Next we compute the bitwise AND between each byte and 0x1 and compute the horizontal sum of
384
+ * the values in the vector. This computes how many bytes need to be escaped within this chunk.
385
+ *
386
+ * Finally we compute a mask that indicates which bytes need to be escaped. If the mask is 0 then,
387
+ * no bytes need to be escaped and we can continue to the next chunk. If the mask is not 0 then we
388
+ * have at least one byte that needs to be escaped.
389
+ */
390
+
391
+ if (string_scan_simd_neon(&search->ptr, search->end, &search->matches_mask)) {
392
+ search->has_matches = true;
393
+ search->chunk_base = search->ptr;
394
+ search->chunk_end = search->ptr + sizeof(uint8x16_t);
395
+ return neon_next_match(search);
396
+ }
397
+
398
+ // There are fewer than 16 bytes left.
399
+ unsigned long remaining = (search->end - search->ptr);
400
+ if (remaining >= SIMD_MINIMUM_THRESHOLD) {
401
+ char *s = copy_remaining_bytes(search, sizeof(uint8x16_t), remaining);
402
+
403
+ uint64_t mask = compute_chunk_mask_neon(s);
404
+
405
+ if (!mask) {
406
+ // Nothing to escape, ensure search_flush doesn't do anything by setting
407
+ // search->cursor to search->ptr.
408
+ fbuffer_consumed(search->buffer, remaining);
409
+ search->ptr = search->end;
410
+ search->cursor = search->end;
411
+ return 0;
412
+ }
413
+
414
+ search->matches_mask = mask;
415
+ search->has_matches = true;
416
+ search->chunk_end = search->end;
417
+ search->chunk_base = search->ptr;
418
+ return neon_next_match(search);
419
+ }
420
+
421
+ if (search->ptr < search->end) {
422
+ return search_escape_basic(search);
423
+ }
424
+
425
+ search_flush(search);
426
+ return 0;
427
+ }
428
+ #endif /* HAVE_SIMD_NEON */
429
+
430
+ #ifdef HAVE_SIMD_SSE2
431
+
432
+ ALWAYS_INLINE(static) unsigned char sse2_next_match(search_state *search)
433
+ {
434
+ int mask = search->matches_mask;
435
+ int index = trailing_zeros(mask);
436
+
437
+ // It is assumed escape_UTF8_char_basic will only ever increase search->ptr by at most one character.
438
+ // If we want to use a similar approach for full escaping we'll need to ensure:
439
+ // search->chunk_base + index >= search->ptr
440
+ // However, since we know escape_UTF8_char_basic only increases search->ptr by one, if the next match
441
+ // is one byte after the previous match then:
442
+ // search->chunk_base + index == search->ptr
443
+ search->ptr = search->chunk_base + index;
444
+ mask &= mask - 1;
445
+ search->matches_mask = mask;
446
+ search_flush(search);
447
+ return 1;
448
+ }
449
+
450
+ #if defined(__clang__) || defined(__GNUC__)
451
+ #define TARGET_SSE2 __attribute__((target("sse2")))
452
+ #else
453
+ #define TARGET_SSE2
454
+ #endif
455
+
456
+ ALWAYS_INLINE(static) TARGET_SSE2 unsigned char search_escape_basic_sse2(search_state *search)
457
+ {
458
+ if (RB_UNLIKELY(search->has_matches)) {
459
+ // There are more matches if search->matches_mask > 0.
460
+ if (search->matches_mask > 0) {
461
+ return sse2_next_match(search);
462
+ } else {
463
+ // sse2_next_match will only advance search->ptr up to the last matching character.
464
+ // Skip over any characters in the last chunk that occur after the last match.
465
+ search->has_matches = false;
466
+ if (RB_UNLIKELY(search->chunk_base + sizeof(__m128i) >= search->end)) {
467
+ search->ptr = search->end;
468
+ } else {
469
+ search->ptr = search->chunk_base + sizeof(__m128i);
470
+ }
471
+ }
472
+ }
473
+
474
+ if (string_scan_simd_sse2(&search->ptr, search->end, &search->matches_mask)) {
475
+ search->has_matches = true;
476
+ search->chunk_base = search->ptr;
477
+ search->chunk_end = search->ptr + sizeof(__m128i);
478
+ return sse2_next_match(search);
479
+ }
480
+
481
+ // There are fewer than 16 bytes left.
482
+ unsigned long remaining = (search->end - search->ptr);
483
+ if (remaining >= SIMD_MINIMUM_THRESHOLD) {
484
+ char *s = copy_remaining_bytes(search, sizeof(__m128i), remaining);
485
+
486
+ int needs_escape_mask = compute_chunk_mask_sse2(s);
487
+
488
+ if (needs_escape_mask == 0) {
489
+ // Nothing to escape, ensure search_flush doesn't do anything by setting
490
+ // search->cursor to search->ptr.
491
+ fbuffer_consumed(search->buffer, remaining);
492
+ search->ptr = search->end;
493
+ search->cursor = search->end;
494
+ return 0;
495
+ }
496
+
497
+ search->has_matches = true;
498
+ search->matches_mask = needs_escape_mask;
499
+ search->chunk_base = search->ptr;
500
+ return sse2_next_match(search);
501
+ }
502
+
503
+ if (search->ptr < search->end) {
504
+ return search_escape_basic(search);
505
+ }
506
+
507
+ search_flush(search);
508
+ return 0;
509
+ }
510
+
511
+ #endif /* HAVE_SIMD_SSE2 */
512
+
513
+ #endif /* HAVE_SIMD */
514
+
230
515
  static const unsigned char script_safe_escape_table[256] = {
231
516
  // ASCII Control Characters
232
517
  9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
@@ -330,7 +615,8 @@ static inline unsigned char search_ascii_only_escape(search_state *search, const
330
615
  return 0;
331
616
  }
332
617
 
333
- static inline void full_escape_UTF8_char(search_state *search, unsigned char ch_len) {
618
+ static inline void full_escape_UTF8_char(search_state *search, unsigned char ch_len)
619
+ {
334
620
  const unsigned char ch = (unsigned char)*search->ptr;
335
621
  switch (ch_len) {
336
622
  case 1: {
@@ -360,7 +646,7 @@ static inline void full_escape_UTF8_char(search_state *search, unsigned char ch_
360
646
 
361
647
  uint32_t wchar = 0;
362
648
 
363
- switch(ch_len) {
649
+ switch (ch_len) {
364
650
  case 2:
365
651
  wchar = ch & 0x1F;
366
652
  break;
@@ -415,380 +701,267 @@ static void convert_UTF8_to_ASCII_only_JSON(search_state *search, const unsigned
415
701
  }
416
702
  }
417
703
 
418
- /*
419
- * Document-module: JSON::Ext::Generator
420
- *
421
- * This is the JSON generator implemented as a C extension. It can be
422
- * configured to be used by setting
423
- *
424
- * JSON.generator = JSON::Ext::Generator
425
- *
426
- * with the method generator= in JSON.
427
- *
428
- */
429
-
430
- /* Explanation of the following: that's the only way to not pollute
431
- * standard library's docs with GeneratorMethods::<ClassName> which
432
- * are uninformative and take a large place in a list of classes
433
- */
434
-
435
- /*
436
- * Document-module: JSON::Ext::Generator::GeneratorMethods
437
- * :nodoc:
438
- */
439
-
440
- /*
441
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Array
442
- * :nodoc:
443
- */
444
-
445
- /*
446
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Bignum
447
- * :nodoc:
448
- */
449
-
450
- /*
451
- * Document-module: JSON::Ext::Generator::GeneratorMethods::FalseClass
452
- * :nodoc:
453
- */
454
-
455
- /*
456
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Fixnum
457
- * :nodoc:
458
- */
459
-
460
- /*
461
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Float
462
- * :nodoc:
463
- */
464
-
465
- /*
466
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Hash
467
- * :nodoc:
468
- */
469
-
470
- /*
471
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Integer
472
- * :nodoc:
473
- */
474
-
475
- /*
476
- * Document-module: JSON::Ext::Generator::GeneratorMethods::NilClass
477
- * :nodoc:
478
- */
479
-
480
- /*
481
- * Document-module: JSON::Ext::Generator::GeneratorMethods::Object
482
- * :nodoc:
483
- */
484
-
485
- /*
486
- * Document-module: JSON::Ext::Generator::GeneratorMethods::String
487
- * :nodoc:
488
- */
489
-
490
- /*
491
- * Document-module: JSON::Ext::Generator::GeneratorMethods::String::Extend
492
- * :nodoc:
493
- */
494
-
495
- /*
496
- * Document-module: JSON::Ext::Generator::GeneratorMethods::TrueClass
497
- * :nodoc:
498
- */
499
-
500
- /*
501
- * call-seq: to_json(state = nil)
502
- *
503
- * Returns a JSON string containing a JSON object, that is generated from
504
- * this Hash instance.
505
- * _state_ is a JSON::State object, that can also be used to configure the
506
- * produced JSON string output further.
507
- */
508
- static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self)
509
- {
510
- rb_check_arity(argc, 0, 1);
511
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
512
- return cState_partial_generate(Vstate, self, generate_json_object, Qfalse);
513
- }
514
-
515
- /*
516
- * call-seq: to_json(state = nil)
517
- *
518
- * Returns a JSON string containing a JSON array, that is generated from
519
- * this Array instance.
520
- * _state_ is a JSON::State object, that can also be used to configure the
521
- * produced JSON string output further.
522
- */
523
- static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self) {
524
- rb_check_arity(argc, 0, 1);
525
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
526
- return cState_partial_generate(Vstate, self, generate_json_array, Qfalse);
527
- }
528
-
529
- #ifdef RUBY_INTEGER_UNIFICATION
530
- /*
531
- * call-seq: to_json(*)
532
- *
533
- * Returns a JSON string representation for this Integer number.
534
- */
535
- static VALUE mInteger_to_json(int argc, VALUE *argv, VALUE self)
704
+ static void State_mark(void *ptr)
536
705
  {
537
- rb_check_arity(argc, 0, 1);
538
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
539
- return cState_partial_generate(Vstate, self, generate_json_integer, Qfalse);
706
+ JSON_Generator_State *state = ptr;
707
+ rb_gc_mark_movable(state->indent);
708
+ rb_gc_mark_movable(state->space);
709
+ rb_gc_mark_movable(state->space_before);
710
+ rb_gc_mark_movable(state->object_nl);
711
+ rb_gc_mark_movable(state->array_nl);
712
+ rb_gc_mark_movable(state->as_json);
713
+ rb_gc_mark_movable(state->sort_keys);
540
714
  }
541
715
 
542
- #else
543
- /*
544
- * call-seq: to_json(*)
545
- *
546
- * Returns a JSON string representation for this Integer number.
547
- */
548
- static VALUE mFixnum_to_json(int argc, VALUE *argv, VALUE self)
716
+ static void State_compact(void *ptr)
549
717
  {
550
- rb_check_arity(argc, 0, 1);
551
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
552
- return cState_partial_generate(Vstate, self, generate_json_fixnum, Qfalse);
718
+ JSON_Generator_State *state = ptr;
719
+ state->indent = rb_gc_location(state->indent);
720
+ state->space = rb_gc_location(state->space);
721
+ state->space_before = rb_gc_location(state->space_before);
722
+ state->object_nl = rb_gc_location(state->object_nl);
723
+ state->array_nl = rb_gc_location(state->array_nl);
724
+ state->as_json = rb_gc_location(state->as_json);
725
+ state->sort_keys = rb_gc_location(state->sort_keys);
553
726
  }
554
727
 
555
- /*
556
- * call-seq: to_json(*)
557
- *
558
- * Returns a JSON string representation for this Integer number.
559
- */
560
- static VALUE mBignum_to_json(int argc, VALUE *argv, VALUE self)
728
+ static size_t State_memsize(const void *ptr)
561
729
  {
562
- rb_check_arity(argc, 0, 1);
563
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
564
- return cState_partial_generate(Vstate, self, generate_json_bignum, Qfalse);
565
- }
730
+ #ifdef HAVE_RUBY_TYPED_EMBEDDABLE
731
+ return 0;
732
+ #else
733
+ return sizeof(JSON_Generator_State);
566
734
  #endif
567
-
568
- /*
569
- * call-seq: to_json(*)
570
- *
571
- * Returns a JSON string representation for this Float number.
572
- */
573
- static VALUE mFloat_to_json(int argc, VALUE *argv, VALUE self)
574
- {
575
- rb_check_arity(argc, 0, 1);
576
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
577
- return cState_partial_generate(Vstate, self, generate_json_float, Qfalse);
578
735
  }
579
736
 
580
- /*
581
- * call-seq: String.included(modul)
582
- *
583
- * Extends _modul_ with the String::Extend module.
584
- */
585
- static VALUE mString_included_s(VALUE self, VALUE modul) {
586
- VALUE result = rb_funcall(modul, i_extend, 1, mString_Extend);
587
- rb_call_super(1, &modul);
588
- return result;
589
- }
737
+ static const rb_data_type_t JSON_Generator_State_type = {
738
+ .wrap_struct_name = "JSON/Generator/State",
739
+ .function = {
740
+ .dmark = State_mark,
741
+ .dfree = RUBY_DEFAULT_FREE,
742
+ .dsize = State_memsize,
743
+ .dcompact = State_compact,
744
+ },
745
+ .flags = RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_FROZEN_SHAREABLE | RUBY_TYPED_EMBEDDABLE,
746
+ };
590
747
 
591
- /*
592
- * call-seq: to_json(*)
593
- *
594
- * This string should be encoded with UTF-8 A call to this method
595
- * returns a JSON string encoded with UTF16 big endian characters as
596
- * \u????.
597
- */
598
- static VALUE mString_to_json(int argc, VALUE *argv, VALUE self)
748
+ static void state_init(JSON_Generator_State *state)
599
749
  {
600
- rb_check_arity(argc, 0, 1);
601
- VALUE Vstate = cState_from_state_s(cState, argc == 1 ? argv[0] : Qnil);
602
- return cState_partial_generate(Vstate, self, generate_json_string, Qfalse);
750
+ state->max_nesting = 100;
751
+ state->buffer_initial_length = FBUFFER_INITIAL_LENGTH_DEFAULT;
603
752
  }
604
753
 
605
- /*
606
- * call-seq: to_json_raw_object()
607
- *
608
- * This method creates a raw object hash, that can be nested into
609
- * other data structures and will be generated as a raw string. This
610
- * method should be used, if you want to convert raw strings to JSON
611
- * instead of UTF-8 strings, e. g. binary data.
612
- */
613
- static VALUE mString_to_json_raw_object(VALUE self)
754
+ static VALUE cState_s_allocate(VALUE klass)
614
755
  {
615
- VALUE ary;
616
- VALUE result = rb_hash_new();
617
- rb_hash_aset(result, rb_funcall(mJSON, i_create_id, 0), rb_class_name(rb_obj_class(self)));
618
- ary = rb_funcall(self, i_unpack, 1, rb_str_new2("C*"));
619
- rb_hash_aset(result, rb_utf8_str_new_lit("raw"), ary);
620
- return result;
756
+ JSON_Generator_State *state;
757
+ VALUE obj = TypedData_Make_Struct(klass, JSON_Generator_State, &JSON_Generator_State_type, state);
758
+ state_init(state);
759
+ return obj;
621
760
  }
622
761
 
623
- /*
624
- * call-seq: to_json_raw(*args)
625
- *
626
- * This method creates a JSON text from the result of a call to
627
- * to_json_raw_object of this String.
628
- */
629
- static VALUE mString_to_json_raw(int argc, VALUE *argv, VALUE self)
762
+ static void vstate_spill(struct generate_json_data *data)
630
763
  {
631
- VALUE obj = mString_to_json_raw_object(self);
632
- Check_Type(obj, T_HASH);
633
- return mHash_to_json(argc, argv, obj);
764
+ VALUE vstate = cState_s_allocate(cState);
765
+ GET_STATE(vstate);
766
+ MEMCPY(state, data->state, JSON_Generator_State, 1);
767
+ data->state = state;
768
+ data->vstate = vstate;
769
+ RB_OBJ_WRITTEN(vstate, Qundef, state->indent);
770
+ RB_OBJ_WRITTEN(vstate, Qundef, state->space);
771
+ RB_OBJ_WRITTEN(vstate, Qundef, state->space_before);
772
+ RB_OBJ_WRITTEN(vstate, Qundef, state->object_nl);
773
+ RB_OBJ_WRITTEN(vstate, Qundef, state->array_nl);
774
+ RB_OBJ_WRITTEN(vstate, Qundef, state->as_json);
775
+ RB_OBJ_WRITTEN(vstate, Qundef, state->sort_keys);
634
776
  }
635
777
 
636
- /*
637
- * call-seq: json_create(o)
638
- *
639
- * Raw Strings are JSON Objects (the raw bytes are stored in an array for the
640
- * key "raw"). The Ruby String can be created by this module method.
641
- */
642
- static VALUE mString_Extend_json_create(VALUE self, VALUE o)
778
+ static inline VALUE json_call_to_json(struct generate_json_data *data, VALUE obj)
643
779
  {
644
- VALUE ary;
645
- Check_Type(o, T_HASH);
646
- ary = rb_hash_aref(o, rb_str_new2("raw"));
647
- return rb_funcall(ary, i_pack, 1, rb_str_new2("C*"));
780
+ if (RB_UNLIKELY(!data->vstate)) {
781
+ vstate_spill(data);
782
+ }
783
+ GET_STATE(data->vstate);
784
+ state->depth = data->depth;
785
+ VALUE tmp = rb_funcall(obj, i_to_json, 1, data->vstate);
786
+ // no need to restore state->depth, vstate is just a temporary State
787
+ return tmp;
648
788
  }
649
789
 
650
- /*
651
- * call-seq: to_json(*)
652
- *
653
- * Returns a JSON string for true: 'true'.
654
- */
655
- static VALUE mTrueClass_to_json(int argc, VALUE *argv, VALUE self)
790
+ static VALUE
791
+ json_call_as_json(JSON_Generator_State *state, VALUE object, VALUE is_key)
656
792
  {
657
- rb_check_arity(argc, 0, 1);
658
- return rb_utf8_str_new("true", 4);
793
+ VALUE proc_args[2] = {object, is_key};
794
+ return rb_proc_call_with_block(state->as_json, 2, proc_args, Qnil);
659
795
  }
660
796
 
661
- /*
662
- * call-seq: to_json(*)
663
- *
664
- * Returns a JSON string for false: 'false'.
665
- */
666
- static VALUE mFalseClass_to_json(int argc, VALUE *argv, VALUE self)
797
+ static VALUE
798
+ convert_string_subclass(VALUE key)
667
799
  {
668
- rb_check_arity(argc, 0, 1);
669
- return rb_utf8_str_new("false", 5);
800
+ VALUE key_to_s = rb_funcall(key, i_to_s, 0);
801
+
802
+ if (RB_UNLIKELY(!RB_TYPE_P(key_to_s, T_STRING))) {
803
+ VALUE cname = rb_obj_class(key);
804
+ rb_raise(rb_eTypeError,
805
+ "can't convert %"PRIsVALUE" to %s (%"PRIsVALUE"#%s gives %"PRIsVALUE")",
806
+ cname, "String", cname, "to_s", rb_obj_class(key_to_s));
807
+ }
808
+
809
+ return key_to_s;
670
810
  }
671
811
 
672
- /*
673
- * call-seq: to_json(*)
674
- *
675
- * Returns a JSON string for nil: 'null'.
676
- */
677
- static VALUE mNilClass_to_json(int argc, VALUE *argv, VALUE self)
812
+ static bool enc_utf8_compatible_p(int enc_idx)
678
813
  {
679
- rb_check_arity(argc, 0, 1);
680
- return rb_utf8_str_new("null", 4);
814
+ if (enc_idx == usascii_encindex) return true;
815
+ if (enc_idx == utf8_encindex) return true;
816
+ return false;
681
817
  }
682
818
 
683
- /*
684
- * call-seq: to_json(*)
685
- *
686
- * Converts this object to a string (calling #to_s), converts
687
- * it to a JSON string, and returns the result. This is a fallback, if no
688
- * special method #to_json was defined for some object.
689
- */
690
- static VALUE mObject_to_json(int argc, VALUE *argv, VALUE self)
819
+ static VALUE encode_json_string_try(VALUE str)
691
820
  {
692
- VALUE state;
693
- VALUE string = rb_funcall(self, i_to_s, 0);
694
- rb_scan_args(argc, argv, "01", &state);
695
- Check_Type(string, T_STRING);
696
- state = cState_from_state_s(cState, state);
697
- return cState_partial_generate(state, string, generate_json_string, Qfalse);
821
+ return rb_funcall(str, i_encode, 1, Encoding_UTF_8);
698
822
  }
699
823
 
700
- static void State_mark(void *ptr)
824
+ static VALUE encode_json_string_rescue(VALUE str, VALUE exception)
701
825
  {
702
- JSON_Generator_State *state = ptr;
703
- rb_gc_mark_movable(state->indent);
704
- rb_gc_mark_movable(state->space);
705
- rb_gc_mark_movable(state->space_before);
706
- rb_gc_mark_movable(state->object_nl);
707
- rb_gc_mark_movable(state->array_nl);
708
- rb_gc_mark_movable(state->as_json);
826
+ raise_generator_error_str(str, rb_funcall(exception, rb_intern("message"), 0));
827
+ return Qundef;
709
828
  }
710
829
 
711
- static void State_compact(void *ptr)
712
- {
713
- JSON_Generator_State *state = ptr;
714
- state->indent = rb_gc_location(state->indent);
715
- state->space = rb_gc_location(state->space);
716
- state->space_before = rb_gc_location(state->space_before);
717
- state->object_nl = rb_gc_location(state->object_nl);
718
- state->array_nl = rb_gc_location(state->array_nl);
719
- state->as_json = rb_gc_location(state->as_json);
830
+ static inline int json_str_coderange(VALUE str) {
831
+ int coderange = RB_ENC_CODERANGE(str);
832
+ if (coderange == RUBY_ENC_CODERANGE_UNKNOWN) {
833
+ coderange = rb_enc_str_coderange(str);
834
+ }
835
+ return coderange;
720
836
  }
721
837
 
722
- static void State_free(void *ptr)
838
+ static inline bool valid_json_string_p(VALUE str)
723
839
  {
724
- JSON_Generator_State *state = ptr;
725
- ruby_xfree(state);
840
+ int coderange = json_str_coderange(str);
841
+
842
+ if (RB_LIKELY(coderange == ENC_CODERANGE_7BIT)) {
843
+ return true;
844
+ }
845
+
846
+ if (RB_LIKELY(coderange == ENC_CODERANGE_VALID)) {
847
+ return enc_utf8_compatible_p(RB_ENCODING_GET_INLINED(str));
848
+ }
849
+
850
+ return false;
726
851
  }
727
852
 
728
- static size_t State_memsize(const void *ptr)
853
+ NOINLINE(static) VALUE convert_invalid_encoding(struct generate_json_data *data, VALUE str, bool as_json_called, bool is_key)
729
854
  {
730
- return sizeof(JSON_Generator_State);
731
- }
855
+ if (!as_json_called && data->state->strict && RTEST(data->state->as_json)) {
856
+ VALUE coerced_str = json_call_as_json(data->state, str, Qfalse);
857
+ if (coerced_str != str) {
858
+ if (RB_TYPE_P(coerced_str, T_STRING)) {
859
+ if (!valid_json_string_p(coerced_str)) {
860
+ raise_generator_error(str, "source sequence is illegal/malformed utf-8");
861
+ }
862
+ } else {
863
+ // as_json could return another type than T_STRING
864
+ if (is_key) {
865
+ raise_generator_error(coerced_str, "%"PRIsVALUE" not allowed as object key in JSON", CLASS_OF(coerced_str));
866
+ }
867
+ }
732
868
 
733
- #ifndef HAVE_RB_EXT_RACTOR_SAFE
734
- # undef RUBY_TYPED_FROZEN_SHAREABLE
735
- # define RUBY_TYPED_FROZEN_SHAREABLE 0
736
- #endif
869
+ return coerced_str;
870
+ }
871
+ }
737
872
 
738
- static const rb_data_type_t JSON_Generator_State_type = {
739
- "JSON/Generator/State",
740
- {
741
- .dmark = State_mark,
742
- .dfree = State_free,
743
- .dsize = State_memsize,
744
- .dcompact = State_compact,
745
- },
746
- 0, 0,
747
- RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE,
748
- };
873
+ if (RB_ENCODING_GET_INLINED(str) == binary_encindex) {
874
+ VALUE utf8_string = rb_enc_associate_index(rb_str_dup(str), utf8_encindex);
875
+ switch (rb_enc_str_coderange(utf8_string)) {
876
+ case ENC_CODERANGE_7BIT:
877
+ return utf8_string;
878
+ case ENC_CODERANGE_VALID:
879
+ // For historical reason, we silently reinterpret binary strings as UTF-8 if it would work.
880
+ // TODO: Raise in 3.0.0
881
+ rb_warn("JSON.generate: UTF-8 string passed as BINARY, this will raise an encoding error in json 3.0");
882
+ return utf8_string;
883
+ break;
884
+ }
885
+ }
749
886
 
750
- static void state_init(JSON_Generator_State *state)
751
- {
752
- state->max_nesting = 100;
753
- state->buffer_initial_length = FBUFFER_INITIAL_LENGTH_DEFAULT;
887
+ return rb_rescue(encode_json_string_try, str, encode_json_string_rescue, str);
754
888
  }
755
889
 
756
- static VALUE cState_s_allocate(VALUE klass)
890
+ ALWAYS_INLINE(static) VALUE ensure_valid_encoding(struct generate_json_data *data, VALUE str, bool as_json_called, bool is_key)
757
891
  {
758
- JSON_Generator_State *state;
759
- VALUE obj = TypedData_Make_Struct(klass, JSON_Generator_State, &JSON_Generator_State_type, state);
760
- state_init(state);
761
- return obj;
892
+ if (RB_LIKELY(valid_json_string_p(str))) {
893
+ return str;
894
+ }
895
+ else {
896
+ return convert_invalid_encoding(data, str, as_json_called, is_key);
897
+ }
762
898
  }
763
899
 
764
- static void vstate_spill(struct generate_json_data *data)
900
+ static void raw_generate_json_string(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
765
901
  {
766
- VALUE vstate = cState_s_allocate(cState);
767
- GET_STATE(vstate);
768
- MEMCPY(state, data->state, JSON_Generator_State, 1);
769
- data->state = state;
770
- data->vstate = vstate;
771
- RB_OBJ_WRITTEN(vstate, Qundef, state->indent);
772
- RB_OBJ_WRITTEN(vstate, Qundef, state->space);
773
- RB_OBJ_WRITTEN(vstate, Qundef, state->space_before);
774
- RB_OBJ_WRITTEN(vstate, Qundef, state->object_nl);
775
- RB_OBJ_WRITTEN(vstate, Qundef, state->array_nl);
776
- RB_OBJ_WRITTEN(vstate, Qundef, state->as_json);
902
+ fbuffer_append_char(buffer, '"');
903
+
904
+ long len;
905
+ search_state search;
906
+ search.buffer = buffer;
907
+ RSTRING_GETMEM(obj, search.ptr, len);
908
+ search.cursor = search.ptr;
909
+ search.end = search.ptr + len;
910
+
911
+ #ifdef HAVE_SIMD
912
+ search.matches_mask = 0;
913
+ search.has_matches = false;
914
+ search.chunk_base = NULL;
915
+ search.chunk_end = NULL;
916
+ #endif /* HAVE_SIMD */
917
+
918
+ switch (json_str_coderange(obj)) {
919
+ case ENC_CODERANGE_7BIT:
920
+ case ENC_CODERANGE_VALID:
921
+ if (RB_UNLIKELY(data->state->ascii_only)) {
922
+ convert_UTF8_to_ASCII_only_JSON(&search, data->state->script_safe ? script_safe_escape_table : ascii_only_escape_table);
923
+ } else if (RB_UNLIKELY(data->state->script_safe)) {
924
+ convert_UTF8_to_script_safe_JSON(&search);
925
+ } else {
926
+ convert_UTF8_to_JSON(&search);
927
+ }
928
+ break;
929
+ default:
930
+ raise_generator_error(obj, "source sequence is illegal/malformed utf-8");
931
+ break;
932
+ }
933
+ fbuffer_append_char(buffer, '"');
777
934
  }
778
935
 
779
- static inline VALUE vstate_get(struct generate_json_data *data)
936
+ static void generate_json_string(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
780
937
  {
781
- if (RB_UNLIKELY(!data->vstate)) {
782
- vstate_spill(data);
783
- }
784
- return data->vstate;
938
+ obj = ensure_valid_encoding(data, obj, false, false);
939
+ raw_generate_json_string(buffer, data, obj);
785
940
  }
786
941
 
787
942
  struct hash_foreach_arg {
943
+ VALUE hash;
788
944
  struct generate_json_data *data;
789
- int iter;
945
+ int first_key_type;
946
+ bool first;
947
+ bool mixed_keys_encountered;
790
948
  };
791
949
 
950
+ NOINLINE(static) void
951
+ json_inspect_hash_with_mixed_keys(struct hash_foreach_arg *arg)
952
+ {
953
+ if (arg->mixed_keys_encountered) {
954
+ return;
955
+ }
956
+ arg->mixed_keys_encountered = true;
957
+
958
+ JSON_Generator_State *state = arg->data->state;
959
+ if (state->on_duplicate_key != JSON_IGNORE) {
960
+ VALUE do_raise = state->on_duplicate_key == JSON_RAISE ? Qtrue : Qfalse;
961
+ rb_funcall(mJSON, rb_intern("on_mixed_keys_hash"), 2, arg->hash, do_raise);
962
+ }
963
+ }
964
+
792
965
  static int
793
966
  json_object_i(VALUE key, VALUE val, VALUE _arg)
794
967
  {
@@ -798,38 +971,66 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
798
971
  FBuffer *buffer = data->buffer;
799
972
  JSON_Generator_State *state = data->state;
800
973
 
801
- long depth = state->depth;
802
- int j;
974
+ long depth = data->depth;
975
+ int key_type = rb_type(key);
976
+
977
+ if (arg->first) {
978
+ arg->first = false;
979
+ arg->first_key_type = key_type;
980
+ }
981
+ else {
982
+ fbuffer_append_char(buffer, ',');
983
+ }
803
984
 
804
- if (arg->iter > 0) fbuffer_append_char(buffer, ',');
805
985
  if (RB_UNLIKELY(data->state->object_nl)) {
806
986
  fbuffer_append_str(buffer, data->state->object_nl);
807
987
  }
808
988
  if (RB_UNLIKELY(data->state->indent)) {
809
- for (j = 0; j < depth; j++) {
810
- fbuffer_append_str(buffer, data->state->indent);
811
- }
989
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
812
990
  }
813
991
 
814
992
  VALUE key_to_s;
815
- switch(rb_type(key)) {
993
+ bool as_json_called = false;
994
+
995
+ start:
996
+ switch (key_type) {
816
997
  case T_STRING:
998
+ if (RB_UNLIKELY(arg->first_key_type != T_STRING)) {
999
+ json_inspect_hash_with_mixed_keys(arg);
1000
+ }
1001
+
817
1002
  if (RB_LIKELY(RBASIC_CLASS(key) == rb_cString)) {
818
1003
  key_to_s = key;
819
1004
  } else {
820
- key_to_s = rb_funcall(key, i_to_s, 0);
1005
+ key_to_s = convert_string_subclass(key);
821
1006
  }
822
1007
  break;
823
1008
  case T_SYMBOL:
1009
+ if (RB_UNLIKELY(arg->first_key_type != T_SYMBOL)) {
1010
+ json_inspect_hash_with_mixed_keys(arg);
1011
+ }
1012
+
824
1013
  key_to_s = rb_sym2str(key);
825
1014
  break;
826
1015
  default:
1016
+ if (data->state->strict) {
1017
+ if (RTEST(data->state->as_json) && !as_json_called) {
1018
+ key = json_call_as_json(data->state, key, Qtrue);
1019
+ key_type = rb_type(key);
1020
+ as_json_called = true;
1021
+ goto start;
1022
+ } else {
1023
+ raise_generator_error(key, "%"PRIsVALUE" not allowed as object key in JSON", CLASS_OF(key));
1024
+ }
1025
+ }
827
1026
  key_to_s = rb_convert_type(key, T_STRING, "String", "to_s");
828
1027
  break;
829
1028
  }
830
1029
 
1030
+ key_to_s = ensure_valid_encoding(data, key_to_s, as_json_called, true);
1031
+
831
1032
  if (RB_LIKELY(RBASIC_CLASS(key_to_s) == rb_cString)) {
832
- generate_json_string(buffer, data, key_to_s);
1033
+ raw_generate_json_string(buffer, data, key_to_s);
833
1034
  } else {
834
1035
  generate_json(buffer, data, key_to_s);
835
1036
  }
@@ -838,46 +1039,48 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
838
1039
  if (RB_UNLIKELY(state->space)) fbuffer_append_str(buffer, data->state->space);
839
1040
  generate_json(buffer, data, val);
840
1041
 
841
- arg->iter++;
842
1042
  return ST_CONTINUE;
843
1043
  }
844
1044
 
845
1045
  static inline long increase_depth(struct generate_json_data *data)
846
1046
  {
847
1047
  JSON_Generator_State *state = data->state;
848
- long depth = ++state->depth;
1048
+ long depth = ++data->depth;
849
1049
  if (RB_UNLIKELY(depth > state->max_nesting && state->max_nesting)) {
850
- rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
1050
+ rb_raise(eNestingError, "nesting of %ld is too deep. Did you try to serialize objects with circular references?", --data->depth);
851
1051
  }
852
1052
  return depth;
853
1053
  }
854
1054
 
855
1055
  static void generate_json_object(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
856
1056
  {
857
- int j;
1057
+ if (RB_UNLIKELY(data->state->sort_keys)) {
1058
+ obj = rb_proc_call_with_block(data->state->sort_keys, 1, &obj, Qnil);
1059
+ Check_Type(obj, T_HASH);
1060
+ }
1061
+
858
1062
  long depth = increase_depth(data);
859
1063
 
860
1064
  if (RHASH_SIZE(obj) == 0) {
861
1065
  fbuffer_append(buffer, "{}", 2);
862
- --data->state->depth;
1066
+ --data->depth;
863
1067
  return;
864
1068
  }
865
1069
 
866
1070
  fbuffer_append_char(buffer, '{');
867
1071
 
868
1072
  struct hash_foreach_arg arg = {
1073
+ .hash = obj,
869
1074
  .data = data,
870
- .iter = 0,
1075
+ .first = true,
871
1076
  };
872
1077
  rb_hash_foreach(obj, json_object_i, (VALUE)&arg);
873
1078
 
874
- depth = --data->state->depth;
1079
+ depth = --data->depth;
875
1080
  if (RB_UNLIKELY(data->state->object_nl)) {
876
1081
  fbuffer_append_str(buffer, data->state->object_nl);
877
1082
  if (RB_UNLIKELY(data->state->indent)) {
878
- for (j = 0; j < depth; j++) {
879
- fbuffer_append_str(buffer, data->state->indent);
880
- }
1083
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
881
1084
  }
882
1085
  }
883
1086
  fbuffer_append_char(buffer, '}');
@@ -885,119 +1088,41 @@ static void generate_json_object(FBuffer *buffer, struct generate_json_data *dat
885
1088
 
886
1089
  static void generate_json_array(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
887
1090
  {
888
- int i, j;
889
1091
  long depth = increase_depth(data);
890
1092
 
891
1093
  if (RARRAY_LEN(obj) == 0) {
892
1094
  fbuffer_append(buffer, "[]", 2);
893
- --data->state->depth;
1095
+ --data->depth;
894
1096
  return;
895
1097
  }
896
1098
 
897
1099
  fbuffer_append_char(buffer, '[');
898
1100
  if (RB_UNLIKELY(data->state->array_nl)) fbuffer_append_str(buffer, data->state->array_nl);
899
- for(i = 0; i < RARRAY_LEN(obj); i++) {
1101
+ for (int i = 0; i < RARRAY_LEN(obj); i++) {
900
1102
  if (i > 0) {
901
1103
  fbuffer_append_char(buffer, ',');
902
1104
  if (RB_UNLIKELY(data->state->array_nl)) fbuffer_append_str(buffer, data->state->array_nl);
903
1105
  }
904
1106
  if (RB_UNLIKELY(data->state->indent)) {
905
- for (j = 0; j < depth; j++) {
906
- fbuffer_append_str(buffer, data->state->indent);
907
- }
1107
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
908
1108
  }
909
1109
  generate_json(buffer, data, RARRAY_AREF(obj, i));
910
1110
  }
911
- data->state->depth = --depth;
1111
+ data->depth = --depth;
912
1112
  if (RB_UNLIKELY(data->state->array_nl)) {
913
1113
  fbuffer_append_str(buffer, data->state->array_nl);
914
1114
  if (RB_UNLIKELY(data->state->indent)) {
915
- for (j = 0; j < depth; j++) {
916
- fbuffer_append_str(buffer, data->state->indent);
917
- }
1115
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
918
1116
  }
919
1117
  }
920
1118
  fbuffer_append_char(buffer, ']');
921
1119
  }
922
1120
 
923
- static inline int enc_utf8_compatible_p(int enc_idx)
924
- {
925
- if (enc_idx == usascii_encindex) return 1;
926
- if (enc_idx == utf8_encindex) return 1;
927
- return 0;
928
- }
929
-
930
- static VALUE encode_json_string_try(VALUE str)
931
- {
932
- return rb_funcall(str, i_encode, 1, Encoding_UTF_8);
933
- }
934
-
935
- static VALUE encode_json_string_rescue(VALUE str, VALUE exception)
936
- {
937
- raise_generator_error_str(str, rb_funcall(exception, rb_intern("message"), 0));
938
- return Qundef;
939
- }
940
-
941
- static inline VALUE ensure_valid_encoding(VALUE str)
942
- {
943
- int encindex = RB_ENCODING_GET(str);
944
- VALUE utf8_string;
945
- if (RB_UNLIKELY(!enc_utf8_compatible_p(encindex))) {
946
- if (encindex == binary_encindex) {
947
- utf8_string = rb_enc_associate_index(rb_str_dup(str), utf8_encindex);
948
- switch (rb_enc_str_coderange(utf8_string)) {
949
- case ENC_CODERANGE_7BIT:
950
- return utf8_string;
951
- case ENC_CODERANGE_VALID:
952
- // For historical reason, we silently reinterpret binary strings as UTF-8 if it would work.
953
- // TODO: Raise in 3.0.0
954
- rb_warn("JSON.generate: UTF-8 string passed as BINARY, this will raise an encoding error in json 3.0");
955
- return utf8_string;
956
- break;
957
- }
958
- }
959
-
960
- str = rb_rescue(encode_json_string_try, str, encode_json_string_rescue, str);
961
- }
962
- return str;
963
- }
964
-
965
- static void generate_json_string(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
966
- {
967
- obj = ensure_valid_encoding(obj);
968
-
969
- fbuffer_append_char(buffer, '"');
970
-
971
- long len;
972
- search_state search;
973
- search.buffer = buffer;
974
- RSTRING_GETMEM(obj, search.ptr, len);
975
- search.cursor = search.ptr;
976
- search.end = search.ptr + len;
977
-
978
- switch(rb_enc_str_coderange(obj)) {
979
- case ENC_CODERANGE_7BIT:
980
- case ENC_CODERANGE_VALID:
981
- if (RB_UNLIKELY(data->state->ascii_only)) {
982
- convert_UTF8_to_ASCII_only_JSON(&search, data->state->script_safe ? script_safe_escape_table : ascii_only_escape_table);
983
- } else if (RB_UNLIKELY(data->state->script_safe)) {
984
- convert_UTF8_to_script_safe_JSON(&search);
985
- } else {
986
- convert_UTF8_to_JSON(&search);
987
- }
988
- break;
989
- default:
990
- raise_generator_error(obj, "source sequence is illegal/malformed utf-8");
991
- break;
992
- }
993
- fbuffer_append_char(buffer, '"');
994
- }
995
-
996
1121
  static void generate_json_fallback(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
997
1122
  {
998
1123
  VALUE tmp;
999
1124
  if (rb_respond_to(obj, i_to_json)) {
1000
- tmp = rb_funcall(obj, i_to_json, 1, vstate_get(data));
1125
+ tmp = json_call_to_json(data, obj);
1001
1126
  Check_Type(tmp, T_STRING);
1002
1127
  fbuffer_append_str(buffer, tmp);
1003
1128
  } else {
@@ -1039,19 +1164,9 @@ static void generate_json_fixnum(FBuffer *buffer, struct generate_json_data *dat
1039
1164
  static void generate_json_bignum(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1040
1165
  {
1041
1166
  VALUE tmp = rb_funcall(obj, i_to_s, 0);
1042
- fbuffer_append_str(buffer, tmp);
1167
+ fbuffer_append_str(buffer, StringValue(tmp));
1043
1168
  }
1044
1169
 
1045
- #ifdef RUBY_INTEGER_UNIFICATION
1046
- static void generate_json_integer(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1047
- {
1048
- if (FIXNUM_P(obj))
1049
- generate_json_fixnum(buffer, data, obj);
1050
- else
1051
- generate_json_bignum(buffer, data, obj);
1052
- }
1053
- #endif
1054
-
1055
1170
  static void generate_json_float(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1056
1171
  {
1057
1172
  double value = RFLOAT_VALUE(obj);
@@ -1060,11 +1175,11 @@ static void generate_json_float(FBuffer *buffer, struct generate_json_data *data
1060
1175
  /* for NaN and Infinity values we either raise an error or rely on Float#to_s. */
1061
1176
  if (!allow_nan) {
1062
1177
  if (data->state->strict && data->state->as_json) {
1063
- VALUE casted_obj = rb_proc_call_with_block(data->state->as_json, 1, &obj, Qnil);
1178
+ VALUE casted_obj = json_call_as_json(data->state, obj, Qfalse);
1064
1179
  if (casted_obj != obj) {
1065
1180
  increase_depth(data);
1066
1181
  generate_json(buffer, data, casted_obj);
1067
- data->state->depth--;
1182
+ data->depth--;
1068
1183
  return;
1069
1184
  }
1070
1185
  }
@@ -1077,17 +1192,15 @@ static void generate_json_float(FBuffer *buffer, struct generate_json_data *data
1077
1192
  }
1078
1193
 
1079
1194
  /* This implementation writes directly into the buffer. We reserve
1080
- * the 24 characters that fpconv_dtoa states as its maximum, plus
1081
- * 2 more characters for the potential ".0" suffix.
1195
+ * the 32 characters that fpconv_dtoa states as its maximum.
1082
1196
  */
1083
- fbuffer_inc_capa(buffer, 26);
1197
+ fbuffer_inc_capa(buffer, 32);
1084
1198
  char* d = buffer->ptr + buffer->len;
1085
1199
  int len = fpconv_dtoa(value, d);
1086
-
1087
1200
  /* fpconv_dtoa converts a float to its shortest string representation,
1088
1201
  * but it adds a ".0" if this is a plain integer.
1089
1202
  */
1090
- buffer->len += len;
1203
+ fbuffer_consumed(buffer, len);
1091
1204
  }
1092
1205
 
1093
1206
  static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
@@ -1097,7 +1210,7 @@ static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *d
1097
1210
  fbuffer_append_str(buffer, fragment);
1098
1211
  }
1099
1212
 
1100
- static void generate_json(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1213
+ static inline void generate_json_general(FBuffer *buffer, struct generate_json_data *data, VALUE obj, bool fallback)
1101
1214
  {
1102
1215
  bool as_json_called = false;
1103
1216
  start:
@@ -1124,22 +1237,31 @@ start:
1124
1237
  generate_json_bignum(buffer, data, obj);
1125
1238
  break;
1126
1239
  case T_HASH:
1127
- if (klass != rb_cHash) goto general;
1240
+ if (fallback && klass != rb_cHash) goto general;
1128
1241
  generate_json_object(buffer, data, obj);
1129
1242
  break;
1130
1243
  case T_ARRAY:
1131
- if (klass != rb_cArray) goto general;
1244
+ if (fallback && klass != rb_cArray) goto general;
1132
1245
  generate_json_array(buffer, data, obj);
1133
1246
  break;
1134
1247
  case T_STRING:
1135
- if (klass != rb_cString) goto general;
1136
- generate_json_string(buffer, data, obj);
1248
+ if (fallback && klass != rb_cString) goto general;
1249
+
1250
+ if (RB_LIKELY(valid_json_string_p(obj))) {
1251
+ raw_generate_json_string(buffer, data, obj);
1252
+ } else if (as_json_called) {
1253
+ raise_generator_error(obj, "source sequence is illegal/malformed utf-8");
1254
+ } else {
1255
+ obj = ensure_valid_encoding(data, obj, false, false);
1256
+ as_json_called = true;
1257
+ goto start;
1258
+ }
1137
1259
  break;
1138
1260
  case T_SYMBOL:
1139
1261
  generate_json_symbol(buffer, data, obj);
1140
1262
  break;
1141
1263
  case T_FLOAT:
1142
- if (klass != rb_cFloat) goto general;
1264
+ if (fallback && klass != rb_cFloat) goto general;
1143
1265
  generate_json_float(buffer, data, obj);
1144
1266
  break;
1145
1267
  case T_STRUCT:
@@ -1150,7 +1272,7 @@ start:
1150
1272
  general:
1151
1273
  if (data->state->strict) {
1152
1274
  if (RTEST(data->state->as_json) && !as_json_called) {
1153
- obj = rb_proc_call_with_block(data->state->as_json, 1, &obj, Qnil);
1275
+ obj = json_call_as_json(data->state, obj, Qfalse);
1154
1276
  as_json_called = true;
1155
1277
  goto start;
1156
1278
  } else {
@@ -1163,45 +1285,50 @@ start:
1163
1285
  }
1164
1286
  }
1165
1287
 
1288
+ static void generate_json(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1289
+ {
1290
+ generate_json_general(buffer, data, obj, true);
1291
+ }
1292
+
1293
+ static void generate_json_no_fallback(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1294
+ {
1295
+ generate_json_general(buffer, data, obj, false);
1296
+ }
1297
+
1166
1298
  static VALUE generate_json_try(VALUE d)
1167
1299
  {
1168
1300
  struct generate_json_data *data = (struct generate_json_data *)d;
1169
1301
 
1170
1302
  data->func(data->buffer, data, data->obj);
1171
1303
 
1172
- return Qnil;
1304
+ return fbuffer_finalize(data->buffer);
1173
1305
  }
1174
1306
 
1175
- static VALUE generate_json_rescue(VALUE d, VALUE exc)
1307
+ static VALUE generate_json_ensure(VALUE d)
1176
1308
  {
1177
1309
  struct generate_json_data *data = (struct generate_json_data *)d;
1178
1310
  fbuffer_free(data->buffer);
1179
1311
 
1180
- rb_exc_raise(exc);
1181
-
1182
1312
  return Qundef;
1183
1313
  }
1184
1314
 
1185
- static VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func func, VALUE io)
1315
+ static inline VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func func, VALUE io)
1186
1316
  {
1187
1317
  GET_STATE(self);
1188
1318
 
1189
1319
  char stack_buffer[FBUFFER_STACK_SIZE];
1190
- FBuffer buffer = {
1191
- .io = RTEST(io) ? io : Qfalse,
1192
- };
1193
- fbuffer_stack_init(&buffer, state->buffer_initial_length, stack_buffer, FBUFFER_STACK_SIZE);
1320
+ FBuffer buffer = { 0 };
1321
+ fbuffer_init(&buffer, state->buffer_initial_length, io, stack_buffer, FBUFFER_STACK_SIZE);
1194
1322
 
1195
1323
  struct generate_json_data data = {
1196
1324
  .buffer = &buffer,
1197
- .vstate = self,
1325
+ .vstate = Qfalse, // don't use self as it may be frozen and its depth is mutated when calling to_json
1198
1326
  .state = state,
1327
+ .depth = state->depth,
1199
1328
  .obj = obj,
1200
1329
  .func = func
1201
1330
  };
1202
- rb_rescue(generate_json_try, (VALUE)&data, generate_json_rescue, (VALUE)&data);
1203
-
1204
- return fbuffer_finalize(&buffer);
1331
+ return rb_ensure(generate_json_try, (VALUE)&data, generate_json_ensure, (VALUE)&data);
1205
1332
  }
1206
1333
 
1207
1334
  /* call-seq:
@@ -1217,10 +1344,16 @@ static VALUE cState_generate(int argc, VALUE *argv, VALUE self)
1217
1344
  rb_check_arity(argc, 1, 2);
1218
1345
  VALUE obj = argv[0];
1219
1346
  VALUE io = argc > 1 ? argv[1] : Qnil;
1220
- VALUE result = cState_partial_generate(self, obj, generate_json, io);
1221
- GET_STATE(self);
1222
- (void)state;
1223
- return result;
1347
+ return cState_partial_generate(self, obj, generate_json, io);
1348
+ }
1349
+
1350
+ /* :nodoc: */
1351
+ static VALUE cState_generate_no_fallback(int argc, VALUE *argv, VALUE self)
1352
+ {
1353
+ rb_check_arity(argc, 1, 2);
1354
+ VALUE obj = argv[0];
1355
+ VALUE io = argc > 1 ? argv[1] : Qnil;
1356
+ return cState_partial_generate(self, obj, generate_json_no_fallback, io);
1224
1357
  }
1225
1358
 
1226
1359
  static VALUE cState_initialize(int argc, VALUE *argv, VALUE self)
@@ -1245,12 +1378,15 @@ static VALUE cState_init_copy(VALUE obj, VALUE orig)
1245
1378
  if (!objState) rb_raise(rb_eArgError, "unallocated JSON::State");
1246
1379
 
1247
1380
  MEMCPY(objState, origState, JSON_Generator_State, 1);
1248
- objState->indent = origState->indent;
1249
- objState->space = origState->space;
1250
- objState->space_before = origState->space_before;
1251
- objState->object_nl = origState->object_nl;
1252
- objState->array_nl = origState->array_nl;
1253
- objState->as_json = origState->as_json;
1381
+
1382
+ RB_OBJ_WRITTEN(obj, Qundef, objState->indent);
1383
+ RB_OBJ_WRITTEN(obj, Qundef, objState->space);
1384
+ RB_OBJ_WRITTEN(obj, Qundef, objState->space_before);
1385
+ RB_OBJ_WRITTEN(obj, Qundef, objState->object_nl);
1386
+ RB_OBJ_WRITTEN(obj, Qundef, objState->array_nl);
1387
+ RB_OBJ_WRITTEN(obj, Qundef, objState->as_json);
1388
+ RB_OBJ_WRITTEN(obj, Qundef, objState->sort_keys);
1389
+
1254
1390
  return obj;
1255
1391
  }
1256
1392
 
@@ -1301,6 +1437,7 @@ static VALUE string_config(VALUE config)
1301
1437
  */
1302
1438
  static VALUE cState_indent_set(VALUE self, VALUE indent)
1303
1439
  {
1440
+ rb_check_frozen(self);
1304
1441
  GET_STATE(self);
1305
1442
  RB_OBJ_WRITE(self, &state->indent, string_config(indent));
1306
1443
  return Qnil;
@@ -1326,6 +1463,7 @@ static VALUE cState_space(VALUE self)
1326
1463
  */
1327
1464
  static VALUE cState_space_set(VALUE self, VALUE space)
1328
1465
  {
1466
+ rb_check_frozen(self);
1329
1467
  GET_STATE(self);
1330
1468
  RB_OBJ_WRITE(self, &state->space, string_config(space));
1331
1469
  return Qnil;
@@ -1349,6 +1487,7 @@ static VALUE cState_space_before(VALUE self)
1349
1487
  */
1350
1488
  static VALUE cState_space_before_set(VALUE self, VALUE space_before)
1351
1489
  {
1490
+ rb_check_frozen(self);
1352
1491
  GET_STATE(self);
1353
1492
  RB_OBJ_WRITE(self, &state->space_before, string_config(space_before));
1354
1493
  return Qnil;
@@ -1374,6 +1513,7 @@ static VALUE cState_object_nl(VALUE self)
1374
1513
  */
1375
1514
  static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)
1376
1515
  {
1516
+ rb_check_frozen(self);
1377
1517
  GET_STATE(self);
1378
1518
  RB_OBJ_WRITE(self, &state->object_nl, string_config(object_nl));
1379
1519
  return Qnil;
@@ -1397,6 +1537,7 @@ static VALUE cState_array_nl(VALUE self)
1397
1537
  */
1398
1538
  static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)
1399
1539
  {
1540
+ rb_check_frozen(self);
1400
1541
  GET_STATE(self);
1401
1542
  RB_OBJ_WRITE(self, &state->array_nl, string_config(array_nl));
1402
1543
  return Qnil;
@@ -1420,6 +1561,7 @@ static VALUE cState_as_json(VALUE self)
1420
1561
  */
1421
1562
  static VALUE cState_as_json_set(VALUE self, VALUE as_json)
1422
1563
  {
1564
+ rb_check_frozen(self);
1423
1565
  GET_STATE(self);
1424
1566
  RB_OBJ_WRITE(self, &state->as_json, rb_convert_type(as_json, T_DATA, "Proc", "to_proc"));
1425
1567
  return Qnil;
@@ -1451,7 +1593,21 @@ static VALUE cState_max_nesting(VALUE self)
1451
1593
 
1452
1594
  static long long_config(VALUE num)
1453
1595
  {
1454
- return RTEST(num) ? FIX2LONG(num) : 0;
1596
+ return RTEST(num) ? NUM2LONG(num) : 0;
1597
+ }
1598
+
1599
+ // depth must never be negative; reject early with a clear error.
1600
+ static long depth_config(VALUE num)
1601
+ {
1602
+ if (!RTEST(num)) return 0;
1603
+ long d = NUM2LONG(num);
1604
+ if (RB_UNLIKELY(d < 0)) {
1605
+ rb_raise(rb_eArgError, "depth must be >= 0 (got %ld)", d);
1606
+ }
1607
+ if (RB_UNLIKELY(d > INT_MAX)) {
1608
+ rb_raise(rb_eArgError, "depth is too large (got %ld)", d);
1609
+ }
1610
+ return d;
1455
1611
  }
1456
1612
 
1457
1613
  /*
@@ -1462,6 +1618,7 @@ static long long_config(VALUE num)
1462
1618
  */
1463
1619
  static VALUE cState_max_nesting_set(VALUE self, VALUE depth)
1464
1620
  {
1621
+ rb_check_frozen(self);
1465
1622
  GET_STATE(self);
1466
1623
  state->max_nesting = long_config(depth);
1467
1624
  return Qnil;
@@ -1487,6 +1644,7 @@ static VALUE cState_script_safe(VALUE self)
1487
1644
  */
1488
1645
  static VALUE cState_script_safe_set(VALUE self, VALUE enable)
1489
1646
  {
1647
+ rb_check_frozen(self);
1490
1648
  GET_STATE(self);
1491
1649
  state->script_safe = RTEST(enable);
1492
1650
  return Qnil;
@@ -1518,6 +1676,7 @@ static VALUE cState_strict(VALUE self)
1518
1676
  */
1519
1677
  static VALUE cState_strict_set(VALUE self, VALUE enable)
1520
1678
  {
1679
+ rb_check_frozen(self);
1521
1680
  GET_STATE(self);
1522
1681
  state->strict = RTEST(enable);
1523
1682
  return Qnil;
@@ -1542,6 +1701,7 @@ static VALUE cState_allow_nan_p(VALUE self)
1542
1701
  */
1543
1702
  static VALUE cState_allow_nan_set(VALUE self, VALUE enable)
1544
1703
  {
1704
+ rb_check_frozen(self);
1545
1705
  GET_STATE(self);
1546
1706
  state->allow_nan = RTEST(enable);
1547
1707
  return Qnil;
@@ -1566,11 +1726,74 @@ static VALUE cState_ascii_only_p(VALUE self)
1566
1726
  */
1567
1727
  static VALUE cState_ascii_only_set(VALUE self, VALUE enable)
1568
1728
  {
1729
+ rb_check_frozen(self);
1569
1730
  GET_STATE(self);
1570
1731
  state->ascii_only = RTEST(enable);
1571
1732
  return Qnil;
1572
1733
  }
1573
1734
 
1735
+ static VALUE cState_set_default_sort_keys_proc(VALUE self, VALUE proc)
1736
+ {
1737
+ if (!rb_obj_is_proc(proc)) {
1738
+ rb_raise(rb_eTypeError, "sort_key_proc must be a Proc");
1739
+ }
1740
+ return default_sort_keys_proc = proc;
1741
+ }
1742
+
1743
+ static VALUE normalize_sort_keys(VALUE value)
1744
+ {
1745
+ if (rb_obj_is_proc(value)) {
1746
+ return value;
1747
+ } else if (value == Qtrue) {
1748
+ return default_sort_keys_proc;
1749
+ } else if (RTEST(value)) {
1750
+ rb_raise(rb_eTypeError, "The `sort_keys` argument must be a boolean or a Proc");
1751
+ } else {
1752
+ return Qfalse;
1753
+ }
1754
+ }
1755
+
1756
+ /*
1757
+ * call-seq: sort_keys
1758
+ *
1759
+ * Get the value of sort_keys.
1760
+ */
1761
+ static VALUE cState_sort_keys_p(VALUE self)
1762
+ {
1763
+ GET_STATE(self);
1764
+ return state->sort_keys;
1765
+ }
1766
+
1767
+ /*
1768
+ * call-seq: sort_keys=(value)
1769
+ *
1770
+ * value is a boolean or a proc. If the value is the boolean true, object keys
1771
+ * will be sorted lexicographically in ascending order.
1772
+ *
1773
+ * If the value is a proc, it receives the entire Hash and must return a Hash
1774
+ * with its pairs in the desired order, allowing for arbitrary sorting.
1775
+ */
1776
+ static VALUE cState_sort_keys_set(VALUE self, VALUE value)
1777
+ {
1778
+ rb_check_frozen(self);
1779
+ GET_STATE(self);
1780
+ RB_OBJ_WRITE(self, &state->sort_keys, normalize_sort_keys(value));
1781
+ return Qnil;
1782
+ }
1783
+
1784
+ static VALUE cState_allow_duplicate_key_p(VALUE self)
1785
+ {
1786
+ GET_STATE(self);
1787
+ switch (state->on_duplicate_key) {
1788
+ case JSON_IGNORE:
1789
+ return Qtrue;
1790
+ case JSON_DEPRECATED:
1791
+ return Qnil;
1792
+ default:
1793
+ return Qfalse;
1794
+ }
1795
+ }
1796
+
1574
1797
  /*
1575
1798
  * call-seq: depth
1576
1799
  *
@@ -1590,8 +1813,9 @@ static VALUE cState_depth(VALUE self)
1590
1813
  */
1591
1814
  static VALUE cState_depth_set(VALUE self, VALUE depth)
1592
1815
  {
1816
+ rb_check_frozen(self);
1593
1817
  GET_STATE(self);
1594
- state->depth = long_config(depth);
1818
+ state->depth = depth_config(depth);
1595
1819
  return Qnil;
1596
1820
  }
1597
1821
 
@@ -1623,33 +1847,57 @@ static void buffer_initial_length_set(JSON_Generator_State *state, VALUE buffer_
1623
1847
  */
1624
1848
  static VALUE cState_buffer_initial_length_set(VALUE self, VALUE buffer_initial_length)
1625
1849
  {
1850
+ rb_check_frozen(self);
1626
1851
  GET_STATE(self);
1627
1852
  buffer_initial_length_set(state, buffer_initial_length);
1628
1853
  return Qnil;
1629
1854
  }
1630
1855
 
1856
+ struct configure_state_data {
1857
+ JSON_Generator_State *state;
1858
+ VALUE vstate; // Ruby object that owns the state, or Qfalse if stack-allocated
1859
+ };
1860
+
1861
+ static inline void state_write_value(struct configure_state_data *data, VALUE *field, VALUE value)
1862
+ {
1863
+ if (RTEST(data->vstate)) {
1864
+ RB_OBJ_WRITE(data->vstate, field, value);
1865
+ } else {
1866
+ *field = value;
1867
+ }
1868
+ }
1869
+
1631
1870
  static int configure_state_i(VALUE key, VALUE val, VALUE _arg)
1632
1871
  {
1633
- JSON_Generator_State *state = (JSON_Generator_State *)_arg;
1872
+ struct configure_state_data *data = (struct configure_state_data *)_arg;
1873
+ JSON_Generator_State *state = data->state;
1634
1874
 
1635
- if (key == sym_indent) { state->indent = string_config(val); }
1636
- else if (key == sym_space) { state->space = string_config(val); }
1637
- else if (key == sym_space_before) { state->space_before = string_config(val); }
1638
- else if (key == sym_object_nl) { state->object_nl = string_config(val); }
1639
- else if (key == sym_array_nl) { state->array_nl = string_config(val); }
1875
+ if (key == sym_indent) { state_write_value(data, &state->indent, string_config(val)); }
1876
+ else if (key == sym_space) { state_write_value(data, &state->space, string_config(val)); }
1877
+ else if (key == sym_space_before) { state_write_value(data, &state->space_before, string_config(val)); }
1878
+ else if (key == sym_object_nl) { state_write_value(data, &state->object_nl, string_config(val)); }
1879
+ else if (key == sym_array_nl) { state_write_value(data, &state->array_nl, string_config(val)); }
1640
1880
  else if (key == sym_max_nesting) { state->max_nesting = long_config(val); }
1641
1881
  else if (key == sym_allow_nan) { state->allow_nan = RTEST(val); }
1642
1882
  else if (key == sym_ascii_only) { state->ascii_only = RTEST(val); }
1643
- else if (key == sym_depth) { state->depth = long_config(val); }
1883
+ else if (key == sym_depth) { state->depth = depth_config(val); }
1644
1884
  else if (key == sym_buffer_initial_length) { buffer_initial_length_set(state, val); }
1645
1885
  else if (key == sym_script_safe) { state->script_safe = RTEST(val); }
1646
1886
  else if (key == sym_escape_slash) { state->script_safe = RTEST(val); }
1647
1887
  else if (key == sym_strict) { state->strict = RTEST(val); }
1648
- else if (key == sym_as_json) { state->as_json = RTEST(val) ? rb_convert_type(val, T_DATA, "Proc", "to_proc") : Qfalse; }
1888
+ else if (key == sym_allow_duplicate_key) { state->on_duplicate_key = RTEST(val) ? JSON_IGNORE : JSON_RAISE; }
1889
+ else if (key == sym_as_json) {
1890
+ VALUE proc = RTEST(val) ? rb_convert_type(val, T_DATA, "Proc", "to_proc") : Qfalse;
1891
+ state->as_json_single_arg = proc && rb_proc_arity(proc) == 1;
1892
+ state_write_value(data, &state->as_json, proc);
1893
+ }
1894
+ else if (key == sym_sort_keys) {
1895
+ state_write_value(data, &state->sort_keys, normalize_sort_keys(val));
1896
+ }
1649
1897
  return ST_CONTINUE;
1650
1898
  }
1651
1899
 
1652
- static void configure_state(JSON_Generator_State *state, VALUE config)
1900
+ static void configure_state(JSON_Generator_State *state, VALUE vstate, VALUE config)
1653
1901
  {
1654
1902
  if (!RTEST(config)) return;
1655
1903
 
@@ -1657,45 +1905,55 @@ static void configure_state(JSON_Generator_State *state, VALUE config)
1657
1905
 
1658
1906
  if (!RHASH_SIZE(config)) return;
1659
1907
 
1908
+ struct configure_state_data data = {
1909
+ .state = state,
1910
+ .vstate = vstate
1911
+ };
1912
+
1660
1913
  // We assume in most cases few keys are set so it's faster to go over
1661
1914
  // the provided keys than to check all possible keys.
1662
- rb_hash_foreach(config, configure_state_i, (VALUE)state);
1915
+ rb_hash_foreach(config, configure_state_i, (VALUE)&data);
1663
1916
  }
1664
1917
 
1665
1918
  static VALUE cState_configure(VALUE self, VALUE opts)
1666
1919
  {
1920
+ rb_check_frozen(self);
1667
1921
  GET_STATE(self);
1668
- configure_state(state, opts);
1922
+ configure_state(state, self, opts);
1669
1923
  return self;
1670
1924
  }
1671
1925
 
1672
- static VALUE cState_m_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1926
+ static VALUE cState_m_do_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io, generator_func func)
1673
1927
  {
1674
1928
  JSON_Generator_State state = {0};
1675
1929
  state_init(&state);
1676
- configure_state(&state, opts);
1930
+ configure_state(&state, Qfalse, opts);
1677
1931
 
1678
1932
  char stack_buffer[FBUFFER_STACK_SIZE];
1679
- FBuffer buffer = {
1680
- .io = RTEST(io) ? io : Qfalse,
1681
- };
1682
- fbuffer_stack_init(&buffer, state.buffer_initial_length, stack_buffer, FBUFFER_STACK_SIZE);
1933
+ FBuffer buffer = { 0 };
1934
+ fbuffer_init(&buffer, state.buffer_initial_length, io, stack_buffer, FBUFFER_STACK_SIZE);
1683
1935
 
1684
1936
  struct generate_json_data data = {
1685
1937
  .buffer = &buffer,
1686
1938
  .vstate = Qfalse,
1687
1939
  .state = &state,
1940
+ .depth = state.depth,
1688
1941
  .obj = obj,
1689
- .func = generate_json,
1942
+ .func = func,
1690
1943
  };
1691
- rb_rescue(generate_json_try, (VALUE)&data, generate_json_rescue, (VALUE)&data);
1944
+ return rb_ensure(generate_json_try, (VALUE)&data, generate_json_ensure, (VALUE)&data);
1945
+ }
1946
+
1947
+ static VALUE cState_m_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1948
+ {
1949
+ return cState_m_do_generate(klass, obj, opts, io, generate_json);
1950
+ }
1692
1951
 
1693
- return fbuffer_finalize(&buffer);
1952
+ static VALUE cState_m_generate_no_fallback(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1953
+ {
1954
+ return cState_m_do_generate(klass, obj, opts, io, generate_json_no_fallback);
1694
1955
  }
1695
1956
 
1696
- /*
1697
- *
1698
- */
1699
1957
  void Init_generator(void)
1700
1958
  {
1701
1959
  #ifdef HAVE_RB_EXT_RACTOR_SAFE
@@ -1713,6 +1971,8 @@ void Init_generator(void)
1713
1971
  VALUE mExt = rb_define_module_under(mJSON, "Ext");
1714
1972
  VALUE mGenerator = rb_define_module_under(mExt, "Generator");
1715
1973
 
1974
+ rb_global_variable(&default_sort_keys_proc);
1975
+
1716
1976
  rb_global_variable(&eGeneratorError);
1717
1977
  eGeneratorError = rb_path2class("JSON::GeneratorError");
1718
1978
 
@@ -1722,6 +1982,8 @@ void Init_generator(void)
1722
1982
  cState = rb_define_class_under(mGenerator, "State", rb_cObject);
1723
1983
  rb_define_alloc_func(cState, cState_s_allocate);
1724
1984
  rb_define_singleton_method(cState, "from_state", cState_from_state_s, 1);
1985
+ rb_define_singleton_method(cState, "default_sort_keys_proc=", cState_set_default_sort_keys_proc, 1);
1986
+
1725
1987
  rb_define_method(cState, "initialize", cState_initialize, -1);
1726
1988
  rb_define_alias(cState, "initialize", "initialize"); // avoid method redefinition warnings
1727
1989
  rb_define_private_method(cState, "_configure", cState_configure, 1);
@@ -1760,51 +2022,14 @@ void Init_generator(void)
1760
2022
  rb_define_method(cState, "buffer_initial_length", cState_buffer_initial_length, 0);
1761
2023
  rb_define_method(cState, "buffer_initial_length=", cState_buffer_initial_length_set, 1);
1762
2024
  rb_define_method(cState, "generate", cState_generate, -1);
1763
- rb_define_alias(cState, "generate_new", "generate"); // :nodoc:
1764
-
1765
- rb_define_singleton_method(cState, "generate", cState_m_generate, 3);
1766
-
1767
- VALUE mGeneratorMethods = rb_define_module_under(mGenerator, "GeneratorMethods");
1768
-
1769
- VALUE mObject = rb_define_module_under(mGeneratorMethods, "Object");
1770
- rb_define_method(mObject, "to_json", mObject_to_json, -1);
1771
-
1772
- VALUE mHash = rb_define_module_under(mGeneratorMethods, "Hash");
1773
- rb_define_method(mHash, "to_json", mHash_to_json, -1);
1774
-
1775
- VALUE mArray = rb_define_module_under(mGeneratorMethods, "Array");
1776
- rb_define_method(mArray, "to_json", mArray_to_json, -1);
1777
-
1778
- #ifdef RUBY_INTEGER_UNIFICATION
1779
- VALUE mInteger = rb_define_module_under(mGeneratorMethods, "Integer");
1780
- rb_define_method(mInteger, "to_json", mInteger_to_json, -1);
1781
- #else
1782
- VALUE mFixnum = rb_define_module_under(mGeneratorMethods, "Fixnum");
1783
- rb_define_method(mFixnum, "to_json", mFixnum_to_json, -1);
1784
-
1785
- VALUE mBignum = rb_define_module_under(mGeneratorMethods, "Bignum");
1786
- rb_define_method(mBignum, "to_json", mBignum_to_json, -1);
1787
- #endif
1788
- VALUE mFloat = rb_define_module_under(mGeneratorMethods, "Float");
1789
- rb_define_method(mFloat, "to_json", mFloat_to_json, -1);
1790
-
1791
- VALUE mString = rb_define_module_under(mGeneratorMethods, "String");
1792
- rb_define_singleton_method(mString, "included", mString_included_s, 1);
1793
- rb_define_method(mString, "to_json", mString_to_json, -1);
1794
- rb_define_method(mString, "to_json_raw", mString_to_json_raw, -1);
1795
- rb_define_method(mString, "to_json_raw_object", mString_to_json_raw_object, 0);
2025
+ rb_define_method(cState, "_generate_no_fallback", cState_generate_no_fallback, -1);
2026
+ rb_define_method(cState, "sort_keys", cState_sort_keys_p, 0);
2027
+ rb_define_method(cState, "sort_keys=", cState_sort_keys_set, 1);
1796
2028
 
1797
- mString_Extend = rb_define_module_under(mString, "Extend");
1798
- rb_define_method(mString_Extend, "json_create", mString_Extend_json_create, 1);
2029
+ rb_define_private_method(cState, "allow_duplicate_key?", cState_allow_duplicate_key_p, 0);
1799
2030
 
1800
- VALUE mTrueClass = rb_define_module_under(mGeneratorMethods, "TrueClass");
1801
- rb_define_method(mTrueClass, "to_json", mTrueClass_to_json, -1);
1802
-
1803
- VALUE mFalseClass = rb_define_module_under(mGeneratorMethods, "FalseClass");
1804
- rb_define_method(mFalseClass, "to_json", mFalseClass_to_json, -1);
1805
-
1806
- VALUE mNilClass = rb_define_module_under(mGeneratorMethods, "NilClass");
1807
- rb_define_method(mNilClass, "to_json", mNilClass_to_json, -1);
2031
+ rb_define_singleton_method(cState, "generate", cState_m_generate, 3);
2032
+ rb_define_singleton_method(cState, "_generate_no_fallback", cState_m_generate_no_fallback, 3);
1808
2033
 
1809
2034
  rb_global_variable(&Encoding_UTF_8);
1810
2035
  Encoding_UTF_8 = rb_const_get(rb_path2class("Encoding"), rb_intern("UTF_8"));
@@ -1812,10 +2037,6 @@ void Init_generator(void)
1812
2037
  i_to_s = rb_intern("to_s");
1813
2038
  i_to_json = rb_intern("to_json");
1814
2039
  i_new = rb_intern("new");
1815
- i_pack = rb_intern("pack");
1816
- i_unpack = rb_intern("unpack");
1817
- i_create_id = rb_intern("create_id");
1818
- i_extend = rb_intern("extend");
1819
2040
  i_encode = rb_intern("encode");
1820
2041
 
1821
2042
  sym_indent = ID2SYM(rb_intern("indent"));
@@ -1832,10 +2053,14 @@ void Init_generator(void)
1832
2053
  sym_escape_slash = ID2SYM(rb_intern("escape_slash"));
1833
2054
  sym_strict = ID2SYM(rb_intern("strict"));
1834
2055
  sym_as_json = ID2SYM(rb_intern("as_json"));
2056
+ sym_allow_duplicate_key = ID2SYM(rb_intern("allow_duplicate_key"));
2057
+ sym_sort_keys = ID2SYM(rb_intern("sort_keys"));
1835
2058
 
1836
2059
  usascii_encindex = rb_usascii_encindex();
1837
2060
  utf8_encindex = rb_utf8_encindex();
1838
2061
  binary_encindex = rb_ascii8bit_encindex();
1839
2062
 
1840
2063
  rb_require("json/ext/generator/state");
2064
+
2065
+ simd_impl = find_simd_implementation();
1841
2066
  }