json 1.2.0 → 2.19.8

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.
Files changed (145) hide show
  1. checksums.yaml +7 -0
  2. data/BSDL +22 -0
  3. data/CHANGES.md +783 -0
  4. data/COPYING +14 -16
  5. data/LEGAL +20 -0
  6. data/README.md +310 -0
  7. data/ext/json/ext/fbuffer/fbuffer.h +260 -0
  8. data/ext/json/ext/generator/extconf.rb +15 -8
  9. data/ext/json/ext/generator/generator.c +1675 -613
  10. data/ext/json/ext/json.h +116 -0
  11. data/ext/json/ext/parser/extconf.rb +16 -7
  12. data/ext/json/ext/parser/parser.c +1649 -1772
  13. data/ext/json/ext/simd/conf.rb +24 -0
  14. data/ext/json/ext/simd/simd.h +208 -0
  15. data/ext/json/ext/vendor/fpconv.c +480 -0
  16. data/ext/json/ext/vendor/jeaiii-ltoa.h +267 -0
  17. data/ext/json/ext/vendor/ryu.h +819 -0
  18. data/json.gemspec +62 -0
  19. data/lib/json/add/bigdecimal.rb +58 -0
  20. data/lib/json/add/complex.rb +51 -0
  21. data/lib/json/add/core.rb +11 -133
  22. data/lib/json/add/date.rb +54 -0
  23. data/lib/json/add/date_time.rb +67 -0
  24. data/lib/json/add/exception.rb +49 -0
  25. data/lib/json/add/ostruct.rb +54 -0
  26. data/lib/json/add/range.rb +54 -0
  27. data/lib/json/add/rational.rb +49 -0
  28. data/lib/json/add/regexp.rb +48 -0
  29. data/lib/json/add/set.rb +48 -0
  30. data/lib/json/add/string.rb +35 -0
  31. data/lib/json/add/struct.rb +52 -0
  32. data/lib/json/add/symbol.rb +52 -0
  33. data/lib/json/add/time.rb +52 -0
  34. data/lib/json/common.rb +1056 -254
  35. data/lib/json/ext/generator/state.rb +103 -0
  36. data/lib/json/ext.rb +35 -5
  37. data/lib/json/generic_object.rb +67 -0
  38. data/lib/json/truffle_ruby/generator.rb +755 -0
  39. data/lib/json/version.rb +3 -6
  40. data/lib/json.rb +671 -6
  41. metadata +68 -159
  42. data/CHANGES +0 -136
  43. data/GPL +0 -340
  44. data/README +0 -360
  45. data/Rakefile +0 -287
  46. data/TODO +0 -1
  47. data/VERSION +0 -1
  48. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkComparison.log +0 -52
  49. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkExt#generator_fast-autocorrelation.dat +0 -1000
  50. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkExt#generator_fast.dat +0 -1001
  51. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkExt#generator_pretty-autocorrelation.dat +0 -900
  52. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkExt#generator_pretty.dat +0 -901
  53. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkExt#generator_safe-autocorrelation.dat +0 -1000
  54. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkExt#generator_safe.dat +0 -1001
  55. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkExt.log +0 -261
  56. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkPure#generator_fast-autocorrelation.dat +0 -1000
  57. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkPure#generator_fast.dat +0 -1001
  58. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkPure#generator_pretty-autocorrelation.dat +0 -1000
  59. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkPure#generator_pretty.dat +0 -1001
  60. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkPure#generator_safe-autocorrelation.dat +0 -1000
  61. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkPure#generator_safe.dat +0 -1001
  62. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkPure.log +0 -262
  63. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkRails#generator-autocorrelation.dat +0 -1000
  64. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkRails#generator.dat +0 -1001
  65. data/benchmarks/data-p4-3GHz-ruby18/GeneratorBenchmarkRails.log +0 -82
  66. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkComparison.log +0 -34
  67. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkExt#parser-autocorrelation.dat +0 -900
  68. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkExt#parser.dat +0 -901
  69. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkExt.log +0 -81
  70. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkPure#parser-autocorrelation.dat +0 -1000
  71. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkPure#parser.dat +0 -1001
  72. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkPure.log +0 -82
  73. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkRails#parser-autocorrelation.dat +0 -1000
  74. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkRails#parser.dat +0 -1001
  75. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkRails.log +0 -82
  76. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkYAML#parser-autocorrelation.dat +0 -1000
  77. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkYAML#parser.dat +0 -1001
  78. data/benchmarks/data-p4-3GHz-ruby18/ParserBenchmarkYAML.log +0 -82
  79. data/benchmarks/generator_benchmark.rb +0 -165
  80. data/benchmarks/parser_benchmark.rb +0 -197
  81. data/bin/edit_json.rb +0 -9
  82. data/bin/prettify_json.rb +0 -75
  83. data/data/example.json +0 -1
  84. data/data/index.html +0 -38
  85. data/data/prototype.js +0 -4184
  86. data/ext/json/ext/generator/unicode.c +0 -180
  87. data/ext/json/ext/generator/unicode.h +0 -53
  88. data/ext/json/ext/parser/parser.rl +0 -737
  89. data/ext/json/ext/parser/unicode.c +0 -154
  90. data/ext/json/ext/parser/unicode.h +0 -58
  91. data/install.rb +0 -26
  92. data/lib/json/Array.xpm +0 -21
  93. data/lib/json/FalseClass.xpm +0 -21
  94. data/lib/json/Hash.xpm +0 -21
  95. data/lib/json/Key.xpm +0 -73
  96. data/lib/json/NilClass.xpm +0 -21
  97. data/lib/json/Numeric.xpm +0 -28
  98. data/lib/json/String.xpm +0 -96
  99. data/lib/json/TrueClass.xpm +0 -21
  100. data/lib/json/add/rails.rb +0 -58
  101. data/lib/json/editor.rb +0 -1371
  102. data/lib/json/json.xpm +0 -1499
  103. data/lib/json/pure/generator.rb +0 -443
  104. data/lib/json/pure/parser.rb +0 -303
  105. data/lib/json/pure.rb +0 -77
  106. data/tests/fixtures/fail1.json +0 -1
  107. data/tests/fixtures/fail10.json +0 -1
  108. data/tests/fixtures/fail11.json +0 -1
  109. data/tests/fixtures/fail12.json +0 -1
  110. data/tests/fixtures/fail13.json +0 -1
  111. data/tests/fixtures/fail14.json +0 -1
  112. data/tests/fixtures/fail18.json +0 -1
  113. data/tests/fixtures/fail19.json +0 -1
  114. data/tests/fixtures/fail2.json +0 -1
  115. data/tests/fixtures/fail20.json +0 -1
  116. data/tests/fixtures/fail21.json +0 -1
  117. data/tests/fixtures/fail22.json +0 -1
  118. data/tests/fixtures/fail23.json +0 -1
  119. data/tests/fixtures/fail24.json +0 -1
  120. data/tests/fixtures/fail25.json +0 -1
  121. data/tests/fixtures/fail27.json +0 -2
  122. data/tests/fixtures/fail28.json +0 -2
  123. data/tests/fixtures/fail3.json +0 -1
  124. data/tests/fixtures/fail4.json +0 -1
  125. data/tests/fixtures/fail5.json +0 -1
  126. data/tests/fixtures/fail6.json +0 -1
  127. data/tests/fixtures/fail7.json +0 -1
  128. data/tests/fixtures/fail8.json +0 -1
  129. data/tests/fixtures/fail9.json +0 -1
  130. data/tests/fixtures/pass1.json +0 -56
  131. data/tests/fixtures/pass15.json +0 -1
  132. data/tests/fixtures/pass16.json +0 -1
  133. data/tests/fixtures/pass17.json +0 -1
  134. data/tests/fixtures/pass2.json +0 -1
  135. data/tests/fixtures/pass26.json +0 -1
  136. data/tests/fixtures/pass3.json +0 -6
  137. data/tests/test_json.rb +0 -320
  138. data/tests/test_json_addition.rb +0 -164
  139. data/tests/test_json_encoding.rb +0 -67
  140. data/tests/test_json_fixtures.rb +0 -34
  141. data/tests/test_json_generate.rb +0 -120
  142. data/tests/test_json_rails.rb +0 -146
  143. data/tests/test_json_unicode.rb +0 -62
  144. data/tools/fuzz.rb +0 -139
  145. data/tools/server.rb +0 -61
@@ -1,49 +1,19 @@
1
- #include <string.h>
2
- #include "ruby.h"
3
- #if HAVE_RUBY_ST_H
4
- #include "ruby/st.h"
5
- #endif
6
- #if HAVE_ST_H
7
- #include "st.h"
8
- #endif
9
- #include "unicode.h"
10
- #include <math.h>
11
-
12
- #ifndef RHASH_TBL
13
- #define RHASH_TBL(hsh) (RHASH(hsh)->tbl)
14
- #endif
15
-
16
- #ifndef RHASH_SIZE
17
- #define RHASH_SIZE(hsh) (RHASH(hsh)->tbl->num_entries)
18
- #endif
19
-
20
- #ifndef RFLOAT_VALUE
21
- #define RFLOAT_VALUE(val) (RFLOAT(val)->value)
22
- #endif
1
+ #include "../json.h"
2
+ #include "../fbuffer/fbuffer.h"
3
+ #include "../vendor/fpconv.c"
23
4
 
24
- #ifdef HAVE_RUBY_ENCODING_H
25
- #include "ruby/encoding.h"
26
- #define FORCE_UTF8(obj) rb_enc_associate((obj), rb_utf8_encoding())
27
- static VALUE mEncoding_UTF_8;
28
- static ID i_encoding, i_encode;
29
- #else
30
- #define FORCE_UTF8(obj)
31
- #endif
5
+ #include <math.h>
6
+ #include <ctype.h>
32
7
 
33
- #define check_max_nesting(state, depth) do { \
34
- long current_nesting = 1 + depth; \
35
- if (state->max_nesting != 0 && current_nesting > state->max_nesting) \
36
- rb_raise(eNestingError, "nesting of %ld is too deep", current_nesting); \
37
- } while (0);
8
+ #include "../simd/simd.h"
38
9
 
39
- static VALUE mJSON, mExt, mGenerator, cState, mGeneratorMethods, mObject,
40
- mHash, mArray, mInteger, mFloat, mString, mString_Extend,
41
- mTrueClass, mFalseClass, mNilClass, eGeneratorError,
42
- eCircularDatastructure, eNestingError;
10
+ /* ruby api and some helpers */
43
11
 
44
- static ID i_to_s, i_to_json, i_new, i_indent, i_space, i_space_before,
45
- i_object_nl, i_array_nl, i_check_circular, i_max_nesting,
46
- i_allow_nan, i_pack, i_unpack, i_create_id, i_extend;
12
+ enum duplicate_key_action {
13
+ JSON_DEPRECATED = 0,
14
+ JSON_IGNORE,
15
+ JSON_RAISE,
16
+ };
47
17
 
48
18
  typedef struct JSON_Generator_StateStruct {
49
19
  VALUE indent;
@@ -51,584 +21,1363 @@ typedef struct JSON_Generator_StateStruct {
51
21
  VALUE space_before;
52
22
  VALUE object_nl;
53
23
  VALUE array_nl;
54
- int check_circular;
55
- VALUE seen;
56
- VALUE memo;
57
- VALUE depth;
24
+ VALUE as_json;
25
+
58
26
  long max_nesting;
59
- int flag;
60
- int allow_nan;
27
+ long depth;
28
+ long buffer_initial_length;
29
+
30
+ enum duplicate_key_action on_duplicate_key;
31
+
32
+ bool as_json_single_arg;
33
+ bool allow_nan;
34
+ bool ascii_only;
35
+ bool script_safe;
36
+ bool strict;
61
37
  } JSON_Generator_State;
62
38
 
39
+ static VALUE mJSON, cState, cFragment, eGeneratorError, eNestingError, Encoding_UTF_8;
40
+
41
+ static ID i_to_s, i_to_json, i_new, i_encode;
42
+ static VALUE sym_indent, sym_space, sym_space_before, sym_object_nl, sym_array_nl, sym_max_nesting, sym_allow_nan, sym_allow_duplicate_key,
43
+ sym_ascii_only, sym_depth, sym_buffer_initial_length, sym_script_safe, sym_escape_slash, sym_strict, sym_as_json;
44
+
45
+
46
+ #define GET_STATE_TO(self, state) \
47
+ TypedData_Get_Struct(self, JSON_Generator_State, &JSON_Generator_State_type, state)
48
+
63
49
  #define GET_STATE(self) \
64
50
  JSON_Generator_State *state; \
65
- Data_Get_Struct(self, JSON_Generator_State, state);
51
+ GET_STATE_TO(self, state)
52
+
53
+ struct generate_json_data;
54
+
55
+ typedef void (*generator_func)(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
56
+
57
+ struct generate_json_data {
58
+ FBuffer *buffer;
59
+ VALUE vstate;
60
+ JSON_Generator_State *state;
61
+ VALUE obj;
62
+ generator_func func;
63
+ long depth;
64
+ };
65
+
66
+ static SIMD_Implementation simd_impl;
67
+
68
+ static VALUE cState_from_state_s(VALUE self, VALUE opts);
69
+ static VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func, VALUE io);
70
+ static void generate_json(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
71
+ static void generate_json_object(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
72
+ static void generate_json_array(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
73
+ static void generate_json_string(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
74
+ static void generate_json_null(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
75
+ static void generate_json_false(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
76
+ static void generate_json_true(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
77
+ static void generate_json_fixnum(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
78
+ static void generate_json_bignum(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
79
+ static void generate_json_float(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
80
+ static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *data, VALUE obj);
81
+
82
+ static int usascii_encindex, utf8_encindex, binary_encindex;
83
+
84
+ NORETURN(static void) raise_generator_error_str(VALUE invalid_object, VALUE str)
85
+ {
86
+ rb_enc_associate_index(str, utf8_encindex);
87
+ VALUE exc = rb_exc_new_str(eGeneratorError, str);
88
+ rb_ivar_set(exc, rb_intern("@invalid_object"), invalid_object);
89
+ rb_exc_raise(exc);
90
+ }
91
+
92
+ #ifdef RBIMPL_ATTR_FORMAT
93
+ RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 3)
94
+ #endif
95
+ NORETURN(static void) raise_generator_error(VALUE invalid_object, const char *fmt, ...)
96
+ {
97
+ va_list args;
98
+ va_start(args, fmt);
99
+ VALUE str = rb_vsprintf(fmt, args);
100
+ va_end(args);
101
+ raise_generator_error_str(invalid_object, str);
102
+ }
103
+
104
+ // 0 - single byte char that don't need to be escaped.
105
+ // (x | 8) - char that needs to be escaped.
106
+ static const unsigned char CHAR_LENGTH_MASK = 7;
107
+ static const unsigned char ESCAPE_MASK = 8;
108
+
109
+ typedef struct _search_state {
110
+ const char *ptr;
111
+ const char *end;
112
+ const char *cursor;
113
+ FBuffer *buffer;
114
+
115
+ #ifdef HAVE_SIMD
116
+ const char *chunk_base;
117
+ const char *chunk_end;
118
+ bool has_matches;
119
+
120
+ #if defined(HAVE_SIMD_NEON)
121
+ uint64_t matches_mask;
122
+ #elif defined(HAVE_SIMD_SSE2)
123
+ int matches_mask;
124
+ #else
125
+ #error "Unknown SIMD Implementation."
126
+ #endif /* HAVE_SIMD_NEON */
127
+ #endif /* HAVE_SIMD */
128
+ } search_state;
129
+
130
+ ALWAYS_INLINE(static) void search_flush(search_state *search)
131
+ {
132
+ // Do not remove this conditional without profiling, specifically escape-heavy text.
133
+ // escape_UTF8_char_basic will advance search->ptr and search->cursor (effectively a search_flush).
134
+ // For back-to-back characters that need to be escaped, specifically for the SIMD code paths, this method
135
+ // will be called just before calling escape_UTF8_char_basic. There will be no characters to append for the
136
+ // consecutive characters that need to be escaped. While the fbuffer_append is a no-op if
137
+ // nothing needs to be flushed, we can save a few memory references with this conditional.
138
+ if (search->ptr > search->cursor) {
139
+ fbuffer_append(search->buffer, search->cursor, search->ptr - search->cursor);
140
+ search->cursor = search->ptr;
141
+ }
142
+ }
143
+
144
+ static const unsigned char escape_table_basic[256] = {
145
+ // ASCII Control Characters
146
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
147
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
148
+ // ASCII Characters
149
+ 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // '"'
150
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
151
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
152
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, // '\\'
153
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
154
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
155
+ };
156
+
157
+ static inline unsigned char search_escape_basic(search_state *search)
158
+ {
159
+ while (search->ptr < search->end) {
160
+ if (RB_UNLIKELY(escape_table_basic[(const unsigned char)*search->ptr])) {
161
+ search_flush(search);
162
+ return 1;
163
+ } else {
164
+ search->ptr++;
165
+ }
166
+ }
167
+ search_flush(search);
168
+ return 0;
169
+ }
170
+
171
+ ALWAYS_INLINE(static) void escape_UTF8_char_basic(search_state *search)
172
+ {
173
+ const unsigned char ch = (unsigned char)*search->ptr;
174
+ switch (ch) {
175
+ case '"': fbuffer_append(search->buffer, "\\\"", 2); break;
176
+ case '\\': fbuffer_append(search->buffer, "\\\\", 2); break;
177
+ case '/': fbuffer_append(search->buffer, "\\/", 2); break;
178
+ case '\b': fbuffer_append(search->buffer, "\\b", 2); break;
179
+ case '\f': fbuffer_append(search->buffer, "\\f", 2); break;
180
+ case '\n': fbuffer_append(search->buffer, "\\n", 2); break;
181
+ case '\r': fbuffer_append(search->buffer, "\\r", 2); break;
182
+ case '\t': fbuffer_append(search->buffer, "\\t", 2); break;
183
+ default: {
184
+ const char *hexdig = "0123456789abcdef";
185
+ char scratch[6] = { '\\', 'u', '0', '0', 0, 0 };
186
+ scratch[4] = hexdig[(ch >> 4) & 0xf];
187
+ scratch[5] = hexdig[ch & 0xf];
188
+ fbuffer_append(search->buffer, scratch, 6);
189
+ break;
190
+ }
191
+ }
192
+ search->ptr++;
193
+ search->cursor = search->ptr;
194
+ }
66
195
 
67
- /*
68
- * Document-module: JSON::Ext::Generator
196
+ /* Converts in_string to a JSON string (without the wrapping '"'
197
+ * characters) in FBuffer out_buffer.
69
198
  *
70
- * This is the JSON generator implemented as a C extension. It can be
71
- * configured to be used by setting
199
+ * Character are JSON-escaped according to:
72
200
  *
73
- * JSON.generator = JSON::Ext::Generator
201
+ * - Always: ASCII control characters (0x00-0x1F), dquote, and
202
+ * backslash.
74
203
  *
75
- * with the method generator= in JSON.
204
+ * - If out_ascii_only: non-ASCII characters (>0x7F)
76
205
  *
206
+ * - If script_safe: forwardslash (/), line separator (U+2028), and
207
+ * paragraph separator (U+2029)
208
+ *
209
+ * Everything else (should be UTF-8) is just passed through and
210
+ * appended to the result.
77
211
  */
78
212
 
79
- static int hash_to_json_state_i(VALUE key, VALUE value, VALUE Vstate)
80
- {
81
- VALUE json, buf, Vdepth;
82
- GET_STATE(Vstate);
83
- buf = state->memo;
84
- Vdepth = state->depth;
85
-
86
- if (key == Qundef) return ST_CONTINUE;
87
- if (state->flag) {
88
- state->flag = 0;
89
- rb_str_buf_cat2(buf, ",");
90
- if (RSTRING_LEN(state->object_nl)) rb_str_buf_append(buf, state->object_nl);
91
- }
92
- if (RSTRING_LEN(state->object_nl)) {
93
- rb_str_buf_append(buf, rb_str_times(state->indent, Vdepth));
94
- }
95
- json = rb_funcall(rb_funcall(key, i_to_s, 0), i_to_json, 2, Vstate, Vdepth);
96
- Check_Type(json, T_STRING);
97
- rb_str_buf_append(buf, json);
98
- OBJ_INFECT(buf, json);
99
- if (RSTRING_LEN(state->space_before)) {
100
- rb_str_buf_append(buf, state->space_before);
101
- }
102
- rb_str_buf_cat2(buf, ":");
103
- if (RSTRING_LEN(state->space)) rb_str_buf_append(buf, state->space);
104
- json = rb_funcall(value, i_to_json, 2, Vstate, Vdepth);
105
- Check_Type(json, T_STRING);
106
- state->flag = 1;
107
- rb_str_buf_append(buf, json);
108
- OBJ_INFECT(buf, json);
109
- state->depth = Vdepth;
110
- state->memo = buf;
111
- return ST_CONTINUE;
213
+
214
+ #if defined(HAVE_SIMD_NEON)
215
+ static inline unsigned char search_escape_basic_neon(search_state *search);
216
+ #elif defined(HAVE_SIMD_SSE2)
217
+ static inline unsigned char search_escape_basic_sse2(search_state *search);
218
+ #endif
219
+
220
+ static inline unsigned char search_escape_basic(search_state *search);
221
+
222
+ static inline void convert_UTF8_to_JSON(search_state *search)
223
+ {
224
+ #ifdef HAVE_SIMD
225
+ #if defined(HAVE_SIMD_NEON)
226
+ while (search_escape_basic_neon(search)) {
227
+ escape_UTF8_char_basic(search);
228
+ }
229
+ #elif defined(HAVE_SIMD_SSE2)
230
+ if (simd_impl == SIMD_SSE2) {
231
+ while (search_escape_basic_sse2(search)) {
232
+ escape_UTF8_char_basic(search);
233
+ }
234
+ return;
235
+ }
236
+ while (search_escape_basic(search)) {
237
+ escape_UTF8_char_basic(search);
238
+ }
239
+ #endif
240
+ #else
241
+ while (search_escape_basic(search)) {
242
+ escape_UTF8_char_basic(search);
243
+ }
244
+ #endif /* HAVE_SIMD */
112
245
  }
113
246
 
114
- inline static VALUE mHash_json_transfrom(VALUE self, VALUE Vstate, VALUE Vdepth) {
115
- long depth, len = RHASH_SIZE(self);
116
- VALUE result;
117
- GET_STATE(Vstate);
247
+ static inline void escape_UTF8_char(search_state *search, unsigned char ch_len)
248
+ {
249
+ const unsigned char ch = (unsigned char)*search->ptr;
250
+ switch (ch_len) {
251
+ case 1: {
252
+ switch (ch) {
253
+ case '"': fbuffer_append(search->buffer, "\\\"", 2); break;
254
+ case '\\': fbuffer_append(search->buffer, "\\\\", 2); break;
255
+ case '/': fbuffer_append(search->buffer, "\\/", 2); break;
256
+ case '\b': fbuffer_append(search->buffer, "\\b", 2); break;
257
+ case '\f': fbuffer_append(search->buffer, "\\f", 2); break;
258
+ case '\n': fbuffer_append(search->buffer, "\\n", 2); break;
259
+ case '\r': fbuffer_append(search->buffer, "\\r", 2); break;
260
+ case '\t': fbuffer_append(search->buffer, "\\t", 2); break;
261
+ default: {
262
+ const char *hexdig = "0123456789abcdef";
263
+ char scratch[6] = { '\\', 'u', '0', '0', 0, 0 };
264
+ scratch[4] = hexdig[(ch >> 4) & 0xf];
265
+ scratch[5] = hexdig[ch & 0xf];
266
+ fbuffer_append(search->buffer, scratch, 6);
267
+ break;
268
+ }
269
+ }
270
+ break;
271
+ }
272
+ case 3: {
273
+ if (search->ptr[2] & 1) {
274
+ fbuffer_append(search->buffer, "\\u2029", 6);
275
+ } else {
276
+ fbuffer_append(search->buffer, "\\u2028", 6);
277
+ }
278
+ break;
279
+ }
280
+ }
281
+ search->cursor = (search->ptr += ch_len);
282
+ }
118
283
 
119
- depth = 1 + FIX2LONG(Vdepth);
120
- result = rb_str_buf_new(len);
121
- state->memo = result;
122
- state->depth = LONG2FIX(depth);
123
- state->flag = 0;
124
- rb_str_buf_cat2(result, "{");
125
- if (RSTRING_LEN(state->object_nl)) rb_str_buf_append(result, state->object_nl);
126
- rb_hash_foreach(self, hash_to_json_state_i, Vstate);
127
- if (RSTRING_LEN(state->object_nl)) rb_str_buf_append(result, state->object_nl);
128
- if (RSTRING_LEN(state->object_nl)) {
129
- rb_str_buf_append(result, rb_str_times(state->indent, Vdepth));
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);
130
310
  }
131
- rb_str_buf_cat2(result, "}");
132
- return result;
311
+
312
+ return s;
133
313
  }
134
314
 
135
- static int hash_to_json_i(VALUE key, VALUE value, VALUE buf)
315
+ #ifdef HAVE_SIMD_NEON
316
+
317
+ ALWAYS_INLINE(static) unsigned char neon_next_match(search_state *search)
136
318
  {
137
- VALUE tmp;
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
+ }
138
334
 
139
- if (key == Qundef) return ST_CONTINUE;
140
- if (RSTRING_LEN(buf) > 1) rb_str_buf_cat2(buf, ",");
141
- tmp = rb_funcall(rb_funcall(key, i_to_s, 0), i_to_json, 0);
142
- Check_Type(tmp, T_STRING);
143
- rb_str_buf_append(buf, tmp);
144
- OBJ_INFECT(buf, tmp);
145
- rb_str_buf_cat2(buf, ":");
146
- tmp = rb_funcall(value, i_to_json, 0);
147
- Check_Type(tmp, T_STRING);
148
- rb_str_buf_append(buf, tmp);
149
- OBJ_INFECT(buf, tmp);
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
+ }
150
348
 
151
- return ST_CONTINUE;
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;
152
426
  }
427
+ #endif /* HAVE_SIMD_NEON */
153
428
 
154
- /*
155
- * call-seq: to_json(state = nil, depth = 0)
156
- *
157
- * Returns a JSON string containing a JSON object, that is unparsed from
158
- * this Hash instance.
159
- * _state_ is a JSON::State object, that can also be used to configure the
160
- * produced JSON string output further.
161
- * _depth_ is used to find out nesting depth, to indent accordingly.
162
- */
163
- static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self)
429
+ #ifdef HAVE_SIMD_SSE2
430
+
431
+ ALWAYS_INLINE(static) unsigned char sse2_next_match(search_state *search)
164
432
  {
165
- VALUE Vstate, Vdepth, result;
166
- long depth;
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
+ }
167
448
 
168
- rb_scan_args(argc, argv, "02", &Vstate, &Vdepth);
169
- depth = NIL_P(Vdepth) ? 0 : FIX2LONG(Vdepth);
170
- if (NIL_P(Vstate)) {
171
- long len = RHASH_SIZE(self);
172
- result = rb_str_buf_new(len);
173
- rb_str_buf_cat2(result, "{");
174
- rb_hash_foreach(self, hash_to_json_i, result);
175
- rb_str_buf_cat2(result, "}");
176
- } else {
177
- GET_STATE(Vstate);
178
- check_max_nesting(state, depth);
179
- if (state->check_circular) {
180
- VALUE self_id = rb_obj_id(self);
181
- if (RTEST(rb_hash_aref(state->seen, self_id))) {
182
- rb_raise(eCircularDatastructure,
183
- "circular data structures not supported!");
184
- }
185
- rb_hash_aset(state->seen, self_id, Qtrue);
186
- result = mHash_json_transfrom(self, Vstate, LONG2FIX(depth));
187
- rb_hash_delete(state->seen, self_id);
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);
188
461
  } else {
189
- result = mHash_json_transfrom(self, Vstate, LONG2FIX(depth));
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
+ }
190
470
  }
191
471
  }
192
- OBJ_INFECT(result, self);
193
- FORCE_UTF8(result);
194
- return result;
195
- }
196
-
197
- inline static VALUE mArray_json_transfrom(VALUE self, VALUE Vstate, VALUE Vdepth) {
198
- long i, len = RARRAY_LEN(self);
199
- VALUE shift, result;
200
- long depth = NIL_P(Vdepth) ? 0 : FIX2LONG(Vdepth);
201
- VALUE delim = rb_str_new2(",");
202
- GET_STATE(Vstate);
203
-
204
- check_max_nesting(state, depth);
205
- if (state->check_circular) {
206
- VALUE self_id = rb_obj_id(self);
207
- rb_hash_aset(state->seen, self_id, Qtrue);
208
- result = rb_str_buf_new(len);
209
- if (RSTRING_LEN(state->array_nl)) rb_str_append(delim, state->array_nl);
210
- shift = rb_str_times(state->indent, LONG2FIX(depth + 1));
211
-
212
- rb_str_buf_cat2(result, "[");
213
- OBJ_INFECT(result, self);
214
- rb_str_buf_append(result, state->array_nl);
215
- for (i = 0; i < len; i++) {
216
- VALUE element = RARRAY_PTR(self)[i];
217
- if (RTEST(rb_hash_aref(state->seen, rb_obj_id(element)))) {
218
- rb_raise(eCircularDatastructure,
219
- "circular data structures not supported!");
472
+
473
+ if (string_scan_simd_sse2(&search->ptr, search->end, &search->matches_mask)) {
474
+ search->has_matches = true;
475
+ search->chunk_base = search->ptr;
476
+ search->chunk_end = search->ptr + sizeof(__m128i);
477
+ return sse2_next_match(search);
478
+ }
479
+
480
+ // There are fewer than 16 bytes left.
481
+ unsigned long remaining = (search->end - search->ptr);
482
+ if (remaining >= SIMD_MINIMUM_THRESHOLD) {
483
+ char *s = copy_remaining_bytes(search, sizeof(__m128i), remaining);
484
+
485
+ int needs_escape_mask = compute_chunk_mask_sse2(s);
486
+
487
+ if (needs_escape_mask == 0) {
488
+ // Nothing to escape, ensure search_flush doesn't do anything by setting
489
+ // search->cursor to search->ptr.
490
+ fbuffer_consumed(search->buffer, remaining);
491
+ search->ptr = search->end;
492
+ search->cursor = search->end;
493
+ return 0;
494
+ }
495
+
496
+ search->has_matches = true;
497
+ search->matches_mask = needs_escape_mask;
498
+ search->chunk_base = search->ptr;
499
+ return sse2_next_match(search);
500
+ }
501
+
502
+ if (search->ptr < search->end) {
503
+ return search_escape_basic(search);
504
+ }
505
+
506
+ search_flush(search);
507
+ return 0;
508
+ }
509
+
510
+ #endif /* HAVE_SIMD_SSE2 */
511
+
512
+ #endif /* HAVE_SIMD */
513
+
514
+ static const unsigned char script_safe_escape_table[256] = {
515
+ // ASCII Control Characters
516
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
517
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
518
+ // ASCII Characters
519
+ 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, // '"' and '/'
520
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
521
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
522
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, // '\\'
523
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
524
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
525
+ // Continuation byte
526
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
527
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
528
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
529
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
530
+ // First byte of a 2-byte code point
531
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
532
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
533
+ // First byte of a 3-byte code point
534
+ 3, 3,11, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xE2 is the start of \u2028 and \u2029
535
+ //First byte of a 4+ byte code point
536
+ 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 9, 9,
537
+ };
538
+
539
+ static inline unsigned char search_script_safe_escape(search_state *search)
540
+ {
541
+ while (search->ptr < search->end) {
542
+ unsigned char ch = (unsigned char)*search->ptr;
543
+ unsigned char ch_len = script_safe_escape_table[ch];
544
+
545
+ if (RB_UNLIKELY(ch_len)) {
546
+ if (ch_len & ESCAPE_MASK) {
547
+ if (RB_UNLIKELY(ch_len == 11)) {
548
+ const unsigned char *uptr = (const unsigned char *)search->ptr;
549
+ if (!(uptr[1] == 0x80 && (uptr[2] >> 1) == 0x54)) {
550
+ search->ptr += 3;
551
+ continue;
552
+ }
553
+ }
554
+ search_flush(search);
555
+ return ch_len & CHAR_LENGTH_MASK;
556
+ } else {
557
+ search->ptr += ch_len;
220
558
  }
221
- OBJ_INFECT(result, element);
222
- if (i > 0) rb_str_buf_append(result, delim);
223
- rb_str_buf_append(result, shift);
224
- element = rb_funcall(element, i_to_json, 2, Vstate, LONG2FIX(depth + 1));
225
- Check_Type(element, T_STRING);
226
- rb_str_buf_append(result, element);
559
+ } else {
560
+ search->ptr++;
227
561
  }
228
- if (RSTRING_LEN(state->array_nl)) {
229
- rb_str_buf_append(result, state->array_nl);
230
- rb_str_buf_append(result, rb_str_times(state->indent, LONG2FIX(depth)));
562
+ }
563
+ search_flush(search);
564
+ return 0;
565
+ }
566
+
567
+ static void convert_UTF8_to_script_safe_JSON(search_state *search)
568
+ {
569
+ unsigned char ch_len;
570
+ while ((ch_len = search_script_safe_escape(search))) {
571
+ escape_UTF8_char(search, ch_len);
572
+ }
573
+ }
574
+
575
+ static const unsigned char ascii_only_escape_table[256] = {
576
+ // ASCII Control Characters
577
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
578
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
579
+ // ASCII Characters
580
+ 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // '"'
581
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
582
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
583
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, // '\\'
584
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
585
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
586
+ // Continuation byte
587
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
588
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
589
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
590
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
591
+ // First byte of a 2-byte code point
592
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
593
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
594
+ // First byte of a 3-byte code point
595
+ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
596
+ //First byte of a 4+ byte code point
597
+ 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 9, 9,
598
+ };
599
+
600
+ static inline unsigned char search_ascii_only_escape(search_state *search, const unsigned char escape_table[256])
601
+ {
602
+ while (search->ptr < search->end) {
603
+ unsigned char ch = (unsigned char)*search->ptr;
604
+ unsigned char ch_len = escape_table[ch];
605
+
606
+ if (RB_UNLIKELY(ch_len)) {
607
+ search_flush(search);
608
+ return ch_len & CHAR_LENGTH_MASK;
609
+ } else {
610
+ search->ptr++;
231
611
  }
232
- rb_str_buf_cat2(result, "]");
233
- rb_hash_delete(state->seen, self_id);
234
- } else {
235
- result = rb_str_buf_new(len);
236
- OBJ_INFECT(result, self);
237
- if (RSTRING_LEN(state->array_nl)) rb_str_append(delim, state->array_nl);
238
- shift = rb_str_times(state->indent, LONG2FIX(depth + 1));
239
-
240
- rb_str_buf_cat2(result, "[");
241
- rb_str_buf_append(result, state->array_nl);
242
- for (i = 0; i < len; i++) {
243
- VALUE element = RARRAY_PTR(self)[i];
244
- OBJ_INFECT(result, element);
245
- if (i > 0) rb_str_buf_append(result, delim);
246
- rb_str_buf_append(result, shift);
247
- element = rb_funcall(element, i_to_json, 2, Vstate, LONG2FIX(depth + 1));
248
- Check_Type(element, T_STRING);
249
- rb_str_buf_append(result, element);
612
+ }
613
+ search_flush(search);
614
+ return 0;
615
+ }
616
+
617
+ static inline void full_escape_UTF8_char(search_state *search, unsigned char ch_len)
618
+ {
619
+ const unsigned char ch = (unsigned char)*search->ptr;
620
+ switch (ch_len) {
621
+ case 1: {
622
+ switch (ch) {
623
+ case '"': fbuffer_append(search->buffer, "\\\"", 2); break;
624
+ case '\\': fbuffer_append(search->buffer, "\\\\", 2); break;
625
+ case '/': fbuffer_append(search->buffer, "\\/", 2); break;
626
+ case '\b': fbuffer_append(search->buffer, "\\b", 2); break;
627
+ case '\f': fbuffer_append(search->buffer, "\\f", 2); break;
628
+ case '\n': fbuffer_append(search->buffer, "\\n", 2); break;
629
+ case '\r': fbuffer_append(search->buffer, "\\r", 2); break;
630
+ case '\t': fbuffer_append(search->buffer, "\\t", 2); break;
631
+ default: {
632
+ const char *hexdig = "0123456789abcdef";
633
+ char scratch[6] = { '\\', 'u', '0', '0', 0, 0 };
634
+ scratch[4] = hexdig[(ch >> 4) & 0xf];
635
+ scratch[5] = hexdig[ch & 0xf];
636
+ fbuffer_append(search->buffer, scratch, 6);
637
+ break;
638
+ }
639
+ }
640
+ break;
250
641
  }
251
- rb_str_buf_append(result, state->array_nl);
252
- if (RSTRING_LEN(state->array_nl)) {
253
- rb_str_buf_append(result, rb_str_times(state->indent, LONG2FIX(depth)));
642
+ default: {
643
+ const char *hexdig = "0123456789abcdef";
644
+ char scratch[12] = { '\\', 'u', 0, 0, 0, 0, '\\', 'u' };
645
+
646
+ uint32_t wchar = 0;
647
+
648
+ switch (ch_len) {
649
+ case 2:
650
+ wchar = ch & 0x1F;
651
+ break;
652
+ case 3:
653
+ wchar = ch & 0x0F;
654
+ break;
655
+ case 4:
656
+ wchar = ch & 0x07;
657
+ break;
658
+ }
659
+
660
+ for (short i = 1; i < ch_len; i++) {
661
+ wchar = (wchar << 6) | (search->ptr[i] & 0x3F);
662
+ }
663
+
664
+ if (wchar <= 0xFFFF) {
665
+ scratch[2] = hexdig[wchar >> 12];
666
+ scratch[3] = hexdig[(wchar >> 8) & 0xf];
667
+ scratch[4] = hexdig[(wchar >> 4) & 0xf];
668
+ scratch[5] = hexdig[wchar & 0xf];
669
+ fbuffer_append(search->buffer, scratch, 6);
670
+ } else {
671
+ uint16_t hi, lo;
672
+ wchar -= 0x10000;
673
+ hi = 0xD800 + (uint16_t)(wchar >> 10);
674
+ lo = 0xDC00 + (uint16_t)(wchar & 0x3FF);
675
+
676
+ scratch[2] = hexdig[hi >> 12];
677
+ scratch[3] = hexdig[(hi >> 8) & 0xf];
678
+ scratch[4] = hexdig[(hi >> 4) & 0xf];
679
+ scratch[5] = hexdig[hi & 0xf];
680
+
681
+ scratch[8] = hexdig[lo >> 12];
682
+ scratch[9] = hexdig[(lo >> 8) & 0xf];
683
+ scratch[10] = hexdig[(lo >> 4) & 0xf];
684
+ scratch[11] = hexdig[lo & 0xf];
685
+
686
+ fbuffer_append(search->buffer, scratch, 12);
687
+ }
688
+
689
+ break;
254
690
  }
255
- rb_str_buf_cat2(result, "]");
256
691
  }
257
- return result;
692
+ search->cursor = (search->ptr += ch_len);
258
693
  }
259
694
 
260
- /*
261
- * call-seq: to_json(state = nil, depth = 0)
262
- *
263
- * Returns a JSON string containing a JSON array, that is unparsed from
264
- * this Array instance.
265
- * _state_ is a JSON::State object, that can also be used to configure the
266
- * produced JSON string output further.
267
- * _depth_ is used to find out nesting depth, to indent accordingly.
268
- */
269
- static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self) {
270
- VALUE Vstate, Vdepth, result;
271
-
272
- rb_scan_args(argc, argv, "02", &Vstate, &Vdepth);
273
- if (NIL_P(Vstate)) {
274
- long i, len = RARRAY_LEN(self);
275
- result = rb_str_buf_new(2 + 2 * len);
276
- rb_str_buf_cat2(result, "[");
277
- OBJ_INFECT(result, self);
278
- for (i = 0; i < len; i++) {
279
- VALUE element = RARRAY_PTR(self)[i];
280
- OBJ_INFECT(result, element);
281
- if (i > 0) rb_str_buf_cat2(result, ",");
282
- element = rb_funcall(element, i_to_json, 0);
283
- Check_Type(element, T_STRING);
284
- rb_str_buf_append(result, element);
695
+ static void convert_UTF8_to_ASCII_only_JSON(search_state *search, const unsigned char escape_table[256])
696
+ {
697
+ unsigned char ch_len;
698
+ while ((ch_len = search_ascii_only_escape(search, escape_table))) {
699
+ full_escape_UTF8_char(search, ch_len);
700
+ }
701
+ }
702
+
703
+ static void State_mark(void *ptr)
704
+ {
705
+ JSON_Generator_State *state = ptr;
706
+ rb_gc_mark_movable(state->indent);
707
+ rb_gc_mark_movable(state->space);
708
+ rb_gc_mark_movable(state->space_before);
709
+ rb_gc_mark_movable(state->object_nl);
710
+ rb_gc_mark_movable(state->array_nl);
711
+ rb_gc_mark_movable(state->as_json);
712
+ }
713
+
714
+ static void State_compact(void *ptr)
715
+ {
716
+ JSON_Generator_State *state = ptr;
717
+ state->indent = rb_gc_location(state->indent);
718
+ state->space = rb_gc_location(state->space);
719
+ state->space_before = rb_gc_location(state->space_before);
720
+ state->object_nl = rb_gc_location(state->object_nl);
721
+ state->array_nl = rb_gc_location(state->array_nl);
722
+ state->as_json = rb_gc_location(state->as_json);
723
+ }
724
+
725
+ static size_t State_memsize(const void *ptr)
726
+ {
727
+ return sizeof(JSON_Generator_State);
728
+ }
729
+
730
+ static const rb_data_type_t JSON_Generator_State_type = {
731
+ .wrap_struct_name = "JSON/Generator/State",
732
+ .function = {
733
+ .dmark = State_mark,
734
+ .dfree = RUBY_DEFAULT_FREE,
735
+ .dsize = State_memsize,
736
+ .dcompact = State_compact,
737
+ },
738
+ .flags = RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE | RUBY_TYPED_EMBEDDABLE,
739
+ };
740
+
741
+ static void state_init(JSON_Generator_State *state)
742
+ {
743
+ state->max_nesting = 100;
744
+ state->buffer_initial_length = FBUFFER_INITIAL_LENGTH_DEFAULT;
745
+ }
746
+
747
+ static VALUE cState_s_allocate(VALUE klass)
748
+ {
749
+ JSON_Generator_State *state;
750
+ VALUE obj = TypedData_Make_Struct(klass, JSON_Generator_State, &JSON_Generator_State_type, state);
751
+ state_init(state);
752
+ return obj;
753
+ }
754
+
755
+ static void vstate_spill(struct generate_json_data *data)
756
+ {
757
+ VALUE vstate = cState_s_allocate(cState);
758
+ GET_STATE(vstate);
759
+ MEMCPY(state, data->state, JSON_Generator_State, 1);
760
+ data->state = state;
761
+ data->vstate = vstate;
762
+ RB_OBJ_WRITTEN(vstate, Qundef, state->indent);
763
+ RB_OBJ_WRITTEN(vstate, Qundef, state->space);
764
+ RB_OBJ_WRITTEN(vstate, Qundef, state->space_before);
765
+ RB_OBJ_WRITTEN(vstate, Qundef, state->object_nl);
766
+ RB_OBJ_WRITTEN(vstate, Qundef, state->array_nl);
767
+ RB_OBJ_WRITTEN(vstate, Qundef, state->as_json);
768
+ }
769
+
770
+ static inline VALUE json_call_to_json(struct generate_json_data *data, VALUE obj)
771
+ {
772
+ if (RB_UNLIKELY(!data->vstate)) {
773
+ vstate_spill(data);
774
+ }
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;
285
876
  }
286
- rb_str_buf_cat2(result, "]");
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);
932
+ }
933
+
934
+ struct hash_foreach_arg {
935
+ VALUE hash;
936
+ struct generate_json_data *data;
937
+ int first_key_type;
938
+ bool first;
939
+ bool mixed_keys_encountered;
940
+ };
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
+
957
+ static int
958
+ json_object_i(VALUE key, VALUE val, VALUE _arg)
959
+ {
960
+ struct hash_foreach_arg *arg = (struct hash_foreach_arg *)_arg;
961
+ struct generate_json_data *data = arg->data;
962
+
963
+ FBuffer *buffer = data->buffer;
964
+ JSON_Generator_State *state = data->state;
965
+
966
+ long depth = data->depth;
967
+ int key_type = rb_type(key);
968
+
969
+ if (arg->first) {
970
+ arg->first = false;
971
+ arg->first_key_type = key_type;
972
+ }
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);
982
+ }
983
+
984
+ VALUE key_to_s;
985
+ bool as_json_called = false;
986
+
987
+ start:
988
+ switch (key_type) {
989
+ case T_STRING:
990
+ if (RB_UNLIKELY(arg->first_key_type != T_STRING)) {
991
+ json_inspect_hash_with_mixed_keys(arg);
992
+ }
993
+
994
+ if (RB_LIKELY(RBASIC_CLASS(key) == rb_cString)) {
995
+ key_to_s = key;
996
+ } else {
997
+ key_to_s = convert_string_subclass(key);
998
+ }
999
+ break;
1000
+ case T_SYMBOL:
1001
+ if (RB_UNLIKELY(arg->first_key_type != T_SYMBOL)) {
1002
+ json_inspect_hash_with_mixed_keys(arg);
1003
+ }
1004
+
1005
+ key_to_s = rb_sym2str(key);
1006
+ break;
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
+ }
1018
+ key_to_s = rb_convert_type(key, T_STRING, "String", "to_s");
1019
+ break;
1020
+ }
1021
+
1022
+ key_to_s = ensure_valid_encoding(data, key_to_s, as_json_called, true);
1023
+
1024
+ if (RB_LIKELY(RBASIC_CLASS(key_to_s) == rb_cString)) {
1025
+ raw_generate_json_string(buffer, data, key_to_s);
287
1026
  } else {
288
- result = mArray_json_transfrom(self, Vstate, Vdepth);
1027
+ generate_json(buffer, data, key_to_s);
289
1028
  }
290
- OBJ_INFECT(result, self);
291
- FORCE_UTF8(result);
292
- return result;
1029
+ if (RB_UNLIKELY(state->space_before)) fbuffer_append_str(buffer, data->state->space_before);
1030
+ fbuffer_append_char(buffer, ':');
1031
+ if (RB_UNLIKELY(state->space)) fbuffer_append_str(buffer, data->state->space);
1032
+ generate_json(buffer, data, val);
1033
+
1034
+ return ST_CONTINUE;
293
1035
  }
294
1036
 
295
- /*
296
- * call-seq: to_json(*)
297
- *
298
- * Returns a JSON string representation for this Integer number.
299
- */
300
- static VALUE mInteger_to_json(int argc, VALUE *argv, VALUE self)
1037
+ static inline long increase_depth(struct generate_json_data *data)
1038
+ {
1039
+ JSON_Generator_State *state = data->state;
1040
+ long depth = ++data->depth;
1041
+ if (RB_UNLIKELY(depth > state->max_nesting && state->max_nesting)) {
1042
+ rb_raise(eNestingError, "nesting of %ld is too deep. Did you try to serialize objects with circular references?", --data->depth);
1043
+ }
1044
+ return depth;
1045
+ }
1046
+
1047
+ static void generate_json_object(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
301
1048
  {
302
- VALUE result = rb_funcall(self, i_to_s, 0);
303
- FORCE_UTF8(result);
304
- return result;
1049
+ long depth = increase_depth(data);
1050
+
1051
+ if (RHASH_SIZE(obj) == 0) {
1052
+ fbuffer_append(buffer, "{}", 2);
1053
+ --data->depth;
1054
+ return;
1055
+ }
1056
+
1057
+ fbuffer_append_char(buffer, '{');
1058
+
1059
+ struct hash_foreach_arg arg = {
1060
+ .hash = obj,
1061
+ .data = data,
1062
+ .first = true,
1063
+ };
1064
+ rb_hash_foreach(obj, json_object_i, (VALUE)&arg);
1065
+
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);
1071
+ }
1072
+ }
1073
+ fbuffer_append_char(buffer, '}');
305
1074
  }
306
1075
 
307
- /*
308
- * call-seq: to_json(*)
309
- *
310
- * Returns a JSON string representation for this Float number.
311
- */
312
- static VALUE mFloat_to_json(int argc, VALUE *argv, VALUE self)
313
- {
314
- JSON_Generator_State *state = NULL;
315
- VALUE Vstate, rest, tmp, result;
316
- double value = RFLOAT_VALUE(self);
317
- rb_scan_args(argc, argv, "01*", &Vstate, &rest);
318
- if (!NIL_P(Vstate)) Data_Get_Struct(Vstate, JSON_Generator_State, state);
319
- if (isinf(value)) {
320
- if (state && state->allow_nan) {
321
- result = rb_funcall(self, i_to_s, 0);
322
- } else {
323
- tmp = rb_funcall(self, i_to_s, 0);
324
- rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp));
1076
+ static void generate_json_array(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1077
+ {
1078
+ long depth = increase_depth(data);
1079
+
1080
+ if (RARRAY_LEN(obj) == 0) {
1081
+ fbuffer_append(buffer, "[]", 2);
1082
+ --data->depth;
1083
+ return;
1084
+ }
1085
+
1086
+ fbuffer_append_char(buffer, '[');
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++) {
1089
+ if (i > 0) {
1090
+ fbuffer_append_char(buffer, ',');
1091
+ if (RB_UNLIKELY(data->state->array_nl)) fbuffer_append_str(buffer, data->state->array_nl);
325
1092
  }
326
- } else if (isnan(value)) {
327
- if (state && state->allow_nan) {
328
- result = rb_funcall(self, i_to_s, 0);
329
- } else {
330
- tmp = rb_funcall(self, i_to_s, 0);
331
- rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp));
1093
+ if (RB_UNLIKELY(data->state->indent)) {
1094
+ fbuffer_append_str_repeat(buffer, data->state->indent, depth);
1095
+ }
1096
+ generate_json(buffer, data, RARRAY_AREF(obj, i));
1097
+ }
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);
332
1103
  }
333
- } else {
334
- result = rb_funcall(self, i_to_s, 0);
335
1104
  }
336
- FORCE_UTF8(result);
337
- return result;
1105
+ fbuffer_append_char(buffer, ']');
338
1106
  }
339
1107
 
340
- /*
341
- * call-seq: String.included(modul)
342
- *
343
- * Extends _modul_ with the String::Extend module.
344
- */
345
- static VALUE mString_included_s(VALUE self, VALUE modul) {
346
- VALUE result = rb_funcall(modul, i_extend, 1, mString_Extend);
347
- FORCE_UTF8(result);
348
- return result;
1108
+ static void generate_json_fallback(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1109
+ {
1110
+ VALUE tmp;
1111
+ if (rb_respond_to(obj, i_to_json)) {
1112
+ tmp = json_call_to_json(data, obj);
1113
+ Check_Type(tmp, T_STRING);
1114
+ fbuffer_append_str(buffer, tmp);
1115
+ } else {
1116
+ tmp = rb_funcall(obj, i_to_s, 0);
1117
+ Check_Type(tmp, T_STRING);
1118
+ generate_json_string(buffer, data, tmp);
1119
+ }
349
1120
  }
350
1121
 
351
- /*
352
- * call-seq: to_json(*)
353
- *
354
- * This string should be encoded with UTF-8 A call to this method
355
- * returns a JSON string encoded with UTF16 big endian characters as
356
- * \u????.
357
- */
358
- static VALUE mString_to_json(int argc, VALUE *argv, VALUE self)
1122
+ static inline void generate_json_symbol(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
359
1123
  {
360
- VALUE result = rb_str_buf_new(RSTRING_LEN(self));
361
- rb_str_buf_cat2(result, "\"");
362
- #ifdef HAVE_RUBY_ENCODING_H
363
- if (rb_funcall(self, i_encoding, 0) == mEncoding_UTF_8) {
364
- JSON_convert_UTF8_to_JSON(result, self, strictConversion);
1124
+ if (data->state->strict) {
1125
+ generate_json_string(buffer, data, rb_sym2str(obj));
365
1126
  } else {
366
- VALUE string = rb_funcall(self, i_encode, 1, mEncoding_UTF_8);
367
- JSON_convert_UTF8_to_JSON(result, string, strictConversion);
1127
+ generate_json_fallback(buffer, data, obj);
368
1128
  }
369
- #else
370
- JSON_convert_UTF8_to_JSON(result, self, strictConversion);
371
- #endif
372
- rb_str_buf_cat2(result, "\"");
373
- FORCE_UTF8(result);
374
- return result;
375
1129
  }
376
1130
 
377
- /*
378
- * call-seq: to_json_raw_object()
379
- *
380
- * This method creates a raw object hash, that can be nested into
381
- * other data structures and will be unparsed as a raw string. This
382
- * method should be used, if you want to convert raw strings to JSON
383
- * instead of UTF-8 strings, e. g. binary data.
384
- */
385
- static VALUE mString_to_json_raw_object(VALUE self) {
386
- VALUE ary;
387
- VALUE result = rb_hash_new();
388
- rb_hash_aset(result, rb_funcall(mJSON, i_create_id, 0), rb_class_name(rb_obj_class(self)));
389
- ary = rb_funcall(self, i_unpack, 1, rb_str_new2("C*"));
390
- rb_hash_aset(result, rb_str_new2("raw"), ary);
391
- FORCE_UTF8(result);
392
- return result;
1131
+ static void generate_json_null(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1132
+ {
1133
+ fbuffer_append(buffer, "null", 4);
393
1134
  }
394
1135
 
395
- /*
396
- * call-seq: to_json_raw(*args)
397
- *
398
- * This method creates a JSON text from the result of a call to
399
- * to_json_raw_object of this String.
400
- */
401
- static VALUE mString_to_json_raw(int argc, VALUE *argv, VALUE self) {
402
- VALUE result, obj = mString_to_json_raw_object(self);
403
- Check_Type(obj, T_HASH);
404
- result = mHash_to_json(argc, argv, obj);
405
- FORCE_UTF8(result);
406
- return result;
1136
+ static void generate_json_false(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1137
+ {
1138
+ fbuffer_append(buffer, "false", 5);
407
1139
  }
408
1140
 
409
- /*
410
- * call-seq: json_create(o)
411
- *
412
- * Raw Strings are JSON Objects (the raw bytes are stored in an array for the
413
- * key "raw"). The Ruby String can be created by this module method.
414
- */
415
- static VALUE mString_Extend_json_create(VALUE self, VALUE o) {
416
- VALUE ary;
417
- Check_Type(o, T_HASH);
418
- ary = rb_hash_aref(o, rb_str_new2("raw"));
419
- return rb_funcall(ary, i_pack, 1, rb_str_new2("C*"));
1141
+ static void generate_json_true(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
1142
+ {
1143
+ fbuffer_append(buffer, "true", 4);
420
1144
  }
421
1145
 
422
- /*
423
- * call-seq: to_json(*)
424
- *
425
- * Returns a JSON string for true: 'true'.
426
- */
427
- static VALUE mTrueClass_to_json(int argc, VALUE *argv, VALUE self)
1146
+ static void generate_json_fixnum(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
428
1147
  {
429
- VALUE result = rb_str_new2("true");
430
- FORCE_UTF8(result);
431
- return result;
1148
+ fbuffer_append_long(buffer, FIX2LONG(obj));
432
1149
  }
433
1150
 
434
- /*
435
- * call-seq: to_json(*)
436
- *
437
- * Returns a JSON string for false: 'false'.
438
- */
439
- static VALUE mFalseClass_to_json(int argc, VALUE *argv, VALUE self)
1151
+ static void generate_json_bignum(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
440
1152
  {
441
- VALUE result = rb_str_new2("false");
442
- FORCE_UTF8(result);
443
- return result;
1153
+ VALUE tmp = rb_funcall(obj, i_to_s, 0);
1154
+ fbuffer_append_str(buffer, StringValue(tmp));
444
1155
  }
445
1156
 
446
- /*
447
- * call-seq: to_json(*)
448
- *
449
- */
450
- static VALUE mNilClass_to_json(int argc, VALUE *argv, VALUE self)
1157
+ static void generate_json_float(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
451
1158
  {
452
- VALUE result = rb_str_new2("null");
453
- FORCE_UTF8(result);
454
- return result;
1159
+ double value = RFLOAT_VALUE(obj);
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);
1166
+ if (casted_obj != obj) {
1167
+ increase_depth(data);
1168
+ generate_json(buffer, data, casted_obj);
1169
+ data->depth--;
1170
+ return;
1171
+ }
1172
+ }
1173
+ raise_generator_error(obj, "%"PRIsVALUE" not allowed in JSON", rb_funcall(obj, i_to_s, 0));
1174
+ }
1175
+
1176
+ VALUE tmp = rb_funcall(obj, i_to_s, 0);
1177
+ fbuffer_append_str(buffer, tmp);
1178
+ return;
1179
+ }
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);
455
1191
  }
456
1192
 
457
- /*
458
- * call-seq: to_json(*)
459
- *
460
- * Converts this object to a string (calling #to_s), converts
461
- * it to a JSON string, and returns the result. This is a fallback, if no
462
- * special method #to_json was defined for some object.
463
- */
464
- static VALUE mObject_to_json(int argc, VALUE *argv, VALUE self)
1193
+ static void generate_json_fragment(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
465
1194
  {
466
- VALUE result, string = rb_funcall(self, i_to_s, 0);
467
- Check_Type(string, T_STRING);
468
- result = mString_to_json(argc, argv, string);
469
- FORCE_UTF8(result);
470
- return result;
1195
+ VALUE fragment = RSTRUCT_GET(obj, 0);
1196
+ Check_Type(fragment, T_STRING);
1197
+ fbuffer_append_str(buffer, fragment);
471
1198
  }
472
1199
 
473
- /*
474
- * Document-class: JSON::Ext::Generator::State
475
- *
476
- * This class is used to create State instances, that are use to hold data
477
- * while generating a JSON text from a a Ruby data structure.
478
- */
1200
+ static inline void generate_json_general(FBuffer *buffer, struct generate_json_data *data, VALUE obj, bool fallback)
1201
+ {
1202
+ bool as_json_called = false;
1203
+ start:
1204
+ if (obj == Qnil) {
1205
+ generate_json_null(buffer, data, obj);
1206
+ } else if (obj == Qfalse) {
1207
+ generate_json_false(buffer, data, obj);
1208
+ } else if (obj == Qtrue) {
1209
+ generate_json_true(buffer, data, obj);
1210
+ } else if (RB_SPECIAL_CONST_P(obj)) {
1211
+ if (RB_FIXNUM_P(obj)) {
1212
+ generate_json_fixnum(buffer, data, obj);
1213
+ } else if (RB_FLONUM_P(obj)) {
1214
+ generate_json_float(buffer, data, obj);
1215
+ } else if (RB_STATIC_SYM_P(obj)) {
1216
+ generate_json_symbol(buffer, data, obj);
1217
+ } else {
1218
+ goto general;
1219
+ }
1220
+ } else {
1221
+ VALUE klass = RBASIC_CLASS(obj);
1222
+ switch (RB_BUILTIN_TYPE(obj)) {
1223
+ case T_BIGNUM:
1224
+ generate_json_bignum(buffer, data, obj);
1225
+ break;
1226
+ case T_HASH:
1227
+ if (fallback && klass != rb_cHash) goto general;
1228
+ generate_json_object(buffer, data, obj);
1229
+ break;
1230
+ case T_ARRAY:
1231
+ if (fallback && klass != rb_cArray) goto general;
1232
+ generate_json_array(buffer, data, obj);
1233
+ break;
1234
+ case T_STRING:
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
+ }
1246
+ break;
1247
+ case T_SYMBOL:
1248
+ generate_json_symbol(buffer, data, obj);
1249
+ break;
1250
+ case T_FLOAT:
1251
+ if (fallback && klass != rb_cFloat) goto general;
1252
+ generate_json_float(buffer, data, obj);
1253
+ break;
1254
+ case T_STRUCT:
1255
+ if (klass != cFragment) goto general;
1256
+ generate_json_fragment(buffer, data, obj);
1257
+ break;
1258
+ default:
1259
+ general:
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);
1263
+ as_json_called = true;
1264
+ goto start;
1265
+ } else {
1266
+ raise_generator_error(obj, "%"PRIsVALUE" not allowed in JSON", CLASS_OF(obj));
1267
+ }
1268
+ } else {
1269
+ generate_json_fallback(buffer, data, obj);
1270
+ }
1271
+ }
1272
+ }
1273
+ }
479
1274
 
480
- static void State_mark(JSON_Generator_State *state)
1275
+ static void generate_json(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
481
1276
  {
482
- rb_gc_mark_maybe(state->indent);
483
- rb_gc_mark_maybe(state->space);
484
- rb_gc_mark_maybe(state->space_before);
485
- rb_gc_mark_maybe(state->object_nl);
486
- rb_gc_mark_maybe(state->array_nl);
487
- rb_gc_mark_maybe(state->seen);
488
- rb_gc_mark_maybe(state->memo);
489
- rb_gc_mark_maybe(state->depth);
1277
+ generate_json_general(buffer, data, obj, true);
490
1278
  }
491
1279
 
492
- static JSON_Generator_State *State_allocate()
1280
+ static void generate_json_no_fallback(FBuffer *buffer, struct generate_json_data *data, VALUE obj)
493
1281
  {
494
- JSON_Generator_State *state = ALLOC(JSON_Generator_State);
495
- return state;
1282
+ generate_json_general(buffer, data, obj, false);
496
1283
  }
497
1284
 
498
- static VALUE cState_s_allocate(VALUE klass)
1285
+ static VALUE generate_json_try(VALUE d)
499
1286
  {
500
- JSON_Generator_State *state = State_allocate();
501
- return Data_Wrap_Struct(klass, State_mark, -1, state);
1287
+ struct generate_json_data *data = (struct generate_json_data *)d;
1288
+
1289
+ data->func(data->buffer, data, data->obj);
1290
+
1291
+ return fbuffer_finalize(data->buffer);
502
1292
  }
503
1293
 
504
- /*
505
- * call-seq: configure(opts)
506
- *
507
- * Configure this State instance with the Hash _opts_, and return
508
- * itself.
509
- */
510
- static VALUE cState_configure(VALUE self, VALUE opts)
1294
+ static VALUE generate_json_ensure(VALUE d)
1295
+ {
1296
+ struct generate_json_data *data = (struct generate_json_data *)d;
1297
+ fbuffer_free(data->buffer);
1298
+
1299
+ return Qundef;
1300
+ }
1301
+
1302
+ static inline VALUE cState_partial_generate(VALUE self, VALUE obj, generator_func func, VALUE io)
511
1303
  {
512
- VALUE tmp;
513
1304
  GET_STATE(self);
514
- tmp = rb_convert_type(opts, T_HASH, "Hash", "to_hash");
515
- if (NIL_P(tmp)) tmp = rb_convert_type(opts, T_HASH, "Hash", "to_h");
516
- if (NIL_P(tmp)) {
517
- rb_raise(rb_eArgError, "opts has to be hash like or convertable into a hash");
518
- }
519
- opts = tmp;
520
- tmp = rb_hash_aref(opts, ID2SYM(i_indent));
521
- if (RTEST(tmp)) {
522
- Check_Type(tmp, T_STRING);
523
- state->indent = tmp;
524
- }
525
- tmp = rb_hash_aref(opts, ID2SYM(i_space));
526
- if (RTEST(tmp)) {
527
- Check_Type(tmp, T_STRING);
528
- state->space = tmp;
529
- }
530
- tmp = rb_hash_aref(opts, ID2SYM(i_space_before));
531
- if (RTEST(tmp)) {
532
- Check_Type(tmp, T_STRING);
533
- state->space_before = tmp;
534
- }
535
- tmp = rb_hash_aref(opts, ID2SYM(i_array_nl));
536
- if (RTEST(tmp)) {
537
- Check_Type(tmp, T_STRING);
538
- state->array_nl = tmp;
539
- }
540
- tmp = rb_hash_aref(opts, ID2SYM(i_object_nl));
541
- if (RTEST(tmp)) {
542
- Check_Type(tmp, T_STRING);
543
- state->object_nl = tmp;
544
- }
545
- tmp = ID2SYM(i_check_circular);
546
- if (st_lookup(RHASH_TBL(opts), tmp, 0)) {
547
- tmp = rb_hash_aref(opts, ID2SYM(i_check_circular));
548
- state->check_circular = RTEST(tmp);
549
- } else {
550
- state->check_circular = 1;
551
- }
552
- tmp = ID2SYM(i_max_nesting);
553
- state->max_nesting = 19;
554
- if (st_lookup(RHASH_TBL(opts), tmp, 0)) {
555
- VALUE max_nesting = rb_hash_aref(opts, tmp);
556
- if (RTEST(max_nesting)) {
557
- Check_Type(max_nesting, T_FIXNUM);
558
- state->max_nesting = FIX2LONG(max_nesting);
559
- } else {
560
- state->max_nesting = 0;
561
- }
562
- }
563
- tmp = rb_hash_aref(opts, ID2SYM(i_allow_nan));
564
- state->allow_nan = RTEST(tmp);
565
- return self;
1305
+
1306
+ char stack_buffer[FBUFFER_STACK_SIZE];
1307
+ FBuffer buffer = {
1308
+ .io = RTEST(io) ? io : Qfalse,
1309
+ };
1310
+ fbuffer_stack_init(&buffer, state->buffer_initial_length, stack_buffer, FBUFFER_STACK_SIZE);
1311
+
1312
+ struct generate_json_data data = {
1313
+ .buffer = &buffer,
1314
+ .vstate = Qfalse, // don't use self as it may be frozen and its depth is mutated when calling to_json
1315
+ .state = state,
1316
+ .depth = state->depth,
1317
+ .obj = obj,
1318
+ .func = func
1319
+ };
1320
+ return rb_ensure(generate_json_try, (VALUE)&data, generate_json_ensure, (VALUE)&data);
566
1321
  }
567
1322
 
568
- /*
569
- * call-seq: to_h
1323
+ /* call-seq:
1324
+ * generate(obj) -> String
1325
+ * generate(obj, anIO) -> anIO
570
1326
  *
571
- * Returns the configuration instance variables as a hash, that can be
572
- * passed to the configure method.
1327
+ * Generates a valid JSON document from object +obj+ and returns the
1328
+ * result. If no valid JSON document can be created this method raises a
1329
+ * GeneratorError exception.
573
1330
  */
574
- static VALUE cState_to_h(VALUE self)
1331
+ static VALUE cState_generate(int argc, VALUE *argv, VALUE self)
575
1332
  {
576
- VALUE result = rb_hash_new();
577
- GET_STATE(self);
578
- rb_hash_aset(result, ID2SYM(i_indent), state->indent);
579
- rb_hash_aset(result, ID2SYM(i_space), state->space);
580
- rb_hash_aset(result, ID2SYM(i_space_before), state->space_before);
581
- rb_hash_aset(result, ID2SYM(i_object_nl), state->object_nl);
582
- rb_hash_aset(result, ID2SYM(i_array_nl), state->array_nl);
583
- rb_hash_aset(result, ID2SYM(i_check_circular), state->check_circular ? Qtrue : Qfalse);
584
- rb_hash_aset(result, ID2SYM(i_allow_nan), state->allow_nan ? Qtrue : Qfalse);
585
- rb_hash_aset(result, ID2SYM(i_max_nesting), LONG2FIX(state->max_nesting));
586
- return result;
1333
+ rb_check_arity(argc, 1, 2);
1334
+ VALUE obj = argv[0];
1335
+ VALUE io = argc > 1 ? argv[1] : Qnil;
1336
+ return cState_partial_generate(self, obj, generate_json, io);
587
1337
  }
588
1338
 
1339
+ /* :nodoc: */
1340
+ static VALUE cState_generate_no_fallback(int argc, VALUE *argv, VALUE self)
1341
+ {
1342
+ rb_check_arity(argc, 1, 2);
1343
+ VALUE obj = argv[0];
1344
+ VALUE io = argc > 1 ? argv[1] : Qnil;
1345
+ return cState_partial_generate(self, obj, generate_json_no_fallback, io);
1346
+ }
589
1347
 
590
- /*
591
- * call-seq: new(opts = {})
592
- *
593
- * Instantiates a new State object, configured by _opts_.
594
- *
595
- * _opts_ can have the following keys:
596
- *
597
- * * *indent*: a string used to indent levels (default: ''),
598
- * * *space*: a string that is put after, a : or , delimiter (default: ''),
599
- * * *space_before*: a string that is put before a : pair delimiter (default: ''),
600
- * * *object_nl*: a string that is put at the end of a JSON object (default: ''),
601
- * * *array_nl*: a string that is put at the end of a JSON array (default: ''),
602
- * * *check_circular*: true if checking for circular data structures
603
- * should be done, false (the default) otherwise.
604
- * * *allow_nan*: true if NaN, Infinity, and -Infinity should be
605
- * generated, otherwise an exception is thrown, if these values are
606
- * encountered. This options defaults to false.
607
- */
608
1348
  static VALUE cState_initialize(int argc, VALUE *argv, VALUE self)
609
1349
  {
610
- VALUE opts;
611
- GET_STATE(self);
612
-
613
- rb_scan_args(argc, argv, "01", &opts);
614
- state->indent = rb_str_new2("");
615
- state->space = rb_str_new2("");
616
- state->space_before = rb_str_new2("");
617
- state->array_nl = rb_str_new2("");
618
- state->object_nl = rb_str_new2("");
619
- if (NIL_P(opts)) {
620
- state->check_circular = 1;
621
- state->allow_nan = 0;
622
- state->max_nesting = 19;
623
- } else {
624
- cState_configure(self, opts);
625
- }
626
- state->seen = rb_hash_new();
627
- state->memo = Qnil;
628
- state->depth = INT2FIX(0);
1350
+ rb_warn("The json gem extension was loaded with the stdlib ruby code. You should upgrade rubygems with `gem update --system`");
629
1351
  return self;
630
1352
  }
631
1353
 
1354
+ /*
1355
+ * call-seq: initialize_copy(orig)
1356
+ *
1357
+ * Initializes this object from orig if it can be duplicated/cloned and returns
1358
+ * it.
1359
+ */
1360
+ static VALUE cState_init_copy(VALUE obj, VALUE orig)
1361
+ {
1362
+ JSON_Generator_State *objState, *origState;
1363
+
1364
+ if (obj == orig) return obj;
1365
+ GET_STATE_TO(obj, objState);
1366
+ GET_STATE_TO(orig, origState);
1367
+ if (!objState) rb_raise(rb_eArgError, "unallocated JSON::State");
1368
+
1369
+ MEMCPY(objState, origState, JSON_Generator_State, 1);
1370
+
1371
+ RB_OBJ_WRITTEN(obj, Qundef, objState->indent);
1372
+ RB_OBJ_WRITTEN(obj, Qundef, objState->space);
1373
+ RB_OBJ_WRITTEN(obj, Qundef, objState->space_before);
1374
+ RB_OBJ_WRITTEN(obj, Qundef, objState->object_nl);
1375
+ RB_OBJ_WRITTEN(obj, Qundef, objState->array_nl);
1376
+ RB_OBJ_WRITTEN(obj, Qundef, objState->as_json);
1377
+
1378
+ return obj;
1379
+ }
1380
+
632
1381
  /*
633
1382
  * call-seq: from_state(opts)
634
1383
  *
@@ -643,79 +1392,93 @@ static VALUE cState_from_state_s(VALUE self, VALUE opts)
643
1392
  } else if (rb_obj_is_kind_of(opts, rb_cHash)) {
644
1393
  return rb_funcall(self, i_new, 1, opts);
645
1394
  } else {
646
- return rb_funcall(self, i_new, 0);
1395
+ return rb_class_new_instance(0, NULL, cState);
647
1396
  }
648
1397
  }
649
1398
 
650
1399
  /*
651
1400
  * call-seq: indent()
652
1401
  *
653
- * This string is used to indent levels in the JSON text.
1402
+ * Returns the string that is used to indent levels in the JSON text.
654
1403
  */
655
1404
  static VALUE cState_indent(VALUE self)
656
1405
  {
657
1406
  GET_STATE(self);
658
- return state->indent;
1407
+ return state->indent ? state->indent : rb_str_freeze(rb_utf8_str_new("", 0));
1408
+ }
1409
+
1410
+ static VALUE string_config(VALUE config)
1411
+ {
1412
+ if (RTEST(config)) {
1413
+ Check_Type(config, T_STRING);
1414
+ if (RSTRING_LEN(config)) {
1415
+ return rb_str_new_frozen(config);
1416
+ }
1417
+ }
1418
+ return Qfalse;
659
1419
  }
660
1420
 
661
1421
  /*
662
1422
  * call-seq: indent=(indent)
663
1423
  *
664
- * This string is used to indent levels in the JSON text.
1424
+ * Sets the string that is used to indent levels in the JSON text.
665
1425
  */
666
1426
  static VALUE cState_indent_set(VALUE self, VALUE indent)
667
1427
  {
1428
+ rb_check_frozen(self);
668
1429
  GET_STATE(self);
669
- Check_Type(indent, T_STRING);
670
- return state->indent = indent;
1430
+ RB_OBJ_WRITE(self, &state->indent, string_config(indent));
1431
+ return Qnil;
671
1432
  }
672
1433
 
673
1434
  /*
674
1435
  * call-seq: space()
675
1436
  *
676
- * This string is used to insert a space between the tokens in a JSON
1437
+ * Returns the string that is used to insert a space between the tokens in a JSON
677
1438
  * string.
678
1439
  */
679
1440
  static VALUE cState_space(VALUE self)
680
1441
  {
681
1442
  GET_STATE(self);
682
- return state->space;
1443
+ return state->space ? state->space : rb_str_freeze(rb_utf8_str_new("", 0));
683
1444
  }
684
1445
 
685
1446
  /*
686
1447
  * call-seq: space=(space)
687
1448
  *
688
- * This string is used to insert a space between the tokens in a JSON
1449
+ * Sets _space_ to the string that is used to insert a space between the tokens in a JSON
689
1450
  * string.
690
1451
  */
691
1452
  static VALUE cState_space_set(VALUE self, VALUE space)
692
1453
  {
1454
+ rb_check_frozen(self);
693
1455
  GET_STATE(self);
694
- Check_Type(space, T_STRING);
695
- return state->space = space;
1456
+ RB_OBJ_WRITE(self, &state->space, string_config(space));
1457
+ return Qnil;
696
1458
  }
697
1459
 
698
1460
  /*
699
1461
  * call-seq: space_before()
700
1462
  *
701
- * This string is used to insert a space before the ':' in JSON objects.
1463
+ * Returns the string that is used to insert a space before the ':' in JSON objects.
702
1464
  */
703
1465
  static VALUE cState_space_before(VALUE self)
704
1466
  {
705
1467
  GET_STATE(self);
706
- return state->space_before;
1468
+ return state->space_before ? state->space_before : rb_str_freeze(rb_utf8_str_new("", 0));
707
1469
  }
708
1470
 
709
1471
  /*
710
1472
  * call-seq: space_before=(space_before)
711
1473
  *
712
- * This string is used to insert a space before the ':' in JSON objects.
1474
+ * Sets the string that is used to insert a space before the ':' in JSON objects.
713
1475
  */
714
1476
  static VALUE cState_space_before_set(VALUE self, VALUE space_before)
715
1477
  {
1478
+ rb_check_frozen(self);
716
1479
  GET_STATE(self);
717
- Check_Type(space_before, T_STRING);
718
- return state->space_before = space_before;
1480
+ RB_OBJ_WRITE(self, &state->space_before, string_config(space_before));
1481
+ return Qnil;
719
1482
  }
720
1483
 
721
1484
  /*
@@ -727,7 +1490,7 @@ static VALUE cState_space_before_set(VALUE self, VALUE space_before)
727
1490
  static VALUE cState_object_nl(VALUE self)
728
1491
  {
729
1492
  GET_STATE(self);
730
- return state->object_nl;
1493
+ return state->object_nl ? state->object_nl : rb_str_freeze(rb_utf8_str_new("", 0));
731
1494
  }
732
1495
 
733
1496
  /*
@@ -738,9 +1501,10 @@ static VALUE cState_object_nl(VALUE self)
738
1501
  */
739
1502
  static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)
740
1503
  {
1504
+ rb_check_frozen(self);
741
1505
  GET_STATE(self);
742
- Check_Type(object_nl, T_STRING);
743
- return state->object_nl = object_nl;
1506
+ RB_OBJ_WRITE(self, &state->object_nl, string_config(object_nl));
1507
+ return Qnil;
744
1508
  }
745
1509
 
746
1510
  /*
@@ -751,7 +1515,7 @@ static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)
751
1515
  static VALUE cState_array_nl(VALUE self)
752
1516
  {
753
1517
  GET_STATE(self);
754
- return state->array_nl;
1518
+ return state->array_nl ? state->array_nl : rb_str_freeze(rb_utf8_str_new("", 0));
755
1519
  }
756
1520
 
757
1521
  /*
@@ -760,22 +1524,47 @@ static VALUE cState_array_nl(VALUE self)
760
1524
  * This string is put at the end of a line that holds a JSON array.
761
1525
  */
762
1526
  static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)
1527
+ {
1528
+ rb_check_frozen(self);
1529
+ GET_STATE(self);
1530
+ RB_OBJ_WRITE(self, &state->array_nl, string_config(array_nl));
1531
+ return Qnil;
1532
+ }
1533
+
1534
+ /*
1535
+ * call-seq: as_json()
1536
+ *
1537
+ * This string is put at the end of a line that holds a JSON array.
1538
+ */
1539
+ static VALUE cState_as_json(VALUE self)
763
1540
  {
764
1541
  GET_STATE(self);
765
- Check_Type(array_nl, T_STRING);
766
- return state->array_nl = array_nl;
1542
+ return state->as_json;
767
1543
  }
768
1544
 
769
1545
  /*
770
- * call-seq: check_circular?
1546
+ * call-seq: as_json=(as_json)
771
1547
  *
772
- * Returns true, if circular data structures should be checked,
773
- * otherwise returns false.
1548
+ * This string is put at the end of a line that holds a JSON array.
774
1549
  */
1550
+ static VALUE cState_as_json_set(VALUE self, VALUE as_json)
1551
+ {
1552
+ rb_check_frozen(self);
1553
+ GET_STATE(self);
1554
+ RB_OBJ_WRITE(self, &state->as_json, rb_convert_type(as_json, T_DATA, "Proc", "to_proc"));
1555
+ return Qnil;
1556
+ }
1557
+
1558
+ /*
1559
+ * call-seq: check_circular?
1560
+ *
1561
+ * Returns true, if circular data structures should be checked,
1562
+ * otherwise returns false.
1563
+ */
775
1564
  static VALUE cState_check_circular_p(VALUE self)
776
1565
  {
777
1566
  GET_STATE(self);
778
- return state->check_circular ? Qtrue : Qfalse;
1567
+ return state->max_nesting ? Qtrue : Qfalse;
779
1568
  }
780
1569
 
781
1570
  /*
@@ -790,6 +1579,25 @@ static VALUE cState_max_nesting(VALUE self)
790
1579
  return LONG2FIX(state->max_nesting);
791
1580
  }
792
1581
 
1582
+ static long long_config(VALUE num)
1583
+ {
1584
+ return RTEST(num) ? NUM2LONG(num) : 0;
1585
+ }
1586
+
1587
+ // depth must never be negative; reject early with a clear error.
1588
+ static long depth_config(VALUE num)
1589
+ {
1590
+ if (!RTEST(num)) return 0;
1591
+ long d = NUM2LONG(num);
1592
+ if (RB_UNLIKELY(d < 0)) {
1593
+ rb_raise(rb_eArgError, "depth must be >= 0 (got %ld)", d);
1594
+ }
1595
+ if (RB_UNLIKELY(d > INT_MAX)) {
1596
+ rb_raise(rb_eArgError, "depth is too large (got %ld)", d);
1597
+ }
1598
+ return d;
1599
+ }
1600
+
793
1601
  /*
794
1602
  * call-seq: max_nesting=(depth)
795
1603
  *
@@ -797,10 +1605,68 @@ static VALUE cState_max_nesting(VALUE self)
797
1605
  * to the integer depth, max_nesting = 0 if no maximum should be checked.
798
1606
  */
799
1607
  static VALUE cState_max_nesting_set(VALUE self, VALUE depth)
1608
+ {
1609
+ rb_check_frozen(self);
1610
+ GET_STATE(self);
1611
+ state->max_nesting = long_config(depth);
1612
+ return Qnil;
1613
+ }
1614
+
1615
+ /*
1616
+ * call-seq: script_safe
1617
+ *
1618
+ * If this boolean is true, the forward slashes will be escaped in
1619
+ * the json output.
1620
+ */
1621
+ static VALUE cState_script_safe(VALUE self)
1622
+ {
1623
+ GET_STATE(self);
1624
+ return state->script_safe ? Qtrue : Qfalse;
1625
+ }
1626
+
1627
+ /*
1628
+ * call-seq: script_safe=(enable)
1629
+ *
1630
+ * This sets whether or not the forward slashes will be escaped in
1631
+ * the json output.
1632
+ */
1633
+ static VALUE cState_script_safe_set(VALUE self, VALUE enable)
1634
+ {
1635
+ rb_check_frozen(self);
1636
+ GET_STATE(self);
1637
+ state->script_safe = RTEST(enable);
1638
+ return Qnil;
1639
+ }
1640
+
1641
+ /*
1642
+ * call-seq: strict
1643
+ *
1644
+ * If this boolean is false, types unsupported by the JSON format will
1645
+ * be serialized as strings.
1646
+ * If this boolean is true, types unsupported by the JSON format will
1647
+ * raise a JSON::GeneratorError.
1648
+ */
1649
+ static VALUE cState_strict(VALUE self)
800
1650
  {
801
1651
  GET_STATE(self);
802
- Check_Type(depth, T_FIXNUM);
803
- state->max_nesting = FIX2LONG(depth);
1652
+ return state->strict ? Qtrue : Qfalse;
1653
+ }
1654
+
1655
+ /*
1656
+ * call-seq: strict=(enable)
1657
+ *
1658
+ * This sets whether or not to serialize types unsupported by the
1659
+ * JSON format as strings.
1660
+ * If this boolean is false, types unsupported by the JSON format will
1661
+ * be serialized as strings.
1662
+ * If this boolean is true, types unsupported by the JSON format will
1663
+ * raise a JSON::GeneratorError.
1664
+ */
1665
+ static VALUE cState_strict_set(VALUE self, VALUE enable)
1666
+ {
1667
+ rb_check_frozen(self);
1668
+ GET_STATE(self);
1669
+ state->strict = RTEST(enable);
804
1670
  return Qnil;
805
1671
  }
806
1672
 
@@ -817,56 +1683,246 @@ static VALUE cState_allow_nan_p(VALUE self)
817
1683
  }
818
1684
 
819
1685
  /*
820
- * call-seq: seen?(object)
1686
+ * call-seq: allow_nan=(enable)
1687
+ *
1688
+ * This sets whether or not to serialize NaN, Infinity, and -Infinity
1689
+ */
1690
+ static VALUE cState_allow_nan_set(VALUE self, VALUE enable)
1691
+ {
1692
+ rb_check_frozen(self);
1693
+ GET_STATE(self);
1694
+ state->allow_nan = RTEST(enable);
1695
+ return Qnil;
1696
+ }
1697
+
1698
+ /*
1699
+ * call-seq: ascii_only?
1700
+ *
1701
+ * Returns true, if only ASCII characters should be generated. Otherwise
1702
+ * returns false.
1703
+ */
1704
+ static VALUE cState_ascii_only_p(VALUE self)
1705
+ {
1706
+ GET_STATE(self);
1707
+ return state->ascii_only ? Qtrue : Qfalse;
1708
+ }
1709
+
1710
+ /*
1711
+ * call-seq: ascii_only=(enable)
1712
+ *
1713
+ * This sets whether only ASCII characters should be generated.
1714
+ */
1715
+ static VALUE cState_ascii_only_set(VALUE self, VALUE enable)
1716
+ {
1717
+ rb_check_frozen(self);
1718
+ GET_STATE(self);
1719
+ state->ascii_only = RTEST(enable);
1720
+ return Qnil;
1721
+ }
1722
+
1723
+ static VALUE cState_allow_duplicate_key_p(VALUE self)
1724
+ {
1725
+ GET_STATE(self);
1726
+ switch (state->on_duplicate_key) {
1727
+ case JSON_IGNORE:
1728
+ return Qtrue;
1729
+ case JSON_DEPRECATED:
1730
+ return Qnil;
1731
+ default:
1732
+ return Qfalse;
1733
+ }
1734
+ }
1735
+
1736
+ /*
1737
+ * call-seq: depth
821
1738
  *
822
- * Returns _true_, if _object_ was already seen during this generating run.
1739
+ * This integer returns the current depth of data structure nesting.
823
1740
  */
824
- static VALUE cState_seen_p(VALUE self, VALUE object)
1741
+ static VALUE cState_depth(VALUE self)
825
1742
  {
826
1743
  GET_STATE(self);
827
- return rb_hash_aref(state->seen, rb_obj_id(object));
1744
+ return LONG2FIX(state->depth);
828
1745
  }
829
1746
 
830
1747
  /*
831
- * call-seq: remember(object)
1748
+ * call-seq: depth=(depth)
832
1749
  *
833
- * Remember _object_, to find out if it was already encountered (if a cyclic
834
- * data structure is rendered).
1750
+ * This sets the maximum level of data structure nesting in the generated JSON
1751
+ * to the integer depth, max_nesting = 0 if no maximum should be checked.
835
1752
  */
836
- static VALUE cState_remember(VALUE self, VALUE object)
1753
+ static VALUE cState_depth_set(VALUE self, VALUE depth)
837
1754
  {
1755
+ rb_check_frozen(self);
838
1756
  GET_STATE(self);
839
- return rb_hash_aset(state->seen, rb_obj_id(object), Qtrue);
1757
+ state->depth = depth_config(depth);
1758
+ return Qnil;
840
1759
  }
841
1760
 
842
1761
  /*
843
- * call-seq: forget(object)
1762
+ * call-seq: buffer_initial_length
844
1763
  *
845
- * Forget _object_ for this generating run.
1764
+ * This integer returns the current initial length of the buffer.
846
1765
  */
847
- static VALUE cState_forget(VALUE self, VALUE object)
1766
+ static VALUE cState_buffer_initial_length(VALUE self)
848
1767
  {
849
1768
  GET_STATE(self);
850
- return rb_hash_delete(state->seen, rb_obj_id(object));
1769
+ return LONG2FIX(state->buffer_initial_length);
1770
+ }
1771
+
1772
+ static void buffer_initial_length_set(JSON_Generator_State *state, VALUE buffer_initial_length)
1773
+ {
1774
+ Check_Type(buffer_initial_length, T_FIXNUM);
1775
+ long initial_length = FIX2LONG(buffer_initial_length);
1776
+ if (initial_length > 0) {
1777
+ state->buffer_initial_length = initial_length;
1778
+ }
851
1779
  }
852
1780
 
853
1781
  /*
1782
+ * call-seq: buffer_initial_length=(length)
854
1783
  *
1784
+ * This sets the initial length of the buffer to +length+, if +length+ > 0,
1785
+ * otherwise its value isn't changed.
855
1786
  */
856
- void Init_generator()
1787
+ static VALUE cState_buffer_initial_length_set(VALUE self, VALUE buffer_initial_length)
1788
+ {
1789
+ rb_check_frozen(self);
1790
+ GET_STATE(self);
1791
+ buffer_initial_length_set(state, buffer_initial_length);
1792
+ return Qnil;
1793
+ }
1794
+
1795
+ struct configure_state_data {
1796
+ JSON_Generator_State *state;
1797
+ VALUE vstate; // Ruby object that owns the state, or Qfalse if stack-allocated
1798
+ };
1799
+
1800
+ static inline void state_write_value(struct configure_state_data *data, VALUE *field, VALUE value)
1801
+ {
1802
+ if (RTEST(data->vstate)) {
1803
+ RB_OBJ_WRITE(data->vstate, field, value);
1804
+ } else {
1805
+ *field = value;
1806
+ }
1807
+ }
1808
+
1809
+ static int configure_state_i(VALUE key, VALUE val, VALUE _arg)
1810
+ {
1811
+ struct configure_state_data *data = (struct configure_state_data *)_arg;
1812
+ JSON_Generator_State *state = data->state;
1813
+
1814
+ if (key == sym_indent) { state_write_value(data, &state->indent, string_config(val)); }
1815
+ else if (key == sym_space) { state_write_value(data, &state->space, string_config(val)); }
1816
+ else if (key == sym_space_before) { state_write_value(data, &state->space_before, string_config(val)); }
1817
+ else if (key == sym_object_nl) { state_write_value(data, &state->object_nl, string_config(val)); }
1818
+ else if (key == sym_array_nl) { state_write_value(data, &state->array_nl, string_config(val)); }
1819
+ else if (key == sym_max_nesting) { state->max_nesting = long_config(val); }
1820
+ else if (key == sym_allow_nan) { state->allow_nan = RTEST(val); }
1821
+ else if (key == sym_ascii_only) { state->ascii_only = RTEST(val); }
1822
+ else if (key == sym_depth) { state->depth = depth_config(val); }
1823
+ else if (key == sym_buffer_initial_length) { buffer_initial_length_set(state, val); }
1824
+ else if (key == sym_script_safe) { state->script_safe = RTEST(val); }
1825
+ else if (key == sym_escape_slash) { state->script_safe = RTEST(val); }
1826
+ else if (key == sym_strict) { state->strict = RTEST(val); }
1827
+ else if (key == sym_allow_duplicate_key) { state->on_duplicate_key = RTEST(val) ? JSON_IGNORE : JSON_RAISE; }
1828
+ else if (key == sym_as_json) {
1829
+ VALUE proc = RTEST(val) ? rb_convert_type(val, T_DATA, "Proc", "to_proc") : Qfalse;
1830
+ state->as_json_single_arg = proc && rb_proc_arity(proc) == 1;
1831
+ state_write_value(data, &state->as_json, proc);
1832
+ }
1833
+ return ST_CONTINUE;
1834
+ }
1835
+
1836
+ static void configure_state(JSON_Generator_State *state, VALUE vstate, VALUE config)
1837
+ {
1838
+ if (!RTEST(config)) return;
1839
+
1840
+ Check_Type(config, T_HASH);
1841
+
1842
+ if (!RHASH_SIZE(config)) return;
1843
+
1844
+ struct configure_state_data data = {
1845
+ .state = state,
1846
+ .vstate = vstate
1847
+ };
1848
+
1849
+ // We assume in most cases few keys are set so it's faster to go over
1850
+ // the provided keys than to check all possible keys.
1851
+ rb_hash_foreach(config, configure_state_i, (VALUE)&data);
1852
+ }
1853
+
1854
+ static VALUE cState_configure(VALUE self, VALUE opts)
1855
+ {
1856
+ rb_check_frozen(self);
1857
+ GET_STATE(self);
1858
+ configure_state(state, self, opts);
1859
+ return self;
1860
+ }
1861
+
1862
+ static VALUE cState_m_do_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io, generator_func func)
1863
+ {
1864
+ JSON_Generator_State state = {0};
1865
+ state_init(&state);
1866
+ configure_state(&state, Qfalse, opts);
1867
+
1868
+ char stack_buffer[FBUFFER_STACK_SIZE];
1869
+ FBuffer buffer = {
1870
+ .io = RTEST(io) ? io : Qfalse,
1871
+ };
1872
+ fbuffer_stack_init(&buffer, state.buffer_initial_length, stack_buffer, FBUFFER_STACK_SIZE);
1873
+
1874
+ struct generate_json_data data = {
1875
+ .buffer = &buffer,
1876
+ .vstate = Qfalse,
1877
+ .state = &state,
1878
+ .depth = state.depth,
1879
+ .obj = obj,
1880
+ .func = func,
1881
+ };
1882
+ return rb_ensure(generate_json_try, (VALUE)&data, generate_json_ensure, (VALUE)&data);
1883
+ }
1884
+
1885
+ static VALUE cState_m_generate(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1886
+ {
1887
+ return cState_m_do_generate(klass, obj, opts, io, generate_json);
1888
+ }
1889
+
1890
+ static VALUE cState_m_generate_no_fallback(VALUE klass, VALUE obj, VALUE opts, VALUE io)
1891
+ {
1892
+ return cState_m_do_generate(klass, obj, opts, io, generate_json_no_fallback);
1893
+ }
1894
+
1895
+ void Init_generator(void)
857
1896
  {
1897
+ #ifdef HAVE_RB_EXT_RACTOR_SAFE
1898
+ rb_ext_ractor_safe(true);
1899
+ #endif
1900
+
1901
+ #undef rb_intern
858
1902
  rb_require("json/common");
1903
+
859
1904
  mJSON = rb_define_module("JSON");
860
- mExt = rb_define_module_under(mJSON, "Ext");
861
- mGenerator = rb_define_module_under(mExt, "Generator");
1905
+
1906
+ rb_global_variable(&cFragment);
1907
+ cFragment = rb_const_get(mJSON, rb_intern("Fragment"));
1908
+
1909
+ VALUE mExt = rb_define_module_under(mJSON, "Ext");
1910
+ VALUE mGenerator = rb_define_module_under(mExt, "Generator");
1911
+
1912
+ rb_global_variable(&eGeneratorError);
862
1913
  eGeneratorError = rb_path2class("JSON::GeneratorError");
863
- eCircularDatastructure = rb_path2class("JSON::CircularDatastructure");
1914
+
1915
+ rb_global_variable(&eNestingError);
864
1916
  eNestingError = rb_path2class("JSON::NestingError");
1917
+
865
1918
  cState = rb_define_class_under(mGenerator, "State", rb_cObject);
866
1919
  rb_define_alloc_func(cState, cState_s_allocate);
867
1920
  rb_define_singleton_method(cState, "from_state", cState_from_state_s, 1);
868
1921
  rb_define_method(cState, "initialize", cState_initialize, -1);
1922
+ rb_define_alias(cState, "initialize", "initialize"); // avoid method redefinition warnings
1923
+ rb_define_private_method(cState, "_configure", cState_configure, 1);
869
1924
 
1925
+ rb_define_method(cState, "initialize_copy", cState_init_copy, 1);
870
1926
  rb_define_method(cState, "indent", cState_indent, 0);
871
1927
  rb_define_method(cState, "indent=", cState_indent_set, 1);
872
1928
  rb_define_method(cState, "space", cState_space, 0);
@@ -877,59 +1933,65 @@ void Init_generator()
877
1933
  rb_define_method(cState, "object_nl=", cState_object_nl_set, 1);
878
1934
  rb_define_method(cState, "array_nl", cState_array_nl, 0);
879
1935
  rb_define_method(cState, "array_nl=", cState_array_nl_set, 1);
880
- rb_define_method(cState, "check_circular?", cState_check_circular_p, 0);
1936
+ rb_define_method(cState, "as_json", cState_as_json, 0);
1937
+ rb_define_method(cState, "as_json=", cState_as_json_set, 1);
881
1938
  rb_define_method(cState, "max_nesting", cState_max_nesting, 0);
882
1939
  rb_define_method(cState, "max_nesting=", cState_max_nesting_set, 1);
1940
+ rb_define_method(cState, "script_safe", cState_script_safe, 0);
1941
+ rb_define_method(cState, "script_safe?", cState_script_safe, 0);
1942
+ rb_define_method(cState, "script_safe=", cState_script_safe_set, 1);
1943
+ rb_define_alias(cState, "escape_slash", "script_safe");
1944
+ rb_define_alias(cState, "escape_slash?", "script_safe?");
1945
+ rb_define_alias(cState, "escape_slash=", "script_safe=");
1946
+ rb_define_method(cState, "strict", cState_strict, 0);
1947
+ rb_define_method(cState, "strict?", cState_strict, 0);
1948
+ rb_define_method(cState, "strict=", cState_strict_set, 1);
1949
+ rb_define_method(cState, "check_circular?", cState_check_circular_p, 0);
883
1950
  rb_define_method(cState, "allow_nan?", cState_allow_nan_p, 0);
884
- rb_define_method(cState, "seen?", cState_seen_p, 1);
885
- rb_define_method(cState, "remember", cState_remember, 1);
886
- rb_define_method(cState, "forget", cState_forget, 1);
887
- rb_define_method(cState, "configure", cState_configure, 1);
888
- rb_define_method(cState, "to_h", cState_to_h, 0);
889
-
890
- mGeneratorMethods = rb_define_module_under(mGenerator, "GeneratorMethods");
891
- mObject = rb_define_module_under(mGeneratorMethods, "Object");
892
- rb_define_method(mObject, "to_json", mObject_to_json, -1);
893
- mHash = rb_define_module_under(mGeneratorMethods, "Hash");
894
- rb_define_method(mHash, "to_json", mHash_to_json, -1);
895
- mArray = rb_define_module_under(mGeneratorMethods, "Array");
896
- rb_define_method(mArray, "to_json", mArray_to_json, -1);
897
- mInteger = rb_define_module_under(mGeneratorMethods, "Integer");
898
- rb_define_method(mInteger, "to_json", mInteger_to_json, -1);
899
- mFloat = rb_define_module_under(mGeneratorMethods, "Float");
900
- rb_define_method(mFloat, "to_json", mFloat_to_json, -1);
901
- mString = rb_define_module_under(mGeneratorMethods, "String");
902
- rb_define_singleton_method(mString, "included", mString_included_s, 1);
903
- rb_define_method(mString, "to_json", mString_to_json, -1);
904
- rb_define_method(mString, "to_json_raw", mString_to_json_raw, -1);
905
- rb_define_method(mString, "to_json_raw_object", mString_to_json_raw_object, 0);
906
- mString_Extend = rb_define_module_under(mString, "Extend");
907
- rb_define_method(mString_Extend, "json_create", mString_Extend_json_create, 1);
908
- mTrueClass = rb_define_module_under(mGeneratorMethods, "TrueClass");
909
- rb_define_method(mTrueClass, "to_json", mTrueClass_to_json, -1);
910
- mFalseClass = rb_define_module_under(mGeneratorMethods, "FalseClass");
911
- rb_define_method(mFalseClass, "to_json", mFalseClass_to_json, -1);
912
- mNilClass = rb_define_module_under(mGeneratorMethods, "NilClass");
913
- rb_define_method(mNilClass, "to_json", mNilClass_to_json, -1);
1951
+ rb_define_method(cState, "allow_nan=", cState_allow_nan_set, 1);
1952
+ rb_define_method(cState, "ascii_only?", cState_ascii_only_p, 0);
1953
+ rb_define_method(cState, "ascii_only=", cState_ascii_only_set, 1);
1954
+ rb_define_method(cState, "depth", cState_depth, 0);
1955
+ rb_define_method(cState, "depth=", cState_depth_set, 1);
1956
+ rb_define_method(cState, "buffer_initial_length", cState_buffer_initial_length, 0);
1957
+ rb_define_method(cState, "buffer_initial_length=", cState_buffer_initial_length_set, 1);
1958
+ rb_define_method(cState, "generate", cState_generate, -1);
1959
+ rb_define_method(cState, "_generate_no_fallback", cState_generate_no_fallback, -1);
1960
+
1961
+ rb_define_private_method(cState, "allow_duplicate_key?", cState_allow_duplicate_key_p, 0);
1962
+
1963
+ rb_define_singleton_method(cState, "generate", cState_m_generate, 3);
1964
+ rb_define_singleton_method(cState, "_generate_no_fallback", cState_m_generate_no_fallback, 3);
1965
+
1966
+ rb_global_variable(&Encoding_UTF_8);
1967
+ Encoding_UTF_8 = rb_const_get(rb_path2class("Encoding"), rb_intern("UTF_8"));
914
1968
 
915
1969
  i_to_s = rb_intern("to_s");
916
1970
  i_to_json = rb_intern("to_json");
917
1971
  i_new = rb_intern("new");
918
- i_indent = rb_intern("indent");
919
- i_space = rb_intern("space");
920
- i_space_before = rb_intern("space_before");
921
- i_object_nl = rb_intern("object_nl");
922
- i_array_nl = rb_intern("array_nl");
923
- i_check_circular = rb_intern("check_circular");
924
- i_max_nesting = rb_intern("max_nesting");
925
- i_allow_nan = rb_intern("allow_nan");
926
- i_pack = rb_intern("pack");
927
- i_unpack = rb_intern("unpack");
928
- i_create_id = rb_intern("create_id");
929
- i_extend = rb_intern("extend");
930
- #ifdef HAVE_RUBY_ENCODING_H
931
- mEncoding_UTF_8 = rb_funcall(rb_path2class("Encoding"), rb_intern("find"), 1, rb_str_new2("utf-8"));
932
- i_encoding = rb_intern("encoding");
933
1972
  i_encode = rb_intern("encode");
934
- #endif
1973
+
1974
+ sym_indent = ID2SYM(rb_intern("indent"));
1975
+ sym_space = ID2SYM(rb_intern("space"));
1976
+ sym_space_before = ID2SYM(rb_intern("space_before"));
1977
+ sym_object_nl = ID2SYM(rb_intern("object_nl"));
1978
+ sym_array_nl = ID2SYM(rb_intern("array_nl"));
1979
+ sym_max_nesting = ID2SYM(rb_intern("max_nesting"));
1980
+ sym_allow_nan = ID2SYM(rb_intern("allow_nan"));
1981
+ sym_ascii_only = ID2SYM(rb_intern("ascii_only"));
1982
+ sym_depth = ID2SYM(rb_intern("depth"));
1983
+ sym_buffer_initial_length = ID2SYM(rb_intern("buffer_initial_length"));
1984
+ sym_script_safe = ID2SYM(rb_intern("script_safe"));
1985
+ sym_escape_slash = ID2SYM(rb_intern("escape_slash"));
1986
+ sym_strict = ID2SYM(rb_intern("strict"));
1987
+ sym_as_json = ID2SYM(rb_intern("as_json"));
1988
+ sym_allow_duplicate_key = ID2SYM(rb_intern("allow_duplicate_key"));
1989
+
1990
+ usascii_encindex = rb_usascii_encindex();
1991
+ utf8_encindex = rb_utf8_encindex();
1992
+ binary_encindex = rb_ascii8bit_encindex();
1993
+
1994
+ rb_require("json/ext/generator/state");
1995
+
1996
+ simd_impl = find_simd_implementation();
935
1997
  }