Ruby 3.0.5p211 (2022-11-24 revision ba5cf0f7c52d4d35cc6a173c89eda98ceffa2dcf)
generator.c
Go to the documentation of this file.
1#include "../fbuffer/fbuffer.h"
2#include "generator.h"
3
4#ifdef HAVE_RUBY_ENCODING_H
5static VALUE CEncoding_UTF_8;
6static ID i_encoding, i_encode;
7#endif
8
9static VALUE mJSON, mExt, mGenerator, cState, mGeneratorMethods, mObject,
10 mHash, mArray,
11#ifdef RUBY_INTEGER_UNIFICATION
12 mInteger,
13#else
14 mFixnum, mBignum,
15#endif
16 mFloat, mString, mString_Extend,
17 mTrueClass, mFalseClass, mNilClass, eGeneratorError,
18 eNestingError;
19
20static ID i_to_s, i_to_json, i_new, i_indent, i_space, i_space_before,
21 i_object_nl, i_array_nl, i_max_nesting, i_allow_nan, i_ascii_only,
22 i_pack, i_unpack, i_create_id, i_extend, i_key_p,
23 i_aref, i_send, i_respond_to_p, i_match, i_keys, i_depth,
24 i_buffer_initial_length, i_dup, i_escape_slash;
25
26/*
27 * Copyright 2001-2004 Unicode, Inc.
28 *
29 * Disclaimer
30 *
31 * This source code is provided as is by Unicode, Inc. No claims are
32 * made as to fitness for any particular purpose. No warranties of any
33 * kind are expressed or implied. The recipient agrees to determine
34 * applicability of information provided. If this file has been
35 * purchased on magnetic or optical media from Unicode, Inc., the
36 * sole remedy for any claim will be exchange of defective media
37 * within 90 days of receipt.
38 *
39 * Limitations on Rights to Redistribute This Code
40 *
41 * Unicode, Inc. hereby grants the right to freely use the information
42 * supplied in this file in the creation of products supporting the
43 * Unicode Standard, and to make copies of this file in any form
44 * for internal or external distribution as long as this notice
45 * remains attached.
46 */
47
48/*
49 * Index into the table below with the first byte of a UTF-8 sequence to
50 * get the number of trailing bytes that are supposed to follow it.
51 * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is
52 * left as-is for anyone who may want to do such conversion, which was
53 * allowed in earlier algorithms.
54 */
55static const char trailingBytesForUTF8[256] = {
56 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
57 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
58 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
59 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
60 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
61 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
62 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
63 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
64};
65
66/*
67 * Magic values subtracted from a buffer value during UTF8 conversion.
68 * This table contains as many values as there might be trailing bytes
69 * in a UTF-8 sequence.
70 */
71static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
72 0x03C82080UL, 0xFA082080UL, 0x82082080UL };
73
74/*
75 * Utility routine to tell whether a sequence of bytes is legal UTF-8.
76 * This must be called with the length pre-determined by the first byte.
77 * If not calling this from ConvertUTF8to*, then the length can be set by:
78 * length = trailingBytesForUTF8[*source]+1;
79 * and the sequence is illegal right away if there aren't that many bytes
80 * available.
81 * If presented with a length > 4, this returns 0. The Unicode
82 * definition of UTF-8 goes up to 4-byte sequences.
83 */
84static unsigned char isLegalUTF8(const UTF8 *source, unsigned long length)
85{
86 UTF8 a;
87 const UTF8 *srcptr = source+length;
88 switch (length) {
89 default: return 0;
90 /* Everything else falls through when "1"... */
91 case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0;
92 case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0;
93 case 2: if ((a = (*--srcptr)) > 0xBF) return 0;
94
95 switch (*source) {
96 /* no fall-through in this inner switch */
97 case 0xE0: if (a < 0xA0) return 0; break;
98 case 0xED: if (a > 0x9F) return 0; break;
99 case 0xF0: if (a < 0x90) return 0; break;
100 case 0xF4: if (a > 0x8F) return 0; break;
101 default: if (a < 0x80) return 0;
102 }
103
104 case 1: if (*source >= 0x80 && *source < 0xC2) return 0;
105 }
106 if (*source > 0xF4) return 0;
107 return 1;
108}
109
110/* Escapes the UTF16 character and stores the result in the buffer buf. */
111static void unicode_escape(char *buf, UTF16 character)
112{
113 const char *digits = "0123456789abcdef";
114
115 buf[2] = digits[character >> 12];
116 buf[3] = digits[(character >> 8) & 0xf];
117 buf[4] = digits[(character >> 4) & 0xf];
118 buf[5] = digits[character & 0xf];
119}
120
121/* Escapes the UTF16 character and stores the result in the buffer buf, then
122 * the buffer buf is appended to the FBuffer buffer. */
123static void unicode_escape_to_buffer(FBuffer *buffer, char buf[6], UTF16
124 character)
125{
126 unicode_escape(buf, character);
127 fbuffer_append(buffer, buf, 6);
128}
129
130/* Converts string to a JSON string in FBuffer buffer, where all but the ASCII
131 * and control characters are JSON escaped. */
132static void convert_UTF8_to_JSON_ASCII(FBuffer *buffer, VALUE string, char escape_slash)
133{
134 const UTF8 *source = (UTF8 *) RSTRING_PTR(string);
135 const UTF8 *sourceEnd = source + RSTRING_LEN(string);
136 char buf[6] = { '\\', 'u' };
137
138 while (source < sourceEnd) {
139 UTF32 ch = 0;
140 unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
141 if (source + extraBytesToRead >= sourceEnd) {
142 rb_raise(rb_path2class("JSON::GeneratorError"),
143 "partial character in source, but hit end");
144 }
145 if (!isLegalUTF8(source, extraBytesToRead+1)) {
146 rb_raise(rb_path2class("JSON::GeneratorError"),
147 "source sequence is illegal/malformed utf-8");
148 }
149 /*
150 * The cases all fall through. See "Note A" below.
151 */
152 switch (extraBytesToRead) {
153 case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
154 case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */
155 case 3: ch += *source++; ch <<= 6;
156 case 2: ch += *source++; ch <<= 6;
157 case 1: ch += *source++; ch <<= 6;
158 case 0: ch += *source++;
159 }
160 ch -= offsetsFromUTF8[extraBytesToRead];
161
162 if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */
163 /* UTF-16 surrogate values are illegal in UTF-32 */
164 if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) {
165#if UNI_STRICT_CONVERSION
166 source -= (extraBytesToRead+1); /* return to the illegal value itself */
167 rb_raise(rb_path2class("JSON::GeneratorError"),
168 "source sequence is illegal/malformed utf-8");
169#else
170 unicode_escape_to_buffer(buffer, buf, UNI_REPLACEMENT_CHAR);
171#endif
172 } else {
173 /* normal case */
174 if (ch >= 0x20 && ch <= 0x7f) {
175 switch (ch) {
176 case '\\':
177 fbuffer_append(buffer, "\\\\", 2);
178 break;
179 case '"':
180 fbuffer_append(buffer, "\\\"", 2);
181 break;
182 case '/':
183 if(escape_slash) {
184 fbuffer_append(buffer, "\\/", 2);
185 break;
186 }
187 default:
188 fbuffer_append_char(buffer, (char)ch);
189 break;
190 }
191 } else {
192 switch (ch) {
193 case '\n':
194 fbuffer_append(buffer, "\\n", 2);
195 break;
196 case '\r':
197 fbuffer_append(buffer, "\\r", 2);
198 break;
199 case '\t':
200 fbuffer_append(buffer, "\\t", 2);
201 break;
202 case '\f':
203 fbuffer_append(buffer, "\\f", 2);
204 break;
205 case '\b':
206 fbuffer_append(buffer, "\\b", 2);
207 break;
208 default:
209 unicode_escape_to_buffer(buffer, buf, (UTF16) ch);
210 break;
211 }
212 }
213 }
214 } else if (ch > UNI_MAX_UTF16) {
215#if UNI_STRICT_CONVERSION
216 source -= (extraBytesToRead+1); /* return to the start */
217 rb_raise(rb_path2class("JSON::GeneratorError"),
218 "source sequence is illegal/malformed utf8");
219#else
220 unicode_escape_to_buffer(buffer, buf, UNI_REPLACEMENT_CHAR);
221#endif
222 } else {
223 /* target is a character in range 0xFFFF - 0x10FFFF. */
224 ch -= halfBase;
225 unicode_escape_to_buffer(buffer, buf, (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START));
226 unicode_escape_to_buffer(buffer, buf, (UTF16)((ch & halfMask) + UNI_SUR_LOW_START));
227 }
228 }
229 RB_GC_GUARD(string);
230}
231
232/* Converts string to a JSON string in FBuffer buffer, where only the
233 * characters required by the JSON standard are JSON escaped. The remaining
234 * characters (should be UTF8) are just passed through and appended to the
235 * result. */
236static void convert_UTF8_to_JSON(FBuffer *buffer, VALUE string, char escape_slash)
237{
238 const char *ptr = RSTRING_PTR(string), *p;
239 unsigned long len = RSTRING_LEN(string), start = 0, end = 0;
240 const char *escape = NULL;
241 int escape_len;
242 unsigned char c;
243 char buf[6] = { '\\', 'u' };
244 int ascii_only = rb_enc_str_asciionly_p(string);
245
246 for (start = 0, end = 0; end < len;) {
247 p = ptr + end;
248 c = (unsigned char) *p;
249 if (c < 0x20) {
250 switch (c) {
251 case '\n':
252 escape = "\\n";
253 escape_len = 2;
254 break;
255 case '\r':
256 escape = "\\r";
257 escape_len = 2;
258 break;
259 case '\t':
260 escape = "\\t";
261 escape_len = 2;
262 break;
263 case '\f':
264 escape = "\\f";
265 escape_len = 2;
266 break;
267 case '\b':
268 escape = "\\b";
269 escape_len = 2;
270 break;
271 default:
272 unicode_escape(buf, (UTF16) *p);
273 escape = buf;
274 escape_len = 6;
275 break;
276 }
277 } else {
278 switch (c) {
279 case '\\':
280 escape = "\\\\";
281 escape_len = 2;
282 break;
283 case '"':
284 escape = "\\\"";
285 escape_len = 2;
286 break;
287 case '/':
288 if(escape_slash) {
289 escape = "\\/";
290 escape_len = 2;
291 break;
292 }
293 default:
294 {
295 unsigned short clen = 1;
296 if (!ascii_only) {
297 clen += trailingBytesForUTF8[c];
298 if (end + clen > len) {
299 rb_raise(rb_path2class("JSON::GeneratorError"),
300 "partial character in source, but hit end");
301 }
302 if (!isLegalUTF8((UTF8 *) p, clen)) {
303 rb_raise(rb_path2class("JSON::GeneratorError"),
304 "source sequence is illegal/malformed utf-8");
305 }
306 }
307 end += clen;
308 }
309 continue;
310 break;
311 }
312 }
313 fbuffer_append(buffer, ptr + start, end - start);
314 fbuffer_append(buffer, escape, escape_len);
315 start = ++end;
316 escape = NULL;
317 }
318 fbuffer_append(buffer, ptr + start, end - start);
319}
320
321static char *fstrndup(const char *ptr, unsigned long len) {
322 char *result;
323 if (len <= 0) return NULL;
324 result = ALLOC_N(char, len);
325 memcpy(result, ptr, len);
326 return result;
327}
328
329/*
330 * Document-module: JSON::Ext::Generator
331 *
332 * This is the JSON generator implemented as a C extension. It can be
333 * configured to be used by setting
334 *
335 * JSON.generator = JSON::Ext::Generator
336 *
337 * with the method generator= in JSON.
338 *
339 */
340
341/* Explanation of the following: that's the only way to not pollute
342 * standard library's docs with GeneratorMethods::<ClassName> which
343 * are uninformative and take a large place in a list of classes
344 */
345
346/*
347 * Document-module: JSON::Ext::Generator::GeneratorMethods
348 * :nodoc:
349 */
350
351/*
352 * Document-module: JSON::Ext::Generator::GeneratorMethods::Array
353 * :nodoc:
354 */
355
356/*
357 * Document-module: JSON::Ext::Generator::GeneratorMethods::Bignum
358 * :nodoc:
359 */
360
361/*
362 * Document-module: JSON::Ext::Generator::GeneratorMethods::FalseClass
363 * :nodoc:
364 */
365
366/*
367 * Document-module: JSON::Ext::Generator::GeneratorMethods::Fixnum
368 * :nodoc:
369 */
370
371/*
372 * Document-module: JSON::Ext::Generator::GeneratorMethods::Float
373 * :nodoc:
374 */
375
376/*
377 * Document-module: JSON::Ext::Generator::GeneratorMethods::Hash
378 * :nodoc:
379 */
380
381/*
382 * Document-module: JSON::Ext::Generator::GeneratorMethods::Integer
383 * :nodoc:
384 */
385
386/*
387 * Document-module: JSON::Ext::Generator::GeneratorMethods::NilClass
388 * :nodoc:
389 */
390
391/*
392 * Document-module: JSON::Ext::Generator::GeneratorMethods::Object
393 * :nodoc:
394 */
395
396/*
397 * Document-module: JSON::Ext::Generator::GeneratorMethods::String
398 * :nodoc:
399 */
400
401/*
402 * Document-module: JSON::Ext::Generator::GeneratorMethods::String::Extend
403 * :nodoc:
404 */
405
406/*
407 * Document-module: JSON::Ext::Generator::GeneratorMethods::TrueClass
408 * :nodoc:
409 */
410
411/*
412 * call-seq: to_json(state = nil)
413 *
414 * Returns a JSON string containing a JSON object, that is generated from
415 * this Hash instance.
416 * _state_ is a JSON::State object, that can also be used to configure the
417 * produced JSON string output further.
418 */
419static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self)
420{
421 GENERATE_JSON(object);
422}
423
424/*
425 * call-seq: to_json(state = nil)
426 *
427 * Returns a JSON string containing a JSON array, that is generated from
428 * this Array instance.
429 * _state_ is a JSON::State object, that can also be used to configure the
430 * produced JSON string output further.
431 */
432static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self) {
433 GENERATE_JSON(array);
434}
435
436#ifdef RUBY_INTEGER_UNIFICATION
437/*
438 * call-seq: to_json(*)
439 *
440 * Returns a JSON string representation for this Integer number.
441 */
442static VALUE mInteger_to_json(int argc, VALUE *argv, VALUE self)
443{
444 GENERATE_JSON(integer);
445}
446
447#else
448/*
449 * call-seq: to_json(*)
450 *
451 * Returns a JSON string representation for this Integer number.
452 */
453static VALUE mFixnum_to_json(int argc, VALUE *argv, VALUE self)
454{
455 GENERATE_JSON(fixnum);
456}
457
458/*
459 * call-seq: to_json(*)
460 *
461 * Returns a JSON string representation for this Integer number.
462 */
463static VALUE mBignum_to_json(int argc, VALUE *argv, VALUE self)
464{
465 GENERATE_JSON(bignum);
466}
467#endif
468
469/*
470 * call-seq: to_json(*)
471 *
472 * Returns a JSON string representation for this Float number.
473 */
474static VALUE mFloat_to_json(int argc, VALUE *argv, VALUE self)
475{
476 GENERATE_JSON(float);
477}
478
479/*
480 * call-seq: String.included(modul)
481 *
482 * Extends _modul_ with the String::Extend module.
483 */
484static VALUE mString_included_s(VALUE self, VALUE modul) {
485 VALUE result = rb_funcall(modul, i_extend, 1, mString_Extend);
486 return result;
487}
488
489/*
490 * call-seq: to_json(*)
491 *
492 * This string should be encoded with UTF-8 A call to this method
493 * returns a JSON string encoded with UTF16 big endian characters as
494 * \u????.
495 */
496static VALUE mString_to_json(int argc, VALUE *argv, VALUE self)
497{
498 GENERATE_JSON(string);
499}
500
501/*
502 * call-seq: to_json_raw_object()
503 *
504 * This method creates a raw object hash, that can be nested into
505 * other data structures and will be generated as a raw string. This
506 * method should be used, if you want to convert raw strings to JSON
507 * instead of UTF-8 strings, e. g. binary data.
508 */
509static VALUE mString_to_json_raw_object(VALUE self)
510{
511 VALUE ary;
512 VALUE result = rb_hash_new();
513 rb_hash_aset(result, rb_funcall(mJSON, i_create_id, 0), rb_class_name(rb_obj_class(self)));
514 ary = rb_funcall(self, i_unpack, 1, rb_str_new2("C*"));
515 rb_hash_aset(result, rb_str_new2("raw"), ary);
516 return result;
517}
518
519/*
520 * call-seq: to_json_raw(*args)
521 *
522 * This method creates a JSON text from the result of a call to
523 * to_json_raw_object of this String.
524 */
525static VALUE mString_to_json_raw(int argc, VALUE *argv, VALUE self)
526{
527 VALUE obj = mString_to_json_raw_object(self);
528 Check_Type(obj, T_HASH);
529 return mHash_to_json(argc, argv, obj);
530}
531
532/*
533 * call-seq: json_create(o)
534 *
535 * Raw Strings are JSON Objects (the raw bytes are stored in an array for the
536 * key "raw"). The Ruby String can be created by this module method.
537 */
538static VALUE mString_Extend_json_create(VALUE self, VALUE o)
539{
540 VALUE ary;
541 Check_Type(o, T_HASH);
542 ary = rb_hash_aref(o, rb_str_new2("raw"));
543 return rb_funcall(ary, i_pack, 1, rb_str_new2("C*"));
544}
545
546/*
547 * call-seq: to_json(*)
548 *
549 * Returns a JSON string for true: 'true'.
550 */
551static VALUE mTrueClass_to_json(int argc, VALUE *argv, VALUE self)
552{
553 GENERATE_JSON(true);
554}
555
556/*
557 * call-seq: to_json(*)
558 *
559 * Returns a JSON string for false: 'false'.
560 */
561static VALUE mFalseClass_to_json(int argc, VALUE *argv, VALUE self)
562{
563 GENERATE_JSON(false);
564}
565
566/*
567 * call-seq: to_json(*)
568 *
569 * Returns a JSON string for nil: 'null'.
570 */
571static VALUE mNilClass_to_json(int argc, VALUE *argv, VALUE self)
572{
573 GENERATE_JSON(null);
574}
575
576/*
577 * call-seq: to_json(*)
578 *
579 * Converts this object to a string (calling #to_s), converts
580 * it to a JSON string, and returns the result. This is a fallback, if no
581 * special method #to_json was defined for some object.
582 */
583static VALUE mObject_to_json(int argc, VALUE *argv, VALUE self)
584{
585 VALUE state;
586 VALUE string = rb_funcall(self, i_to_s, 0);
587 rb_scan_args(argc, argv, "01", &state);
588 Check_Type(string, T_STRING);
589 state = cState_from_state_s(cState, state);
590 return cState_partial_generate(state, string);
591}
592
593static void State_free(void *ptr)
594{
596 if (state->indent) ruby_xfree(state->indent);
597 if (state->space) ruby_xfree(state->space);
598 if (state->space_before) ruby_xfree(state->space_before);
599 if (state->object_nl) ruby_xfree(state->object_nl);
600 if (state->array_nl) ruby_xfree(state->array_nl);
601 if (state->array_delim) fbuffer_free(state->array_delim);
602 if (state->object_delim) fbuffer_free(state->object_delim);
603 if (state->object_delim2) fbuffer_free(state->object_delim2);
605}
606
607static size_t State_memsize(const void *ptr)
608{
610 size_t size = sizeof(*state);
611 if (state->indent) size += state->indent_len + 1;
612 if (state->space) size += state->space_len + 1;
613 if (state->space_before) size += state->space_before_len + 1;
614 if (state->object_nl) size += state->object_nl_len + 1;
615 if (state->array_nl) size += state->array_nl_len + 1;
616 if (state->array_delim) size += FBUFFER_CAPA(state->array_delim);
617 if (state->object_delim) size += FBUFFER_CAPA(state->object_delim);
618 if (state->object_delim2) size += FBUFFER_CAPA(state->object_delim2);
619 return size;
620}
621
622#ifndef HAVE_RB_EXT_RACTOR_SAFE
623# undef RUBY_TYPED_FROZEN_SHAREABLE
624# define RUBY_TYPED_FROZEN_SHAREABLE 0
625#endif
626
627#ifdef NEW_TYPEDDATA_WRAPPER
628static const rb_data_type_t JSON_Generator_State_type = {
629 "JSON/Generator/State",
630 {NULL, State_free, State_memsize,},
631#ifdef RUBY_TYPED_FREE_IMMEDIATELY
632 0, 0,
634#endif
635};
636#endif
637
638static VALUE cState_s_allocate(VALUE klass)
639{
642 &JSON_Generator_State_type, state);
643}
644
645/*
646 * call-seq: configure(opts)
647 *
648 * Configure this State instance with the Hash _opts_, and return
649 * itself.
650 */
651static VALUE cState_configure(VALUE self, VALUE opts)
652{
653 VALUE tmp;
654 GET_STATE(self);
655 tmp = rb_check_convert_type(opts, T_HASH, "Hash", "to_hash");
656 if (NIL_P(tmp)) tmp = rb_convert_type(opts, T_HASH, "Hash", "to_h");
657 opts = tmp;
658 tmp = rb_hash_aref(opts, ID2SYM(i_indent));
659 if (RTEST(tmp)) {
660 unsigned long len;
661 Check_Type(tmp, T_STRING);
662 len = RSTRING_LEN(tmp);
663 state->indent = fstrndup(RSTRING_PTR(tmp), len + 1);
664 state->indent_len = len;
665 }
666 tmp = rb_hash_aref(opts, ID2SYM(i_space));
667 if (RTEST(tmp)) {
668 unsigned long len;
669 Check_Type(tmp, T_STRING);
670 len = RSTRING_LEN(tmp);
671 state->space = fstrndup(RSTRING_PTR(tmp), len + 1);
672 state->space_len = len;
673 }
674 tmp = rb_hash_aref(opts, ID2SYM(i_space_before));
675 if (RTEST(tmp)) {
676 unsigned long len;
677 Check_Type(tmp, T_STRING);
678 len = RSTRING_LEN(tmp);
679 state->space_before = fstrndup(RSTRING_PTR(tmp), len + 1);
680 state->space_before_len = len;
681 }
682 tmp = rb_hash_aref(opts, ID2SYM(i_array_nl));
683 if (RTEST(tmp)) {
684 unsigned long len;
685 Check_Type(tmp, T_STRING);
686 len = RSTRING_LEN(tmp);
687 state->array_nl = fstrndup(RSTRING_PTR(tmp), len + 1);
688 state->array_nl_len = len;
689 }
690 tmp = rb_hash_aref(opts, ID2SYM(i_object_nl));
691 if (RTEST(tmp)) {
692 unsigned long len;
693 Check_Type(tmp, T_STRING);
694 len = RSTRING_LEN(tmp);
695 state->object_nl = fstrndup(RSTRING_PTR(tmp), len + 1);
696 state->object_nl_len = len;
697 }
698 tmp = ID2SYM(i_max_nesting);
699 state->max_nesting = 100;
700 if (option_given_p(opts, tmp)) {
701 VALUE max_nesting = rb_hash_aref(opts, tmp);
702 if (RTEST(max_nesting)) {
703 Check_Type(max_nesting, T_FIXNUM);
704 state->max_nesting = FIX2LONG(max_nesting);
705 } else {
706 state->max_nesting = 0;
707 }
708 }
709 tmp = ID2SYM(i_depth);
710 state->depth = 0;
711 if (option_given_p(opts, tmp)) {
712 VALUE depth = rb_hash_aref(opts, tmp);
713 if (RTEST(depth)) {
714 Check_Type(depth, T_FIXNUM);
715 state->depth = FIX2LONG(depth);
716 } else {
717 state->depth = 0;
718 }
719 }
720 tmp = ID2SYM(i_buffer_initial_length);
721 if (option_given_p(opts, tmp)) {
722 VALUE buffer_initial_length = rb_hash_aref(opts, tmp);
723 if (RTEST(buffer_initial_length)) {
724 long initial_length;
725 Check_Type(buffer_initial_length, T_FIXNUM);
726 initial_length = FIX2LONG(buffer_initial_length);
727 if (initial_length > 0) state->buffer_initial_length = initial_length;
728 }
729 }
730 tmp = rb_hash_aref(opts, ID2SYM(i_allow_nan));
731 state->allow_nan = RTEST(tmp);
732 tmp = rb_hash_aref(opts, ID2SYM(i_ascii_only));
733 state->ascii_only = RTEST(tmp);
734 tmp = rb_hash_aref(opts, ID2SYM(i_escape_slash));
735 state->escape_slash = RTEST(tmp);
736 return self;
737}
738
739static void set_state_ivars(VALUE hash, VALUE state)
740{
742 int i = 0;
743 for (i = 0; i < RARRAY_LEN(ivars); i++) {
744 VALUE key = rb_funcall(rb_ary_entry(ivars, i), i_to_s, 0);
745 long key_len = RSTRING_LEN(key);
747 rb_hash_aset(hash, rb_str_intern(rb_str_substr(key, 1, key_len - 1)), value);
748 }
749}
750
751/*
752 * call-seq: to_h
753 *
754 * Returns the configuration instance variables as a hash, that can be
755 * passed to the configure method.
756 */
757static VALUE cState_to_h(VALUE self)
758{
759 VALUE result = rb_hash_new();
760 GET_STATE(self);
761 set_state_ivars(result, self);
762 rb_hash_aset(result, ID2SYM(i_indent), rb_str_new(state->indent, state->indent_len));
763 rb_hash_aset(result, ID2SYM(i_space), rb_str_new(state->space, state->space_len));
764 rb_hash_aset(result, ID2SYM(i_space_before), rb_str_new(state->space_before, state->space_before_len));
765 rb_hash_aset(result, ID2SYM(i_object_nl), rb_str_new(state->object_nl, state->object_nl_len));
766 rb_hash_aset(result, ID2SYM(i_array_nl), rb_str_new(state->array_nl, state->array_nl_len));
767 rb_hash_aset(result, ID2SYM(i_allow_nan), state->allow_nan ? Qtrue : Qfalse);
768 rb_hash_aset(result, ID2SYM(i_ascii_only), state->ascii_only ? Qtrue : Qfalse);
769 rb_hash_aset(result, ID2SYM(i_max_nesting), LONG2FIX(state->max_nesting));
770 rb_hash_aset(result, ID2SYM(i_escape_slash), state->escape_slash ? Qtrue : Qfalse);
771 rb_hash_aset(result, ID2SYM(i_depth), LONG2FIX(state->depth));
772 rb_hash_aset(result, ID2SYM(i_buffer_initial_length), LONG2FIX(state->buffer_initial_length));
773 return result;
774}
775
776/*
777* call-seq: [](name)
778*
779* Returns the value returned by method +name+.
780*/
781static VALUE cState_aref(VALUE self, VALUE name)
782{
783 name = rb_funcall(name, i_to_s, 0);
784 if (RTEST(rb_funcall(self, i_respond_to_p, 1, name))) {
785 return rb_funcall(self, i_send, 1, name);
786 } else {
788 }
789}
790
791/*
792* call-seq: []=(name, value)
793*
794* Sets the attribute name to value.
795*/
796static VALUE cState_aset(VALUE self, VALUE name, VALUE value)
797{
798 VALUE name_writer;
799
800 name = rb_funcall(name, i_to_s, 0);
801 name_writer = rb_str_cat2(rb_str_dup(name), "=");
802 if (RTEST(rb_funcall(self, i_respond_to_p, 1, name_writer))) {
803 return rb_funcall(self, i_send, 2, name_writer, value);
804 } else {
806 }
807 return Qnil;
808}
809
814 int iter;
815};
816
817static int
818json_object_i(VALUE key, VALUE val, VALUE _arg)
819{
820 struct hash_foreach_arg *arg = (struct hash_foreach_arg *)_arg;
821 FBuffer *buffer = arg->buffer;
823 VALUE Vstate = arg->Vstate;
824
825 char *object_nl = state->object_nl;
826 long object_nl_len = state->object_nl_len;
827 char *indent = state->indent;
828 long indent_len = state->indent_len;
829 char *delim = FBUFFER_PTR(state->object_delim);
830 long delim_len = FBUFFER_LEN(state->object_delim);
831 char *delim2 = FBUFFER_PTR(state->object_delim2);
832 long delim2_len = FBUFFER_LEN(state->object_delim2);
833 long depth = state->depth;
834 int j;
835 VALUE klass, key_to_s;
836
837 if (arg->iter > 0) fbuffer_append(buffer, delim, delim_len);
838 if (object_nl) {
839 fbuffer_append(buffer, object_nl, object_nl_len);
840 }
841 if (indent) {
842 for (j = 0; j < depth; j++) {
843 fbuffer_append(buffer, indent, indent_len);
844 }
845 }
846
847 klass = CLASS_OF(key);
848 if (klass == rb_cString) {
849 key_to_s = key;
850 } else if (klass == rb_cSymbol) {
851 key_to_s = rb_id2str(SYM2ID(key));
852 } else {
853 key_to_s = rb_funcall(key, i_to_s, 0);
854 }
855 Check_Type(key_to_s, T_STRING);
856 generate_json(buffer, Vstate, state, key_to_s);
857 fbuffer_append(buffer, delim2, delim2_len);
858 generate_json(buffer, Vstate, state, val);
859
860 arg->iter++;
861 return ST_CONTINUE;
862}
863
864static void generate_json_object(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
865{
866 char *object_nl = state->object_nl;
867 long object_nl_len = state->object_nl_len;
868 char *indent = state->indent;
869 long indent_len = state->indent_len;
870 long max_nesting = state->max_nesting;
871 long depth = ++state->depth;
872 int j;
873 struct hash_foreach_arg arg;
874
875 if (max_nesting != 0 && depth > max_nesting) {
876 fbuffer_free(buffer);
877 rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
878 }
879 fbuffer_append_char(buffer, '{');
880
881 arg.buffer = buffer;
882 arg.state = state;
883 arg.Vstate = Vstate;
884 arg.iter = 0;
885 rb_hash_foreach(obj, json_object_i, (VALUE)&arg);
886
887 depth = --state->depth;
888 if (object_nl) {
889 fbuffer_append(buffer, object_nl, object_nl_len);
890 if (indent) {
891 for (j = 0; j < depth; j++) {
892 fbuffer_append(buffer, indent, indent_len);
893 }
894 }
895 }
896 fbuffer_append_char(buffer, '}');
897}
898
899static void generate_json_array(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
900{
901 char *array_nl = state->array_nl;
902 long array_nl_len = state->array_nl_len;
903 char *indent = state->indent;
904 long indent_len = state->indent_len;
905 long max_nesting = state->max_nesting;
906 char *delim = FBUFFER_PTR(state->array_delim);
907 long delim_len = FBUFFER_LEN(state->array_delim);
908 long depth = ++state->depth;
909 int i, j;
910 if (max_nesting != 0 && depth > max_nesting) {
911 fbuffer_free(buffer);
912 rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth);
913 }
914 fbuffer_append_char(buffer, '[');
915 if (array_nl) fbuffer_append(buffer, array_nl, array_nl_len);
916 for(i = 0; i < RARRAY_LEN(obj); i++) {
917 if (i > 0) fbuffer_append(buffer, delim, delim_len);
918 if (indent) {
919 for (j = 0; j < depth; j++) {
920 fbuffer_append(buffer, indent, indent_len);
921 }
922 }
923 generate_json(buffer, Vstate, state, rb_ary_entry(obj, i));
924 }
925 state->depth = --depth;
926 if (array_nl) {
927 fbuffer_append(buffer, array_nl, array_nl_len);
928 if (indent) {
929 for (j = 0; j < depth; j++) {
930 fbuffer_append(buffer, indent, indent_len);
931 }
932 }
933 }
934 fbuffer_append_char(buffer, ']');
935}
936
937#ifdef HAVE_RUBY_ENCODING_H
938static int enc_utf8_compatible_p(rb_encoding *enc)
939{
940 if (enc == rb_usascii_encoding()) return 1;
941 if (enc == rb_utf8_encoding()) return 1;
942 return 0;
943}
944#endif
945
946static void generate_json_string(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
947{
948 fbuffer_append_char(buffer, '"');
949#ifdef HAVE_RUBY_ENCODING_H
950 if (!enc_utf8_compatible_p(rb_enc_get(obj))) {
951 obj = rb_str_encode(obj, CEncoding_UTF_8, 0, Qnil);
952 }
953#endif
954 if (state->ascii_only) {
955 convert_UTF8_to_JSON_ASCII(buffer, obj, state->escape_slash);
956 } else {
957 convert_UTF8_to_JSON(buffer, obj, state->escape_slash);
958 }
959 fbuffer_append_char(buffer, '"');
960}
961
962static void generate_json_null(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
963{
964 fbuffer_append(buffer, "null", 4);
965}
966
967static void generate_json_false(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
968{
969 fbuffer_append(buffer, "false", 5);
970}
971
972static void generate_json_true(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
973{
974 fbuffer_append(buffer, "true", 4);
975}
976
977static void generate_json_fixnum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
978{
979 fbuffer_append_long(buffer, FIX2LONG(obj));
980}
981
982static void generate_json_bignum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
983{
984 VALUE tmp = rb_funcall(obj, i_to_s, 0);
985 fbuffer_append_str(buffer, tmp);
986}
987
988#ifdef RUBY_INTEGER_UNIFICATION
989static void generate_json_integer(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
990{
991 if (FIXNUM_P(obj))
992 generate_json_fixnum(buffer, Vstate, state, obj);
993 else
994 generate_json_bignum(buffer, Vstate, state, obj);
995}
996#endif
997static void generate_json_float(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
998{
999 double value = RFLOAT_VALUE(obj);
1000 char allow_nan = state->allow_nan;
1001 VALUE tmp = rb_funcall(obj, i_to_s, 0);
1002 if (!allow_nan) {
1003 if (isinf(value)) {
1004 fbuffer_free(buffer);
1005 rb_raise(eGeneratorError, "%u: %"PRIsVALUE" not allowed in JSON", __LINE__, RB_OBJ_STRING(tmp));
1006 } else if (isnan(value)) {
1007 fbuffer_free(buffer);
1008 rb_raise(eGeneratorError, "%u: %"PRIsVALUE" not allowed in JSON", __LINE__, RB_OBJ_STRING(tmp));
1009 }
1010 }
1011 fbuffer_append_str(buffer, tmp);
1012}
1013
1014static void generate_json(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
1015{
1016 VALUE tmp;
1017 VALUE klass = CLASS_OF(obj);
1018 if (klass == rb_cHash) {
1019 generate_json_object(buffer, Vstate, state, obj);
1020 } else if (klass == rb_cArray) {
1021 generate_json_array(buffer, Vstate, state, obj);
1022 } else if (klass == rb_cString) {
1023 generate_json_string(buffer, Vstate, state, obj);
1024 } else if (obj == Qnil) {
1025 generate_json_null(buffer, Vstate, state, obj);
1026 } else if (obj == Qfalse) {
1027 generate_json_false(buffer, Vstate, state, obj);
1028 } else if (obj == Qtrue) {
1029 generate_json_true(buffer, Vstate, state, obj);
1030 } else if (FIXNUM_P(obj)) {
1031 generate_json_fixnum(buffer, Vstate, state, obj);
1032 } else if (RB_TYPE_P(obj, T_BIGNUM)) {
1033 generate_json_bignum(buffer, Vstate, state, obj);
1034 } else if (klass == rb_cFloat) {
1035 generate_json_float(buffer, Vstate, state, obj);
1036 } else if (rb_respond_to(obj, i_to_json)) {
1037 tmp = rb_funcall(obj, i_to_json, 1, Vstate);
1038 Check_Type(tmp, T_STRING);
1039 fbuffer_append_str(buffer, tmp);
1040 } else {
1041 tmp = rb_funcall(obj, i_to_s, 0);
1042 Check_Type(tmp, T_STRING);
1043 generate_json_string(buffer, Vstate, state, tmp);
1044 }
1045}
1046
1047static FBuffer *cState_prepare_buffer(VALUE self)
1048{
1049 FBuffer *buffer;
1050 GET_STATE(self);
1051 buffer = fbuffer_alloc(state->buffer_initial_length);
1052
1053 if (state->object_delim) {
1054 fbuffer_clear(state->object_delim);
1055 } else {
1056 state->object_delim = fbuffer_alloc(16);
1057 }
1058 fbuffer_append_char(state->object_delim, ',');
1059 if (state->object_delim2) {
1060 fbuffer_clear(state->object_delim2);
1061 } else {
1062 state->object_delim2 = fbuffer_alloc(16);
1063 }
1064 if (state->space_before) fbuffer_append(state->object_delim2, state->space_before, state->space_before_len);
1065 fbuffer_append_char(state->object_delim2, ':');
1066 if (state->space) fbuffer_append(state->object_delim2, state->space, state->space_len);
1067
1068 if (state->array_delim) {
1069 fbuffer_clear(state->array_delim);
1070 } else {
1071 state->array_delim = fbuffer_alloc(16);
1072 }
1073 fbuffer_append_char(state->array_delim, ',');
1074 if (state->array_nl) fbuffer_append(state->array_delim, state->array_nl, state->array_nl_len);
1075 return buffer;
1076}
1077
1078static VALUE cState_partial_generate(VALUE self, VALUE obj)
1079{
1080 FBuffer *buffer = cState_prepare_buffer(self);
1081 GET_STATE(self);
1082 generate_json(buffer, self, state, obj);
1083 return fbuffer_to_s(buffer);
1084}
1085
1086/*
1087 * call-seq: generate(obj)
1088 *
1089 * Generates a valid JSON document from object +obj+ and returns the
1090 * result. If no valid JSON document can be created this method raises a
1091 * GeneratorError exception.
1092 */
1093static VALUE cState_generate(VALUE self, VALUE obj)
1094{
1095 VALUE result = cState_partial_generate(self, obj);
1096 GET_STATE(self);
1097 (void)state;
1098 return result;
1099}
1100
1101/*
1102 * call-seq: new(opts = {})
1103 *
1104 * Instantiates a new State object, configured by _opts_.
1105 *
1106 * _opts_ can have the following keys:
1107 *
1108 * * *indent*: a string used to indent levels (default: ''),
1109 * * *space*: a string that is put after, a : or , delimiter (default: ''),
1110 * * *space_before*: a string that is put before a : pair delimiter (default: ''),
1111 * * *object_nl*: a string that is put at the end of a JSON object (default: ''),
1112 * * *array_nl*: a string that is put at the end of a JSON array (default: ''),
1113 * * *allow_nan*: true if NaN, Infinity, and -Infinity should be
1114 * generated, otherwise an exception is thrown, if these values are
1115 * encountered. This options defaults to false.
1116 * * *ascii_only*: true if only ASCII characters should be generated. This
1117 * option defaults to false.
1118 * * *buffer_initial_length*: sets the initial length of the generator's
1119 * internal buffer.
1120 */
1121static VALUE cState_initialize(int argc, VALUE *argv, VALUE self)
1122{
1123 VALUE opts;
1124 GET_STATE(self);
1125 state->max_nesting = 100;
1126 state->buffer_initial_length = FBUFFER_INITIAL_LENGTH_DEFAULT;
1127 rb_scan_args(argc, argv, "01", &opts);
1128 if (!NIL_P(opts)) cState_configure(self, opts);
1129 return self;
1130}
1131
1132/*
1133 * call-seq: initialize_copy(orig)
1134 *
1135 * Initializes this object from orig if it can be duplicated/cloned and returns
1136 * it.
1137*/
1138static VALUE cState_init_copy(VALUE obj, VALUE orig)
1139{
1140 JSON_Generator_State *objState, *origState;
1141
1142 if (obj == orig) return obj;
1143 GET_STATE_TO(obj, objState);
1144 GET_STATE_TO(orig, origState);
1145 if (!objState) rb_raise(rb_eArgError, "unallocated JSON::State");
1146
1147 MEMCPY(objState, origState, JSON_Generator_State, 1);
1148 objState->indent = fstrndup(origState->indent, origState->indent_len);
1149 objState->space = fstrndup(origState->space, origState->space_len);
1150 objState->space_before = fstrndup(origState->space_before, origState->space_before_len);
1151 objState->object_nl = fstrndup(origState->object_nl, origState->object_nl_len);
1152 objState->array_nl = fstrndup(origState->array_nl, origState->array_nl_len);
1153 if (origState->array_delim) objState->array_delim = fbuffer_dup(origState->array_delim);
1154 if (origState->object_delim) objState->object_delim = fbuffer_dup(origState->object_delim);
1155 if (origState->object_delim2) objState->object_delim2 = fbuffer_dup(origState->object_delim2);
1156 return obj;
1157}
1158
1159/*
1160 * call-seq: from_state(opts)
1161 *
1162 * Creates a State object from _opts_, which ought to be Hash to create a
1163 * new State instance configured by _opts_, something else to create an
1164 * unconfigured instance. If _opts_ is a State object, it is just returned.
1165 */
1166static VALUE cState_from_state_s(VALUE self, VALUE opts)
1167{
1168 if (rb_obj_is_kind_of(opts, self)) {
1169 return opts;
1170 } else if (rb_obj_is_kind_of(opts, rb_cHash)) {
1171 return rb_funcall(self, i_new, 1, opts);
1172 } else {
1173 return rb_class_new_instance(0, NULL, cState);
1174 }
1175}
1176
1177/*
1178 * call-seq: indent()
1179 *
1180 * Returns the string that is used to indent levels in the JSON text.
1181 */
1182static VALUE cState_indent(VALUE self)
1183{
1184 GET_STATE(self);
1185 return state->indent ? rb_str_new(state->indent, state->indent_len) : rb_str_new2("");
1186}
1187
1188/*
1189 * call-seq: indent=(indent)
1190 *
1191 * Sets the string that is used to indent levels in the JSON text.
1192 */
1193static VALUE cState_indent_set(VALUE self, VALUE indent)
1194{
1195 unsigned long len;
1196 GET_STATE(self);
1197 Check_Type(indent, T_STRING);
1198 len = RSTRING_LEN(indent);
1199 if (len == 0) {
1200 if (state->indent) {
1201 ruby_xfree(state->indent);
1202 state->indent = NULL;
1203 state->indent_len = 0;
1204 }
1205 } else {
1206 if (state->indent) ruby_xfree(state->indent);
1207 state->indent = fstrndup(RSTRING_PTR(indent), len);
1208 state->indent_len = len;
1209 }
1210 return Qnil;
1211}
1212
1213/*
1214 * call-seq: space()
1215 *
1216 * Returns the string that is used to insert a space between the tokens in a JSON
1217 * string.
1218 */
1219static VALUE cState_space(VALUE self)
1220{
1221 GET_STATE(self);
1222 return state->space ? rb_str_new(state->space, state->space_len) : rb_str_new2("");
1223}
1224
1225/*
1226 * call-seq: space=(space)
1227 *
1228 * Sets _space_ to the string that is used to insert a space between the tokens in a JSON
1229 * string.
1230 */
1231static VALUE cState_space_set(VALUE self, VALUE space)
1232{
1233 unsigned long len;
1234 GET_STATE(self);
1235 Check_Type(space, T_STRING);
1236 len = RSTRING_LEN(space);
1237 if (len == 0) {
1238 if (state->space) {
1239 ruby_xfree(state->space);
1240 state->space = NULL;
1241 state->space_len = 0;
1242 }
1243 } else {
1244 if (state->space) ruby_xfree(state->space);
1245 state->space = fstrndup(RSTRING_PTR(space), len);
1246 state->space_len = len;
1247 }
1248 return Qnil;
1249}
1250
1251/*
1252 * call-seq: space_before()
1253 *
1254 * Returns the string that is used to insert a space before the ':' in JSON objects.
1255 */
1256static VALUE cState_space_before(VALUE self)
1257{
1258 GET_STATE(self);
1259 return state->space_before ? rb_str_new(state->space_before, state->space_before_len) : rb_str_new2("");
1260}
1261
1262/*
1263 * call-seq: space_before=(space_before)
1264 *
1265 * Sets the string that is used to insert a space before the ':' in JSON objects.
1266 */
1267static VALUE cState_space_before_set(VALUE self, VALUE space_before)
1268{
1269 unsigned long len;
1270 GET_STATE(self);
1271 Check_Type(space_before, T_STRING);
1272 len = RSTRING_LEN(space_before);
1273 if (len == 0) {
1274 if (state->space_before) {
1275 ruby_xfree(state->space_before);
1276 state->space_before = NULL;
1277 state->space_before_len = 0;
1278 }
1279 } else {
1280 if (state->space_before) ruby_xfree(state->space_before);
1281 state->space_before = fstrndup(RSTRING_PTR(space_before), len);
1282 state->space_before_len = len;
1283 }
1284 return Qnil;
1285}
1286
1287/*
1288 * call-seq: object_nl()
1289 *
1290 * This string is put at the end of a line that holds a JSON object (or
1291 * Hash).
1292 */
1293static VALUE cState_object_nl(VALUE self)
1294{
1295 GET_STATE(self);
1296 return state->object_nl ? rb_str_new(state->object_nl, state->object_nl_len) : rb_str_new2("");
1297}
1298
1299/*
1300 * call-seq: object_nl=(object_nl)
1301 *
1302 * This string is put at the end of a line that holds a JSON object (or
1303 * Hash).
1304 */
1305static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)
1306{
1307 unsigned long len;
1308 GET_STATE(self);
1309 Check_Type(object_nl, T_STRING);
1310 len = RSTRING_LEN(object_nl);
1311 if (len == 0) {
1312 if (state->object_nl) {
1313 ruby_xfree(state->object_nl);
1314 state->object_nl = NULL;
1315 }
1316 } else {
1317 if (state->object_nl) ruby_xfree(state->object_nl);
1318 state->object_nl = fstrndup(RSTRING_PTR(object_nl), len);
1319 state->object_nl_len = len;
1320 }
1321 return Qnil;
1322}
1323
1324/*
1325 * call-seq: array_nl()
1326 *
1327 * This string is put at the end of a line that holds a JSON array.
1328 */
1329static VALUE cState_array_nl(VALUE self)
1330{
1331 GET_STATE(self);
1332 return state->array_nl ? rb_str_new(state->array_nl, state->array_nl_len) : rb_str_new2("");
1333}
1334
1335/*
1336 * call-seq: array_nl=(array_nl)
1337 *
1338 * This string is put at the end of a line that holds a JSON array.
1339 */
1340static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)
1341{
1342 unsigned long len;
1343 GET_STATE(self);
1344 Check_Type(array_nl, T_STRING);
1345 len = RSTRING_LEN(array_nl);
1346 if (len == 0) {
1347 if (state->array_nl) {
1348 ruby_xfree(state->array_nl);
1349 state->array_nl = NULL;
1350 }
1351 } else {
1352 if (state->array_nl) ruby_xfree(state->array_nl);
1353 state->array_nl = fstrndup(RSTRING_PTR(array_nl), len);
1354 state->array_nl_len = len;
1355 }
1356 return Qnil;
1357}
1358
1359
1360/*
1361* call-seq: check_circular?
1362*
1363* Returns true, if circular data structures should be checked,
1364* otherwise returns false.
1365*/
1366static VALUE cState_check_circular_p(VALUE self)
1367{
1368 GET_STATE(self);
1369 return state->max_nesting ? Qtrue : Qfalse;
1370}
1371
1372/*
1373 * call-seq: max_nesting
1374 *
1375 * This integer returns the maximum level of data structure nesting in
1376 * the generated JSON, max_nesting = 0 if no maximum is checked.
1377 */
1378static VALUE cState_max_nesting(VALUE self)
1379{
1380 GET_STATE(self);
1381 return LONG2FIX(state->max_nesting);
1382}
1383
1384/*
1385 * call-seq: max_nesting=(depth)
1386 *
1387 * This sets the maximum level of data structure nesting in the generated JSON
1388 * to the integer depth, max_nesting = 0 if no maximum should be checked.
1389 */
1390static VALUE cState_max_nesting_set(VALUE self, VALUE depth)
1391{
1392 GET_STATE(self);
1393 Check_Type(depth, T_FIXNUM);
1394 return state->max_nesting = FIX2LONG(depth);
1395}
1396
1397/*
1398 * call-seq: escape_slash
1399 *
1400 * If this boolean is true, the forward slashes will be escaped in
1401 * the json output.
1402 */
1403static VALUE cState_escape_slash(VALUE self)
1404{
1405 GET_STATE(self);
1406 return state->escape_slash ? Qtrue : Qfalse;
1407}
1408
1409/*
1410 * call-seq: escape_slash=(depth)
1411 *
1412 * This sets whether or not the forward slashes will be escaped in
1413 * the json output.
1414 */
1415static VALUE cState_escape_slash_set(VALUE self, VALUE enable)
1416{
1417 GET_STATE(self);
1418 state->escape_slash = RTEST(enable);
1419 return Qnil;
1420}
1421
1422/*
1423 * call-seq: allow_nan?
1424 *
1425 * Returns true, if NaN, Infinity, and -Infinity should be generated, otherwise
1426 * returns false.
1427 */
1428static VALUE cState_allow_nan_p(VALUE self)
1429{
1430 GET_STATE(self);
1431 return state->allow_nan ? Qtrue : Qfalse;
1432}
1433
1434/*
1435 * call-seq: ascii_only?
1436 *
1437 * Returns true, if only ASCII characters should be generated. Otherwise
1438 * returns false.
1439 */
1440static VALUE cState_ascii_only_p(VALUE self)
1441{
1442 GET_STATE(self);
1443 return state->ascii_only ? Qtrue : Qfalse;
1444}
1445
1446/*
1447 * call-seq: depth
1448 *
1449 * This integer returns the current depth of data structure nesting.
1450 */
1451static VALUE cState_depth(VALUE self)
1452{
1453 GET_STATE(self);
1454 return LONG2FIX(state->depth);
1455}
1456
1457/*
1458 * call-seq: depth=(depth)
1459 *
1460 * This sets the maximum level of data structure nesting in the generated JSON
1461 * to the integer depth, max_nesting = 0 if no maximum should be checked.
1462 */
1463static VALUE cState_depth_set(VALUE self, VALUE depth)
1464{
1465 GET_STATE(self);
1466 Check_Type(depth, T_FIXNUM);
1467 state->depth = FIX2LONG(depth);
1468 return Qnil;
1469}
1470
1471/*
1472 * call-seq: buffer_initial_length
1473 *
1474 * This integer returns the current initial length of the buffer.
1475 */
1476static VALUE cState_buffer_initial_length(VALUE self)
1477{
1478 GET_STATE(self);
1479 return LONG2FIX(state->buffer_initial_length);
1480}
1481
1482/*
1483 * call-seq: buffer_initial_length=(length)
1484 *
1485 * This sets the initial length of the buffer to +length+, if +length+ > 0,
1486 * otherwise its value isn't changed.
1487 */
1488static VALUE cState_buffer_initial_length_set(VALUE self, VALUE buffer_initial_length)
1489{
1490 long initial_length;
1491 GET_STATE(self);
1492 Check_Type(buffer_initial_length, T_FIXNUM);
1493 initial_length = FIX2LONG(buffer_initial_length);
1494 if (initial_length > 0) {
1495 state->buffer_initial_length = initial_length;
1496 }
1497 return Qnil;
1498}
1499
1500/*
1501 *
1502 */
1504{
1505#ifdef HAVE_RB_EXT_RACTOR_SAFE
1506 rb_ext_ractor_safe(true);
1507#endif
1508
1509#undef rb_intern
1510 rb_require("json/common");
1511
1512 mJSON = rb_define_module("JSON");
1513 mExt = rb_define_module_under(mJSON, "Ext");
1514 mGenerator = rb_define_module_under(mExt, "Generator");
1515
1516 eGeneratorError = rb_path2class("JSON::GeneratorError");
1517 eNestingError = rb_path2class("JSON::NestingError");
1518 rb_gc_register_mark_object(eGeneratorError);
1519 rb_gc_register_mark_object(eNestingError);
1520
1521 cState = rb_define_class_under(mGenerator, "State", rb_cObject);
1522 rb_define_alloc_func(cState, cState_s_allocate);
1523 rb_define_singleton_method(cState, "from_state", cState_from_state_s, 1);
1524 rb_define_method(cState, "initialize", cState_initialize, -1);
1525 rb_define_method(cState, "initialize_copy", cState_init_copy, 1);
1526 rb_define_method(cState, "indent", cState_indent, 0);
1527 rb_define_method(cState, "indent=", cState_indent_set, 1);
1528 rb_define_method(cState, "space", cState_space, 0);
1529 rb_define_method(cState, "space=", cState_space_set, 1);
1530 rb_define_method(cState, "space_before", cState_space_before, 0);
1531 rb_define_method(cState, "space_before=", cState_space_before_set, 1);
1532 rb_define_method(cState, "object_nl", cState_object_nl, 0);
1533 rb_define_method(cState, "object_nl=", cState_object_nl_set, 1);
1534 rb_define_method(cState, "array_nl", cState_array_nl, 0);
1535 rb_define_method(cState, "array_nl=", cState_array_nl_set, 1);
1536 rb_define_method(cState, "max_nesting", cState_max_nesting, 0);
1537 rb_define_method(cState, "max_nesting=", cState_max_nesting_set, 1);
1538 rb_define_method(cState, "escape_slash", cState_escape_slash, 0);
1539 rb_define_method(cState, "escape_slash?", cState_escape_slash, 0);
1540 rb_define_method(cState, "escape_slash=", cState_escape_slash_set, 1);
1541 rb_define_method(cState, "check_circular?", cState_check_circular_p, 0);
1542 rb_define_method(cState, "allow_nan?", cState_allow_nan_p, 0);
1543 rb_define_method(cState, "ascii_only?", cState_ascii_only_p, 0);
1544 rb_define_method(cState, "depth", cState_depth, 0);
1545 rb_define_method(cState, "depth=", cState_depth_set, 1);
1546 rb_define_method(cState, "buffer_initial_length", cState_buffer_initial_length, 0);
1547 rb_define_method(cState, "buffer_initial_length=", cState_buffer_initial_length_set, 1);
1548 rb_define_method(cState, "configure", cState_configure, 1);
1549 rb_define_alias(cState, "merge", "configure");
1550 rb_define_method(cState, "to_h", cState_to_h, 0);
1551 rb_define_alias(cState, "to_hash", "to_h");
1552 rb_define_method(cState, "[]", cState_aref, 1);
1553 rb_define_method(cState, "[]=", cState_aset, 2);
1554 rb_define_method(cState, "generate", cState_generate, 1);
1555
1556 mGeneratorMethods = rb_define_module_under(mGenerator, "GeneratorMethods");
1557 mObject = rb_define_module_under(mGeneratorMethods, "Object");
1558 rb_define_method(mObject, "to_json", mObject_to_json, -1);
1559 mHash = rb_define_module_under(mGeneratorMethods, "Hash");
1560 rb_define_method(mHash, "to_json", mHash_to_json, -1);
1561 mArray = rb_define_module_under(mGeneratorMethods, "Array");
1562 rb_define_method(mArray, "to_json", mArray_to_json, -1);
1563#ifdef RUBY_INTEGER_UNIFICATION
1564 mInteger = rb_define_module_under(mGeneratorMethods, "Integer");
1565 rb_define_method(mInteger, "to_json", mInteger_to_json, -1);
1566#else
1567 mFixnum = rb_define_module_under(mGeneratorMethods, "Fixnum");
1568 rb_define_method(mFixnum, "to_json", mFixnum_to_json, -1);
1569 mBignum = rb_define_module_under(mGeneratorMethods, "Bignum");
1570 rb_define_method(mBignum, "to_json", mBignum_to_json, -1);
1571#endif
1572 mFloat = rb_define_module_under(mGeneratorMethods, "Float");
1573 rb_define_method(mFloat, "to_json", mFloat_to_json, -1);
1574 mString = rb_define_module_under(mGeneratorMethods, "String");
1575 rb_define_singleton_method(mString, "included", mString_included_s, 1);
1576 rb_define_method(mString, "to_json", mString_to_json, -1);
1577 rb_define_method(mString, "to_json_raw", mString_to_json_raw, -1);
1578 rb_define_method(mString, "to_json_raw_object", mString_to_json_raw_object, 0);
1579 mString_Extend = rb_define_module_under(mString, "Extend");
1580 rb_define_method(mString_Extend, "json_create", mString_Extend_json_create, 1);
1581 mTrueClass = rb_define_module_under(mGeneratorMethods, "TrueClass");
1582 rb_define_method(mTrueClass, "to_json", mTrueClass_to_json, -1);
1583 mFalseClass = rb_define_module_under(mGeneratorMethods, "FalseClass");
1584 rb_define_method(mFalseClass, "to_json", mFalseClass_to_json, -1);
1585 mNilClass = rb_define_module_under(mGeneratorMethods, "NilClass");
1586 rb_define_method(mNilClass, "to_json", mNilClass_to_json, -1);
1587
1588 i_to_s = rb_intern("to_s");
1589 i_to_json = rb_intern("to_json");
1590 i_new = rb_intern("new");
1591 i_indent = rb_intern("indent");
1592 i_space = rb_intern("space");
1593 i_space_before = rb_intern("space_before");
1594 i_object_nl = rb_intern("object_nl");
1595 i_array_nl = rb_intern("array_nl");
1596 i_max_nesting = rb_intern("max_nesting");
1597 i_escape_slash = rb_intern("escape_slash");
1598 i_allow_nan = rb_intern("allow_nan");
1599 i_ascii_only = rb_intern("ascii_only");
1600 i_depth = rb_intern("depth");
1601 i_buffer_initial_length = rb_intern("buffer_initial_length");
1602 i_pack = rb_intern("pack");
1603 i_unpack = rb_intern("unpack");
1604 i_create_id = rb_intern("create_id");
1605 i_extend = rb_intern("extend");
1606 i_key_p = rb_intern("key?");
1607 i_aref = rb_intern("[]");
1608 i_send = rb_intern("__send__");
1609 i_respond_to_p = rb_intern("respond_to?");
1610 i_match = rb_intern("match");
1611 i_keys = rb_intern("keys");
1612 i_dup = rb_intern("dup");
1613#ifdef HAVE_RUBY_ENCODING_H
1614 CEncoding_UTF_8 = rb_funcall(rb_path2class("Encoding"), rb_intern("find"), 1, rb_str_new2("utf-8"));
1615 i_encoding = rb_intern("encoding");
1616 i_encode = rb_intern("encode");
1617#endif
1618}
VALUE rb_cArray
Definition: array.c:40
VALUE rb_ary_entry(VALUE ary, long offset)
Definition: array.c:1672
#define RB_OBJ_STRING(obj)
Definition: bigdecimal.c:99
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
Definition: cxxanyargs.hpp:653
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition: cxxanyargs.hpp:668
struct RIMemo * ptr
Definition: debug.c:88
#define RFLOAT_VALUE
Definition: double.h:28
rb_encoding * rb_utf8_encoding(void)
Definition: encoding.c:1537
rb_encoding * rb_enc_get(VALUE obj)
Definition: encoding.c:1070
rb_encoding * rb_usascii_encoding(void)
Definition: encoding.c:1549
uint8_t len
Definition: escape.c:17
#define RSTRING_LEN(string)
Definition: fbuffer.h:22
#define FBUFFER_CAPA(fb)
Definition: fbuffer.h:57
#define RSTRING_PTR(string)
Definition: fbuffer.h:19
#define FBUFFER_LEN(fb)
Definition: fbuffer.h:56
#define FBUFFER_PTR(fb)
Definition: fbuffer.h:55
#define FBUFFER_INITIAL_LENGTH_DEFAULT
Definition: fbuffer.h:53
#define memcpy(d, s, n)
Definition: ffi_common.h:55
#define PRIsVALUE
Definition: function.c:10
void ruby_xfree(void *x)
Deallocates a storage instance.
Definition: gc.c:10914
void rb_gc_register_mark_object(VALUE obj)
Inform the garbage collector that object is a live Ruby object that should not be moved.
Definition: gc.c:8022
void Init_generator(void)
Definition: generator.c:1503
#define GET_STATE_TO(self, state)
Definition: generator.h:80
unsigned long UTF32
Definition: generator.h:29
#define rb_obj_instance_variables(object)
Definition: generator.h:20
#define UNI_SUR_LOW_START
Definition: generator.h:41
#define UNI_REPLACEMENT_CHAR
Definition: generator.h:33
#define UNI_SUR_HIGH_START
Definition: generator.h:39
unsigned short UTF16
Definition: generator.h:30
#define UNI_MAX_UTF16
Definition: generator.h:35
#define GET_STATE(self)
Definition: generator.h:83
unsigned char UTF8
Definition: generator.h:31
#define UNI_SUR_LOW_END
Definition: generator.h:42
#define rb_intern_str(string)
Definition: generator.h:16
#define UNI_MAX_BMP
Definition: generator.h:34
#define option_given_p(opts, key)
Definition: generator.h:23
#define GENERATE_JSON(type)
Definition: generator.h:87
#define CLASS_OF
Definition: globals.h:153
VALUE rb_cSymbol
Definition: string.c:81
VALUE rb_cFloat
Definition: numeric.c:190
VALUE rb_cString
Definition: string.c:80
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:797
VALUE rb_define_module(const char *name)
Definition: class.c:871
VALUE rb_define_module_under(VALUE outer, const char *name)
Definition: class.c:895
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition: class.c:1999
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:2296
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2917
VALUE rb_eArgError
Definition: error.c:1058
VALUE rb_convert_type(VALUE, int, const char *, const char *)
Converts an object into another type.
Definition: object.c:2930
VALUE rb_check_convert_type(VALUE, int, const char *, const char *)
Tries to convert an object into another type.
Definition: object.c:2971
VALUE rb_cObject
Object class.
Definition: object.c:49
VALUE rb_class_new_instance(int, const VALUE *, VALUE)
Allocates and initializes an instance of klass.
Definition: object.c:1953
VALUE rb_obj_class(VALUE)
Definition: object.c:245
VALUE rb_obj_is_kind_of(VALUE, VALUE)
Determines if obj is a kind of c.
Definition: object.c:724
void rb_hash_foreach(VALUE hash, rb_foreach_func *func, VALUE farg)
Definition: hash.c:1498
VALUE rb_cHash
Definition: hash.c:106
VALUE rb_hash_aref(VALUE hash, VALUE key)
Definition: hash.c:2046
VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val)
Definition: hash.c:2901
VALUE rb_hash_new(void)
Definition: hash.c:1538
VALUE rb_str_encode(VALUE str, VALUE to, int ecflags, VALUE ecopts)
Definition: transcode.c:2892
int rb_enc_str_asciionly_p(VALUE)
Definition: string.c:739
VALUE rb_funcall(VALUE, ID, int,...)
Calls a method.
Definition: vm_eval.c:1077
void rb_ext_ractor_safe(bool flag)
Definition: load.c:1058
#define rb_str_new2
Definition: string.h:276
VALUE rb_str_concat(VALUE, VALUE)
Definition: string.c:3217
#define rb_str_cat2
Definition: string.h:285
#define rb_str_new(str, len)
Definition: string.h:213
VALUE rb_str_substr(VALUE, long, long)
Definition: string.c:2734
VALUE rb_str_intern(VALUE)
Definition: symbol.c:840
VALUE rb_str_dup(VALUE)
Definition: string.c:1631
VALUE rb_class_name(VALUE)
Definition: variable.c:293
VALUE rb_path2class(const char *)
Definition: variable.c:287
VALUE rb_attr_get(VALUE, ID)
Definition: variable.c:1242
VALUE rb_ivar_set(VALUE, ID, VALUE)
Definition: variable.c:1493
int rb_respond_to(VALUE, ID)
Definition: vm_method.c:2561
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
#define ID2SYM
Definition: symbol.h:44
#define SYM2ID
Definition: symbol.h:45
ID rb_intern(const char *)
Definition: symbol.c:785
VALUE rb_iv_get(VALUE, const char *)
Definition: variable.c:3569
voidpf void uLong size
Definition: ioapi.h:138
voidpf void * buf
Definition: ioapi.h:138
int isinf(double n)
Definition: isinf.c:56
#define LONG2FIX
Definition: long.h:49
#define FIX2LONG
Definition: long.h:46
#define MEMCPY(p1, p2, type, n)
Definition: memory.h:129
#define ALLOC_N
Definition: memory.h:133
#define RB_GC_GUARD(v)
Definition: memory.h:91
const char * name
Definition: nkf.c:208
#define RARRAY_LEN
Definition: rarray.h:52
#define NULL
Definition: regenc.h:69
#define StringValueCStr(v)
Definition: rstring.h:52
@ RUBY_TYPED_FREE_IMMEDIATELY
Definition: rtypeddata.h:62
@ RUBY_TYPED_FROZEN_SHAREABLE
Definition: rtypeddata.h:63
#define TypedData_Make_Struct(klass, type, data_type, sval)
Definition: rtypeddata.h:122
VALUE rb_require(const char *)
Definition: load.c:1199
int argc
Definition: ruby.c:240
char ** argv
Definition: ruby.c:241
#define Qtrue
#define RTEST
#define Qnil
#define Qfalse
#define NIL_P
#define FIXNUM_P
@ ST_CONTINUE
Definition: st.h:99
JSON_Generator_State * state
Definition: generator.c:812
FBuffer * buffer
Definition: generator.c:811
Definition: blast.c:41
unsigned long VALUE
Definition: value.h:38
unsigned long ID
Definition: value.h:39
#define T_STRING
Definition: value_type.h:77
#define T_BIGNUM
Definition: value_type.h:56
#define T_FIXNUM
Definition: value_type.h:62
#define T_HASH
Definition: value_type.h:64
#define rb_id2str(id)
Definition: vm_backtrace.c:30
#define isnan(x)
Definition: win32.h:346