From 4a84c27e3ee50c4989591fcde2b7a10c5ccc0395 Mon Sep 17 00:00:00 2001 From: naruse Date: Wed, 1 Dec 2010 16:26:13 +0000 Subject: * ext/json: Update github/flori/json from 1.4.2+ to e22b2f2bdfe6a9b0. this fixes some bugs. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@30003 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 + ext/json/generator/extconf.rb | 16 + ext/json/generator/generator.c | 561 +++++++++------- ext/json/generator/generator.h | 48 +- ext/json/lib/json/common.rb | 35 +- ext/json/lib/json/editor.rb | 1371 --------------------------------------- ext/json/lib/json/ext.rb | 4 +- ext/json/lib/json/version.rb | 2 +- ext/json/parser/extconf.rb | 11 + ext/json/parser/parser.c | 30 +- ext/json/parser/parser.rl | 30 +- test/json/test_json.rb | 60 +- test/json/test_json_addition.rb | 8 +- test/json/test_json_encoding.rb | 1 + test/json/test_json_generate.rb | 61 ++ test/json/test_json_rails.rb | 16 +- 16 files changed, 567 insertions(+), 1692 deletions(-) delete mode 100644 ext/json/lib/json/editor.rb diff --git a/ChangeLog b/ChangeLog index 6eb2c991f5..ae0bdc8169 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Thu Dec 2 01:02:03 2010 NARUSE, Yui + + * ext/json: Update github/flori/json from 1.4.2+ to + e22b2f2bdfe6a9b0. this fixes some bugs. + Thu Dec 2 00:05:44 2010 NARUSE, Yui * lib/net/http.rb: improve rdoc. diff --git a/ext/json/generator/extconf.rb b/ext/json/generator/extconf.rb index 195bfde3ff..149f22c13b 100644 --- a/ext/json/generator/extconf.rb +++ b/ext/json/generator/extconf.rb @@ -1,4 +1,20 @@ require 'mkmf' require 'rbconfig' +unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O3') + $CFLAGS << ' -O3' +end +if CONFIG['CC'] =~ /gcc/ + $CFLAGS << ' -Wall' + #unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O0 -ggdb') + # $CFLAGS << ' -O0 -ggdb' + #end +end + +if RUBY_VERSION < "1.9" + have_header("re.h") +else + have_header("ruby/re.h") + have_header("ruby/encoding.h") +end create_makefile 'json/ext/generator' diff --git a/ext/json/generator/generator.c b/ext/json/generator/generator.c index 1cbbdee194..65058820c7 100644 --- a/ext/json/generator/generator.c +++ b/ext/json/generator/generator.c @@ -6,20 +6,21 @@ static ID i_encoding, i_encode; #endif static VALUE mJSON, mExt, mGenerator, cState, mGeneratorMethods, mObject, - mHash, mArray, mInteger, mFloat, mString, mString_Extend, + mHash, mArray, mFixnum, mBignum, mFloat, mString, mString_Extend, mTrueClass, mFalseClass, mNilClass, eGeneratorError, - eNestingError, CRegexp_MULTILINE, CJSON_SAFE_STATE_PROTOTYPE; + eNestingError, CRegexp_MULTILINE, CJSON_SAFE_STATE_PROTOTYPE, + i_SAFE_STATE_PROTOTYPE; static ID i_to_s, i_to_json, i_new, i_indent, i_space, i_space_before, i_object_nl, i_array_nl, i_max_nesting, i_allow_nan, i_ascii_only, i_pack, i_unpack, i_create_id, i_extend, i_key_p, i_aref, i_send, - i_respond_to_p, i_match; + i_respond_to_p, i_match, i_keys, i_depth, i_dup; /* * Copyright 2001-2004 Unicode, Inc. - * + * * Disclaimer - * + * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine @@ -27,9 +28,9 @@ static ID i_to_s, i_to_json, i_new, i_indent, i_space, i_space_before, * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. - * + * * Limitations on Rights to Redistribute This Code - * + * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form @@ -60,7 +61,7 @@ static const char trailingBytesForUTF8[256] = { * This table contains as many values as there might be trailing bytes * in a UTF-8 sequence. */ -static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, +static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; /* @@ -73,7 +74,7 @@ static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080 * If presented with a length > 4, this returns 0. The Unicode * definition of UTF-8 goes up to 4-byte sequences. */ -static unsigned char isLegalUTF8(const UTF8 *source, int length) +static unsigned char isLegalUTF8(const UTF8 *source, unsigned long length) { UTF8 a; const UTF8 *srcptr = source+length; @@ -222,7 +223,7 @@ static void convert_UTF8_to_JSON_ASCII(FBuffer *buffer, VALUE string) static void convert_UTF8_to_JSON(FBuffer *buffer, VALUE string) { const char *ptr = RSTRING_PTR(string), *p; - int len = RSTRING_LEN(string), start = 0, end = 0; + unsigned long len = RSTRING_LEN(string), start = 0, end = 0; const char *escape = NULL; int escape_len; unsigned char c; @@ -283,7 +284,7 @@ static void convert_UTF8_to_JSON(FBuffer *buffer, VALUE string) fbuffer_append(buffer, ptr + start, end - start); } -static char *fstrndup(const char *ptr, int len) { +static char *fstrndup(const char *ptr, unsigned long len) { char *result; if (len <= 0) return NULL; result = ALLOC_N(char, len); @@ -301,7 +302,7 @@ static FBuffer *fbuffer_alloc() return fb; } -static FBuffer *fbuffer_alloc_with_length(unsigned int initial_length) +static FBuffer *fbuffer_alloc_with_length(unsigned long initial_length) { FBuffer *fb; assert(initial_length > 0); @@ -317,14 +318,19 @@ static void fbuffer_free(FBuffer *fb) ruby_xfree(fb); } +static void fbuffer_free_only_buffer(FBuffer *fb) +{ + ruby_xfree(fb); +} + static void fbuffer_clear(FBuffer *fb) { fb->len = 0; } -static void fbuffer_inc_capa(FBuffer *fb, unsigned int requested) +static void fbuffer_inc_capa(FBuffer *fb, unsigned long requested) { - unsigned int required; + unsigned long required; if (!fb->ptr) { fb->ptr = ALLOC_N(char, fb->initial_length); @@ -339,7 +345,7 @@ static void fbuffer_inc_capa(FBuffer *fb, unsigned int requested) } } -static void fbuffer_append(FBuffer *fb, const char *newstr, unsigned int len) +static void fbuffer_append(FBuffer *fb, const char *newstr, unsigned long len) { if (len > 0) { fbuffer_inc_capa(fb, len); @@ -357,36 +363,36 @@ static void fbuffer_append_char(FBuffer *fb, char newchr) static void freverse(char *start, char *end) { - char c; + char c; - while (end > start) { - c = *end, *end-- = *start, *start++ = c; + while (end > start) { + c = *end, *end-- = *start, *start++ = c; } } -static int fltoa(long number, char *buf) +static long fltoa(long number, char *buf) { - static char digits[] = "0123456789"; - long sign = number; - char* tmp = buf; + static char digits[] = "0123456789"; + long sign = number; + char* tmp = buf; - if (sign < 0) number = -number; + if (sign < 0) number = -number; do *tmp++ = digits[number % 10]; while (number /= 10); - if (sign < 0) *tmp++ = '-'; - freverse(buf, tmp - 1); + if (sign < 0) *tmp++ = '-'; + freverse(buf, tmp - 1); return tmp - buf; } static void fbuffer_append_long(FBuffer *fb, long number) { char buf[20]; - int len = fltoa(number, buf); + unsigned long len = fltoa(number, buf); fbuffer_append(fb, buf, len); } static FBuffer *fbuffer_dup(FBuffer *fb) { - int len = fb->len; + unsigned long len = fb->len; FBuffer *result; if (len > 0) { @@ -398,7 +404,7 @@ static FBuffer *fbuffer_dup(FBuffer *fb) return result; } -/* +/* * Document-module: JSON::Ext::Generator * * This is the JSON generator implemented as a C extension. It can be @@ -411,37 +417,28 @@ static FBuffer *fbuffer_dup(FBuffer *fb) */ /* - * call-seq: to_json(state = nil, depth = 0) + * call-seq: to_json(state = nil) * * Returns a JSON string containing a JSON object, that is generated from * this Hash instance. * _state_ is a JSON::State object, that can also be used to configure the * produced JSON string output further. - * _depth_ is used to find out nesting depth, to indent accordingly. */ static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self) { - VALUE state, depth; - - rb_scan_args(argc, argv, "02", &state, &depth); - state = cState_from_state_s(cState, state); - return cState_partial_generate(state, self, depth); + GENERATE_JSON(object); } /* - * call-seq: to_json(state = nil, depth = 0) + * call-seq: to_json(state = nil) * * Returns a JSON string containing a JSON array, that is generated from * this Array instance. * _state_ is a JSON::State object, that can also be used to configure the * produced JSON string output further. - * _depth_ is used to find out nesting depth, to indent accordingly. */ static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self) { - VALUE state, depth; - rb_scan_args(argc, argv, "02", &state, &depth); - state = cState_from_state_s(cState, state); - return cState_partial_generate(state, self, depth); + GENERATE_JSON(array); } /* @@ -449,12 +446,19 @@ static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self) { * * Returns a JSON string representation for this Integer number. */ -static VALUE mInteger_to_json(int argc, VALUE *argv, VALUE self) +static VALUE mFixnum_to_json(int argc, VALUE *argv, VALUE self) { - VALUE state, depth; - rb_scan_args(argc, argv, "02", &state, &depth); - state = cState_from_state_s(cState, state); - return cState_partial_generate(state, self, depth); + GENERATE_JSON(fixnum); +} + +/* + * call-seq: to_json(*) + * + * Returns a JSON string representation for this Integer number. + */ +static VALUE mBignum_to_json(int argc, VALUE *argv, VALUE self) +{ + GENERATE_JSON(bignum); } /* @@ -464,10 +468,7 @@ static VALUE mInteger_to_json(int argc, VALUE *argv, VALUE self) */ static VALUE mFloat_to_json(int argc, VALUE *argv, VALUE self) { - VALUE state, depth; - rb_scan_args(argc, argv, "02", &state, &depth); - state = cState_from_state_s(cState, state); - return cState_partial_generate(state, self, depth); + GENERATE_JSON(float); } /* @@ -489,10 +490,7 @@ static VALUE mString_included_s(VALUE self, VALUE modul) { */ static VALUE mString_to_json(int argc, VALUE *argv, VALUE self) { - VALUE state, depth; - rb_scan_args(argc, argv, "02", &state, &depth); - state = cState_from_state_s(cState, state); - return cState_partial_generate(state, self, depth); + GENERATE_JSON(string); } /* @@ -547,10 +545,7 @@ static VALUE mString_Extend_json_create(VALUE self, VALUE o) */ static VALUE mTrueClass_to_json(int argc, VALUE *argv, VALUE self) { - VALUE state, depth; - rb_scan_args(argc, argv, "02", &state, &depth); - state = cState_from_state_s(cState, state); - return cState_partial_generate(state, self, depth); + GENERATE_JSON(true); } /* @@ -560,10 +555,7 @@ static VALUE mTrueClass_to_json(int argc, VALUE *argv, VALUE self) */ static VALUE mFalseClass_to_json(int argc, VALUE *argv, VALUE self) { - VALUE state, depth; - rb_scan_args(argc, argv, "02", &state, &depth); - state = cState_from_state_s(cState, state); - return cState_partial_generate(state, self, depth); + GENERATE_JSON(false); } /* @@ -572,10 +564,7 @@ static VALUE mFalseClass_to_json(int argc, VALUE *argv, VALUE self) */ static VALUE mNilClass_to_json(int argc, VALUE *argv, VALUE self) { - VALUE state, depth; - rb_scan_args(argc, argv, "02", &state, &depth); - state = cState_from_state_s(cState, state); - return cState_partial_generate(state, self, depth); + GENERATE_JSON(null); } /* @@ -587,12 +576,12 @@ static VALUE mNilClass_to_json(int argc, VALUE *argv, VALUE self) */ static VALUE mObject_to_json(int argc, VALUE *argv, VALUE self) { - VALUE state, depth; + VALUE state; VALUE string = rb_funcall(self, i_to_s, 0); - rb_scan_args(argc, argv, "02", &state, &depth); + rb_scan_args(argc, argv, "01", &state); Check_Type(string, T_STRING); state = cState_from_state_s(cState, state); - return cState_partial_generate(state, string, depth); + return cState_partial_generate(state, string); } static void State_free(JSON_Generator_State *state) @@ -611,6 +600,7 @@ static void State_free(JSON_Generator_State *state) static JSON_Generator_State *State_allocate() { JSON_Generator_State *state = ALLOC(JSON_Generator_State); + MEMZERO(state, JSON_Generator_State, 1); return state; } @@ -638,7 +628,7 @@ static VALUE cState_configure(VALUE self, VALUE opts) opts = tmp; tmp = rb_hash_aref(opts, ID2SYM(i_indent)); if (RTEST(tmp)) { - int len; + unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->indent = fstrndup(RSTRING_PTR(tmp), len); @@ -646,7 +636,7 @@ static VALUE cState_configure(VALUE self, VALUE opts) } tmp = rb_hash_aref(opts, ID2SYM(i_space)); if (RTEST(tmp)) { - int len; + unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->space = fstrndup(RSTRING_PTR(tmp), len); @@ -654,7 +644,7 @@ static VALUE cState_configure(VALUE self, VALUE opts) } tmp = rb_hash_aref(opts, ID2SYM(i_space_before)); if (RTEST(tmp)) { - int len; + unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->space_before = fstrndup(RSTRING_PTR(tmp), len); @@ -662,7 +652,7 @@ static VALUE cState_configure(VALUE self, VALUE opts) } tmp = rb_hash_aref(opts, ID2SYM(i_array_nl)); if (RTEST(tmp)) { - int len; + unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->array_nl = fstrndup(RSTRING_PTR(tmp), len); @@ -670,7 +660,7 @@ static VALUE cState_configure(VALUE self, VALUE opts) } tmp = rb_hash_aref(opts, ID2SYM(i_object_nl)); if (RTEST(tmp)) { - int len; + unsigned long len; Check_Type(tmp, T_STRING); len = RSTRING_LEN(tmp); state->object_nl = fstrndup(RSTRING_PTR(tmp), len); @@ -687,6 +677,17 @@ static VALUE cState_configure(VALUE self, VALUE opts) state->max_nesting = 0; } } + tmp = ID2SYM(i_depth); + state->depth = 0; + if (option_given_p(opts, tmp)) { + VALUE depth = rb_hash_aref(opts, tmp); + if (RTEST(depth)) { + Check_Type(depth, T_FIXNUM); + state->depth = FIX2LONG(depth); + } else { + state->depth = 0; + } + } tmp = rb_hash_aref(opts, ID2SYM(i_allow_nan)); state->allow_nan = RTEST(tmp); tmp = rb_hash_aref(opts, ID2SYM(i_ascii_only)); @@ -712,6 +713,7 @@ static VALUE cState_to_h(VALUE self) rb_hash_aset(result, ID2SYM(i_allow_nan), state->allow_nan ? Qtrue : Qfalse); rb_hash_aset(result, ID2SYM(i_ascii_only), state->ascii_only ? Qtrue : Qfalse); rb_hash_aset(result, ID2SYM(i_max_nesting), LONG2FIX(state->max_nesting)); + rb_hash_aset(result, ID2SYM(i_depth), LONG2FIX(state->depth)); return result; } @@ -730,165 +732,185 @@ static VALUE cState_aref(VALUE self, VALUE name) } } -static void generate_json(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj, long depth) +static void generate_json_object(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) { - VALUE tmp; - switch (TYPE(obj)) { - case T_HASH: - { - char *object_nl = state->object_nl; - long object_nl_len = state->object_nl_len; - char *indent = state->indent; - long indent_len = state->indent_len; - long max_nesting = state->max_nesting; - char *delim = FBUFFER_PTR(state->object_delim); - long delim_len = FBUFFER_LEN(state->object_delim); - char *delim2 = FBUFFER_PTR(state->object_delim2); - long delim2_len = FBUFFER_LEN(state->object_delim2); - int i, j; - VALUE key, key_to_s, keys; - depth++; - if (max_nesting != 0 && depth > max_nesting) { - fbuffer_free(buffer); - rb_raise(eNestingError, "nesting of %ld is too deep", depth); - } - fbuffer_append_char(buffer, '{'); - keys = rb_funcall(obj, rb_intern("keys"), 0); - for(i = 0; i < RARRAY_LEN(keys); i++) { - if (i > 0) fbuffer_append(buffer, delim, delim_len); - if (object_nl) { - fbuffer_append(buffer, object_nl, object_nl_len); - } - if (indent) { - for (j = 0; j < depth; j++) { - fbuffer_append(buffer, indent, indent_len); - } - } - key = rb_ary_entry(keys, i); - key_to_s = rb_funcall(key, i_to_s, 0); - Check_Type(key_to_s, T_STRING); - generate_json(buffer, Vstate, state, key_to_s, depth); - fbuffer_append(buffer, delim2, delim2_len); - generate_json(buffer, Vstate, state, rb_hash_aref(obj, key), depth); - } - depth--; - if (object_nl) { - fbuffer_append(buffer, object_nl, object_nl_len); - if (indent) { - for (j = 0; j < depth; j++) { - fbuffer_append(buffer, indent, indent_len); - } - } - } - fbuffer_append_char(buffer, '}'); - } - break; - case T_ARRAY: - { - char *array_nl = state->array_nl; - long array_nl_len = state->array_nl_len; - char *indent = state->indent; - long indent_len = state->indent_len; - long max_nesting = state->max_nesting; - char *delim = FBUFFER_PTR(state->array_delim); - long delim_len = FBUFFER_LEN(state->array_delim); - int i, j; - depth++; - if (max_nesting != 0 && depth > max_nesting) { - fbuffer_free(buffer); - rb_raise(eNestingError, "nesting of %ld is too deep", depth); - } - fbuffer_append_char(buffer, '['); - if (array_nl) fbuffer_append(buffer, array_nl, array_nl_len); - for(i = 0; i < RARRAY_LEN(obj); i++) { - if (i > 0) fbuffer_append(buffer, delim, delim_len); - if (indent) { - for (j = 0; j < depth; j++) { - fbuffer_append(buffer, indent, indent_len); - } - } - generate_json(buffer, Vstate, state, rb_ary_entry(obj, i), depth); - } - depth--; - if (array_nl) { - fbuffer_append(buffer, array_nl, array_nl_len); - if (indent) { - for (j = 0; j < depth; j++) { - fbuffer_append(buffer, indent, indent_len); - } - } - } - fbuffer_append_char(buffer, ']'); + char *object_nl = state->object_nl; + long object_nl_len = state->object_nl_len; + char *indent = state->indent; + long indent_len = state->indent_len; + long max_nesting = state->max_nesting; + char *delim = FBUFFER_PTR(state->object_delim); + long delim_len = FBUFFER_LEN(state->object_delim); + char *delim2 = FBUFFER_PTR(state->object_delim2); + long delim2_len = FBUFFER_LEN(state->object_delim2); + long depth = ++state->depth; + int i, j; + VALUE key, key_to_s, keys; + if (max_nesting != 0 && depth > max_nesting) { + fbuffer_free(buffer); + rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth); + } + fbuffer_append_char(buffer, '{'); + keys = rb_funcall(obj, i_keys, 0); + for(i = 0; i < RARRAY_LEN(keys); i++) { + if (i > 0) fbuffer_append(buffer, delim, delim_len); + if (object_nl) { + fbuffer_append(buffer, object_nl, object_nl_len); + } + if (indent) { + for (j = 0; j < depth; j++) { + fbuffer_append(buffer, indent, indent_len); } - break; - case T_STRING: - fbuffer_append_char(buffer, '"'); -#ifdef HAVE_RUBY_ENCODING_H - obj = rb_funcall(obj, i_encode, 1, CEncoding_UTF_8); -#endif - if (state->ascii_only) { - convert_UTF8_to_JSON_ASCII(buffer, obj); - } else { - convert_UTF8_to_JSON(buffer, obj); + } + key = rb_ary_entry(keys, i); + key_to_s = rb_funcall(key, i_to_s, 0); + Check_Type(key_to_s, T_STRING); + generate_json(buffer, Vstate, state, key_to_s); + fbuffer_append(buffer, delim2, delim2_len); + generate_json(buffer, Vstate, state, rb_hash_aref(obj, key)); + } + depth = --state->depth; + if (object_nl) { + fbuffer_append(buffer, object_nl, object_nl_len); + if (indent) { + for (j = 0; j < depth; j++) { + fbuffer_append(buffer, indent, indent_len); } - fbuffer_append_char(buffer, '"'); - break; - case T_NIL: - fbuffer_append(buffer, "null", 4); - break; - case T_FALSE: - fbuffer_append(buffer, "false", 5); - break; - case T_TRUE: - fbuffer_append(buffer, "true", 4); - break; - case T_FIXNUM: - fbuffer_append_long(buffer, FIX2LONG(obj)); - break; - case T_BIGNUM: - tmp = rb_funcall(obj, i_to_s, 0); - fbuffer_append(buffer, RSTRING_PAIR(tmp)); - break; - case T_FLOAT: - { - double value = RFLOAT_VALUE(obj); - char allow_nan = state->allow_nan; - tmp = rb_funcall(obj, i_to_s, 0); - if (!allow_nan) { - if (isinf(value)) { - fbuffer_free(buffer); - rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp)); - } else if (isnan(value)) { - fbuffer_free(buffer); - rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp)); - } - } - fbuffer_append(buffer, RSTRING_PAIR(tmp)); + } + } + fbuffer_append_char(buffer, '}'); +} + +static void generate_json_array(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) +{ + char *array_nl = state->array_nl; + long array_nl_len = state->array_nl_len; + char *indent = state->indent; + long indent_len = state->indent_len; + long max_nesting = state->max_nesting; + char *delim = FBUFFER_PTR(state->array_delim); + long delim_len = FBUFFER_LEN(state->array_delim); + long depth = ++state->depth; + int i, j; + if (max_nesting != 0 && depth > max_nesting) { + fbuffer_free(buffer); + rb_raise(eNestingError, "nesting of %ld is too deep", --state->depth); + } + fbuffer_append_char(buffer, '['); + if (array_nl) fbuffer_append(buffer, array_nl, array_nl_len); + for(i = 0; i < RARRAY_LEN(obj); i++) { + if (i > 0) fbuffer_append(buffer, delim, delim_len); + if (indent) { + for (j = 0; j < depth; j++) { + fbuffer_append(buffer, indent, indent_len); } - break; - default: - if (rb_respond_to(obj, i_to_json)) { - tmp = rb_funcall(obj, i_to_json, 2, Vstate, INT2FIX(depth + 1)); - Check_Type(tmp, T_STRING); - fbuffer_append(buffer, RSTRING_PAIR(tmp)); - } else { - tmp = rb_funcall(obj, i_to_s, 0); - Check_Type(tmp, T_STRING); - generate_json(buffer, Vstate, state, tmp, depth + 1); + } + generate_json(buffer, Vstate, state, rb_ary_entry(obj, i)); + } + state->depth = --depth; + if (array_nl) { + fbuffer_append(buffer, array_nl, array_nl_len); + if (indent) { + for (j = 0; j < depth; j++) { + fbuffer_append(buffer, indent, indent_len); } - break; + } } + fbuffer_append_char(buffer, ']'); } -/* - * call-seq: partial_generate(obj) - * - * Generates a part of a JSON document from object +obj+ and returns the - * result. - */ -static VALUE cState_partial_generate(VALUE self, VALUE obj, VALUE depth) +static void generate_json_string(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) +{ + fbuffer_append_char(buffer, '"'); +#ifdef HAVE_RUBY_ENCODING_H + obj = rb_funcall(obj, i_encode, 1, CEncoding_UTF_8); +#endif + if (state->ascii_only) { + convert_UTF8_to_JSON_ASCII(buffer, obj); + } else { + convert_UTF8_to_JSON(buffer, obj); + } + fbuffer_append_char(buffer, '"'); +} + +static void generate_json_null(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) +{ + fbuffer_append(buffer, "null", 4); +} + +static void generate_json_false(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) +{ + fbuffer_append(buffer, "false", 5); +} + +static void generate_json_true(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) +{ + fbuffer_append(buffer, "true", 4); +} + +static void generate_json_fixnum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) +{ + fbuffer_append_long(buffer, FIX2LONG(obj)); +} + +static void generate_json_bignum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) +{ + VALUE tmp = rb_funcall(obj, i_to_s, 0); + fbuffer_append(buffer, RSTRING_PAIR(tmp)); +} + +static void generate_json_float(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) +{ + double value = RFLOAT_VALUE(obj); + char allow_nan = state->allow_nan; + VALUE tmp = rb_funcall(obj, i_to_s, 0); + if (!allow_nan) { + if (isinf(value)) { + fbuffer_free(buffer); + rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp)); + } else if (isnan(value)) { + fbuffer_free(buffer); + rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp)); + } + } + fbuffer_append(buffer, RSTRING_PAIR(tmp)); +} + +static void generate_json(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj) +{ + VALUE tmp; + VALUE klass = CLASS_OF(obj); + if (klass == rb_cHash) { + generate_json_object(buffer, Vstate, state, obj); + } else if (klass == rb_cArray) { + generate_json_array(buffer, Vstate, state, obj); + } else if (klass == rb_cString) { + generate_json_string(buffer, Vstate, state, obj); + } else if (obj == Qnil) { + generate_json_null(buffer, Vstate, state, obj); + } else if (obj == Qfalse) { + generate_json_false(buffer, Vstate, state, obj); + } else if (obj == Qtrue) { + generate_json_true(buffer, Vstate, state, obj); + } else if (klass == rb_cFixnum) { + generate_json_fixnum(buffer, Vstate, state, obj); + } else if (klass == rb_cBignum) { + generate_json_bignum(buffer, Vstate, state, obj); + } else if (klass == rb_cFloat) { + generate_json_float(buffer, Vstate, state, obj); + } else if (rb_respond_to(obj, i_to_json)) { + tmp = rb_funcall(obj, i_to_json, 1, Vstate); + Check_Type(tmp, T_STRING); + fbuffer_append(buffer, RSTRING_PAIR(tmp)); + } else { + tmp = rb_funcall(obj, i_to_s, 0); + Check_Type(tmp, T_STRING); + generate_json(buffer, Vstate, state, tmp); + } +} + +static FBuffer *cState_prepare_buffer(VALUE self) { - VALUE result; FBuffer *buffer = fbuffer_alloc(); GET_STATE(self); @@ -913,14 +935,25 @@ static VALUE cState_partial_generate(VALUE self, VALUE obj, VALUE depth) } fbuffer_append_char(state->array_delim, ','); if (state->array_nl) fbuffer_append(state->array_delim, state->array_nl, state->array_nl_len); + return buffer; +} - generate_json(buffer, self, state, obj, NIL_P(depth) ? 0 : FIX2INT(depth)); - result = rb_str_new(FBUFFER_PAIR(buffer)); - fbuffer_free(buffer); +static VALUE fbuffer_to_s(FBuffer *fb) +{ + VALUE result = rb_str_new(FBUFFER_PAIR(fb)); + fbuffer_free(fb); FORCE_UTF8(result); return result; } +static VALUE cState_partial_generate(VALUE self, VALUE obj) +{ + FBuffer *buffer = cState_prepare_buffer(self); + GET_STATE(self); + generate_json(buffer, self, state, obj); + return fbuffer_to_s(buffer); +} + /* * call-seq: generate(obj) * @@ -930,7 +963,7 @@ static VALUE cState_partial_generate(VALUE self, VALUE obj, VALUE depth) */ static VALUE cState_generate(VALUE self, VALUE obj) { - VALUE result = cState_partial_generate(self, obj, Qnil); + VALUE result = cState_partial_generate(self, obj); VALUE re, args[2]; args[0] = rb_str_new2("\\A\\s*(?:\\[.*\\]|\\{.*\\})\\s*\\Z"); args[1] = CRegexp_MULTILINE; @@ -951,7 +984,7 @@ static VALUE cState_generate(VALUE self, VALUE obj) * * *indent*: a string used to indent levels (default: ''), * * *space*: a string that is put after, a : or , delimiter (default: ''), * * *space_before*: a string that is put before a : pair delimiter (default: ''), - * * *object_nl*: a string that is put at the end of a JSON object (default: ''), + * * *object_nl*: a string that is put at the end of a JSON object (default: ''), * * *array_nl*: a string that is put at the end of a JSON array (default: ''), * * *allow_nan*: true if NaN, Infinity, and -Infinity should be * generated, otherwise an exception is thrown, if these values are @@ -961,7 +994,6 @@ static VALUE cState_initialize(int argc, VALUE *argv, VALUE self) { VALUE opts; GET_STATE(self); - MEMZERO(state, JSON_Generator_State, 1); state->max_nesting = 19; rb_scan_args(argc, argv, "01", &opts); if (!NIL_P(opts)) cState_configure(self, opts); @@ -1009,9 +1041,9 @@ static VALUE cState_from_state_s(VALUE self, VALUE opts) return rb_funcall(self, i_new, 1, opts); } else { if (NIL_P(CJSON_SAFE_STATE_PROTOTYPE)) { - CJSON_SAFE_STATE_PROTOTYPE = rb_const_get(mJSON, rb_intern("SAFE_STATE_PROTOTYPE")); + CJSON_SAFE_STATE_PROTOTYPE = rb_const_get(mJSON, i_SAFE_STATE_PROTOTYPE); } - return CJSON_SAFE_STATE_PROTOTYPE; + return rb_funcall(CJSON_SAFE_STATE_PROTOTYPE, i_dup, 0); } } @@ -1033,16 +1065,20 @@ static VALUE cState_indent(VALUE self) */ static VALUE cState_indent_set(VALUE self, VALUE indent) { + unsigned long len; GET_STATE(self); Check_Type(indent, T_STRING); - if (RSTRING_LEN(indent) == 0) { + len = RSTRING_LEN(indent); + if (len == 0) { if (state->indent) { ruby_xfree(state->indent); state->indent = NULL; + state->indent_len = 0; } } else { if (state->indent) ruby_xfree(state->indent); state->indent = strdup(RSTRING_PTR(indent)); + state->indent_len = len; } return Qnil; } @@ -1067,16 +1103,20 @@ static VALUE cState_space(VALUE self) */ static VALUE cState_space_set(VALUE self, VALUE space) { + unsigned long len; GET_STATE(self); Check_Type(space, T_STRING); - if (RSTRING_LEN(space) == 0) { + len = RSTRING_LEN(space); + if (len == 0) { if (state->space) { ruby_xfree(state->space); state->space = NULL; + state->space_len = 0; } } else { if (state->space) ruby_xfree(state->space); state->space = strdup(RSTRING_PTR(space)); + state->space_len = len; } return Qnil; } @@ -1099,16 +1139,20 @@ static VALUE cState_space_before(VALUE self) */ static VALUE cState_space_before_set(VALUE self, VALUE space_before) { + unsigned long len; GET_STATE(self); Check_Type(space_before, T_STRING); - if (RSTRING_LEN(space_before) == 0) { + len = RSTRING_LEN(space_before); + if (len == 0) { if (state->space_before) { ruby_xfree(state->space_before); state->space_before = NULL; + state->space_before_len = 0; } } else { if (state->space_before) ruby_xfree(state->space_before); state->space_before = strdup(RSTRING_PTR(space_before)); + state->space_before_len = len; } return Qnil; } @@ -1133,9 +1177,11 @@ static VALUE cState_object_nl(VALUE self) */ static VALUE cState_object_nl_set(VALUE self, VALUE object_nl) { + unsigned long len; GET_STATE(self); Check_Type(object_nl, T_STRING); - if (RSTRING_LEN(object_nl) == 0) { + len = RSTRING_LEN(object_nl); + if (len == 0) { if (state->object_nl) { ruby_xfree(state->object_nl); state->object_nl = NULL; @@ -1143,6 +1189,7 @@ static VALUE cState_object_nl_set(VALUE self, VALUE object_nl) } else { if (state->object_nl) ruby_xfree(state->object_nl); state->object_nl = strdup(RSTRING_PTR(object_nl)); + state->object_nl_len = len; } return Qnil; } @@ -1165,9 +1212,11 @@ static VALUE cState_array_nl(VALUE self) */ static VALUE cState_array_nl_set(VALUE self, VALUE array_nl) { + unsigned long len; GET_STATE(self); Check_Type(array_nl, T_STRING); - if (RSTRING_LEN(array_nl) == 0) { + len = RSTRING_LEN(array_nl); + if (len == 0) { if (state->array_nl) { ruby_xfree(state->array_nl); state->array_nl = NULL; @@ -1175,6 +1224,7 @@ static VALUE cState_array_nl_set(VALUE self, VALUE array_nl) } else { if (state->array_nl) ruby_xfree(state->array_nl); state->array_nl = strdup(RSTRING_PTR(array_nl)); + state->array_nl_len = len; } return Qnil; } @@ -1241,6 +1291,30 @@ static VALUE cState_ascii_only_p(VALUE self) return state->ascii_only ? Qtrue : Qfalse; } +/* + * call-seq: depth + * + * This integer returns the current depth of data structure nesting. + */ +static VALUE cState_depth(VALUE self) +{ + GET_STATE(self); + return LONG2FIX(state->depth); +} + +/* + * call-seq: depth=(depth) + * + * This sets the maximum level of data structure nesting in the generated JSON + * to the integer depth, max_nesting = 0 if no maximum should be checked. + */ +static VALUE cState_depth_set(VALUE self, VALUE depth) +{ + GET_STATE(self); + Check_Type(depth, T_FIXNUM); + return state->depth = FIX2LONG(depth); +} + /* * */ @@ -1275,11 +1349,12 @@ void Init_generator() rb_define_method(cState, "check_circular?", cState_check_circular_p, 0); rb_define_method(cState, "allow_nan?", cState_allow_nan_p, 0); rb_define_method(cState, "ascii_only?", cState_ascii_only_p, 0); + rb_define_method(cState, "depth", cState_depth, 0); + rb_define_method(cState, "depth=", cState_depth_set, 1); rb_define_method(cState, "configure", cState_configure, 1); rb_define_method(cState, "to_h", cState_to_h, 0); rb_define_method(cState, "[]", cState_aref, 1); rb_define_method(cState, "generate", cState_generate, 1); - rb_define_method(cState, "partial_generate", cState_partial_generate, 1); mGeneratorMethods = rb_define_module_under(mGenerator, "GeneratorMethods"); mObject = rb_define_module_under(mGeneratorMethods, "Object"); @@ -1288,8 +1363,10 @@ void Init_generator() rb_define_method(mHash, "to_json", mHash_to_json, -1); mArray = rb_define_module_under(mGeneratorMethods, "Array"); rb_define_method(mArray, "to_json", mArray_to_json, -1); - mInteger = rb_define_module_under(mGeneratorMethods, "Integer"); - rb_define_method(mInteger, "to_json", mInteger_to_json, -1); + mFixnum = rb_define_module_under(mGeneratorMethods, "Fixnum"); + rb_define_method(mFixnum, "to_json", mFixnum_to_json, -1); + mBignum = rb_define_module_under(mGeneratorMethods, "Bignum"); + rb_define_method(mBignum, "to_json", mBignum_to_json, -1); mFloat = rb_define_module_under(mGeneratorMethods, "Float"); rb_define_method(mFloat, "to_json", mFloat_to_json, -1); mString = rb_define_module_under(mGeneratorMethods, "String"); @@ -1318,6 +1395,7 @@ void Init_generator() i_max_nesting = rb_intern("max_nesting"); i_allow_nan = rb_intern("allow_nan"); i_ascii_only = rb_intern("ascii_only"); + i_depth = rb_intern("depth"); i_pack = rb_intern("pack"); i_unpack = rb_intern("unpack"); i_create_id = rb_intern("create_id"); @@ -1327,10 +1405,13 @@ void Init_generator() i_send = rb_intern("__send__"); i_respond_to_p = rb_intern("respond_to?"); i_match = rb_intern("match"); + i_keys = rb_intern("keys"); + i_dup = rb_intern("dup"); #ifdef HAVE_RUBY_ENCODING_H CEncoding_UTF_8 = rb_funcall(rb_path2class("Encoding"), rb_intern("find"), 1, rb_str_new2("utf-8")); i_encoding = rb_intern("encoding"); i_encode = rb_intern("encode"); #endif + i_SAFE_STATE_PROTOTYPE = rb_intern("SAFE_STATE_PROTOTYPE"); CJSON_SAFE_STATE_PROTOTYPE = Qnil; } diff --git a/ext/json/generator/generator.h b/ext/json/generator/generator.h index 35c66af379..e47f507b0d 100644 --- a/ext/json/generator/generator.h +++ b/ext/json/generator/generator.h @@ -50,10 +50,10 @@ /* fbuffer implementation */ typedef struct FBufferStruct { - unsigned int initial_length; + unsigned long initial_length; char *ptr; - unsigned int len; - unsigned int capa; + unsigned long len; + unsigned long capa; } FBuffer; #define FBUFFER_INITIAL_LENGTH 4096 @@ -63,15 +63,17 @@ typedef struct FBufferStruct { #define FBUFFER_CAPA(fb) (fb->capa) #define FBUFFER_PAIR(fb) FBUFFER_PTR(fb), FBUFFER_LEN(fb) -static char *fstrndup(const char *ptr, int len); +static char *fstrndup(const char *ptr, unsigned long len); static FBuffer *fbuffer_alloc(); -static FBuffer *fbuffer_alloc_with_length(unsigned initial_length); +static FBuffer *fbuffer_alloc_with_length(unsigned long initial_length); static void fbuffer_free(FBuffer *fb); +static void fbuffer_free_only_buffer(FBuffer *fb); static void fbuffer_clear(FBuffer *fb); -static void fbuffer_append(FBuffer *fb, const char *newstr, unsigned int len); +static void fbuffer_append(FBuffer *fb, const char *newstr, unsigned long len); static void fbuffer_append_long(FBuffer *fb, long number); static void fbuffer_append_char(FBuffer *fb, char newchr); static FBuffer *fbuffer_dup(FBuffer *fb); +static VALUE fbuffer_to_s(FBuffer *fb); /* unicode defintions */ @@ -97,7 +99,7 @@ static const int halfShift = 10; /* used for shifting by 10 bits */ static const UTF32 halfBase = 0x0010000UL; static const UTF32 halfMask = 0x3FFUL; -static unsigned char isLegalUTF8(const UTF8 *source, int length); +static unsigned char isLegalUTF8(const UTF8 *source, unsigned long length); static void unicode_escape(char *buf, UTF16 character); static void unicode_escape_to_buffer(FBuffer *buffer, char buf[6], UTF16 character); static void convert_UTF8_to_JSON_ASCII(FBuffer *buffer, VALUE string); @@ -122,15 +124,29 @@ typedef struct JSON_Generator_StateStruct { long max_nesting; char allow_nan; char ascii_only; + long depth; } JSON_Generator_State; #define GET_STATE(self) \ JSON_Generator_State *state; \ Data_Get_Struct(self, JSON_Generator_State, state) +#define GENERATE_JSON(type) \ + FBuffer *buffer; \ + VALUE Vstate; \ + JSON_Generator_State *state; \ + \ + rb_scan_args(argc, argv, "01", &Vstate); \ + Vstate = cState_from_state_s(cState, Vstate); \ + Data_Get_Struct(Vstate, JSON_Generator_State, state); \ + buffer = cState_prepare_buffer(Vstate); \ + generate_json_##type(buffer, Vstate, state, self); \ + return fbuffer_to_s(buffer) + static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self); static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self); -static VALUE mInteger_to_json(int argc, VALUE *argv, VALUE self); +static VALUE mFixnum_to_json(int argc, VALUE *argv, VALUE self); +static VALUE mBignum_to_json(int argc, VALUE *argv, VALUE self); static VALUE mFloat_to_json(int argc, VALUE *argv, VALUE self); static VALUE mString_included_s(VALUE self, VALUE modul); static VALUE mString_to_json(int argc, VALUE *argv, VALUE self); @@ -146,8 +162,17 @@ static JSON_Generator_State *State_allocate(); static VALUE cState_s_allocate(VALUE klass); static VALUE cState_configure(VALUE self, VALUE opts); static VALUE cState_to_h(VALUE self); -static void generate_json(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj, long depth); -static VALUE cState_partial_generate(VALUE self, VALUE obj, VALUE depth); +static void generate_json(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static void generate_json_object(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static void generate_json_array(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static void generate_json_string(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static void generate_json_null(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static void generate_json_false(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static void generate_json_true(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static void generate_json_fixnum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static void generate_json_bignum(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static void generate_json_float(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj); +static VALUE cState_partial_generate(VALUE self, VALUE obj); static VALUE cState_generate(VALUE self, VALUE obj); static VALUE cState_initialize(int argc, VALUE *argv, VALUE self); static VALUE cState_from_state_s(VALUE self, VALUE opts); @@ -165,5 +190,8 @@ static VALUE cState_max_nesting(VALUE self); static VALUE cState_max_nesting_set(VALUE self, VALUE depth); static VALUE cState_allow_nan_p(VALUE self); static VALUE cState_ascii_only_p(VALUE self); +static VALUE cState_depth(VALUE self); +static VALUE cState_depth_set(VALUE self, VALUE depth); +static FBuffer *cState_prepare_buffer(VALUE self); #endif diff --git a/ext/json/lib/json/common.rb b/ext/json/lib/json/common.rb index 244634b7a1..d5444b92c8 100644 --- a/ext/json/lib/json/common.rb +++ b/ext/json/lib/json/common.rb @@ -11,9 +11,9 @@ module JSON # generate and parse for their documentation. def [](object, opts = {}) if object.respond_to? :to_str - JSON.parse(object.to_str, opts => {}) + JSON.parse(object.to_str, opts) else - JSON.generate(object, opts => {}) + JSON.generate(object, opts) end end @@ -40,8 +40,8 @@ module JSON else begin p.const_missing(c) - rescue NameError - raise ArgumentError, "can't find const #{path}" + rescue NameError => e + raise ArgumentError, "can't get const #{path}: #{e}" end end end @@ -49,6 +49,7 @@ module JSON # Set the module _generator_ to be used by JSON. def generator=(generator) # :nodoc: + old, $VERBOSE = $VERBOSE, nil @generator = generator generator_methods = generator::GeneratorMethods for const in generator_methods.constants @@ -63,20 +64,22 @@ module JSON end self.state = generator::State const_set :State, self.state - const_set :SAFE_STATE_PROTOTYPE, State.new.freeze + const_set :SAFE_STATE_PROTOTYPE, State.new const_set :FAST_STATE_PROTOTYPE, State.new( :indent => '', :space => '', :object_nl => "", :array_nl => "", :max_nesting => false - ).freeze + ) const_set :PRETTY_STATE_PROTOTYPE, State.new( :indent => ' ', :space => ' ', :object_nl => "\n", :array_nl => "\n" - ).freeze + ) + ensure + $VERBOSE = old end # Returns the JSON generator modul, that is used by JSON. This might be @@ -196,6 +199,7 @@ module JSON # amount of sanity checks, and the pretty_generate method for some # defaults for a pretty output. def generate(obj, opts = nil) + state = SAFE_STATE_PROTOTYPE.dup if opts if opts.respond_to? :to_hash opts = opts.to_hash @@ -204,10 +208,7 @@ module JSON else raise TypeError, "can't convert #{opts.class} into Hash" end - state = SAFE_STATE_PROTOTYPE.dup state = state.configure(opts) - else - state = SAFE_STATE_PROTOTYPE end state.generate(obj) end @@ -225,6 +226,7 @@ module JSON # *WARNING*: Be careful not to pass any Ruby data structures with circles as # _obj_ argument, because this will cause JSON to go into an infinite loop. def fast_generate(obj, opts = nil) + state = FAST_STATE_PROTOTYPE.dup if opts if opts.respond_to? :to_hash opts = opts.to_hash @@ -233,10 +235,7 @@ module JSON else raise TypeError, "can't convert #{opts.class} into Hash" end - state = FAST_STATE_PROTOTYPE.dup state.configure(opts) - else - state = FAST_STATE_PROTOTYPE end state.generate(obj) end @@ -254,6 +253,7 @@ module JSON # The _opts_ argument can be used to configure the generator, see the # generate method for a more detailed explanation. def pretty_generate(obj, opts = nil) + state = PRETTY_STATE_PROTOTYPE.dup if opts if opts.respond_to? :to_hash opts = opts.to_hash @@ -262,10 +262,7 @@ module JSON else raise TypeError, "can't convert #{opts.class} into Hash" end - state = PRETTY_STATE_PROTOTYPE.dup state.configure(opts) - else - state = PRETTY_STATE_PROTOTYPE end state.generate(obj) end @@ -377,11 +374,11 @@ module ::Kernel # # The _opts_ argument is passed through to generate/parse respectively, see # generate and parse for their documentation. - def JSON(object, opts = {}) + def JSON(object, *args) if object.respond_to? :to_str - JSON.parse(object.to_str, opts) + JSON.parse(object.to_str, args.first) else - JSON.generate(object, opts) + JSON.generate(object, args.first) end end end diff --git a/ext/json/lib/json/editor.rb b/ext/json/lib/json/editor.rb deleted file mode 100644 index 1e13f33c8c..0000000000 --- a/ext/json/lib/json/editor.rb +++ /dev/null @@ -1,1371 +0,0 @@ -# To use the GUI JSON editor, start the edit_json.rb executable script. It -# requires ruby-gtk to be installed. - -require 'gtk2' -require 'iconv' -require 'json' -require 'rbconfig' -require 'open-uri' - -module JSON - module Editor - include Gtk - - # Beginning of the editor window title - TITLE = 'JSON Editor'.freeze - - # Columns constants - ICON_COL, TYPE_COL, CONTENT_COL = 0, 1, 2 - - # JSON primitive types (Containers) - CONTAINER_TYPES = %w[Array Hash].sort - # All JSON primitive types - ALL_TYPES = (%w[TrueClass FalseClass Numeric String NilClass] + - CONTAINER_TYPES).sort - - # The Nodes necessary for the tree representation of a JSON document - ALL_NODES = (ALL_TYPES + %w[Key]).sort - - DEFAULT_DIALOG_KEY_PRESS_HANDLER = lambda do |dialog, event| - case event.keyval - when Gdk::Keyval::GDK_Return - dialog.response Dialog::RESPONSE_ACCEPT - when Gdk::Keyval::GDK_Escape - dialog.response Dialog::RESPONSE_REJECT - end - end - - # Returns the Gdk::Pixbuf of the icon named _name_ from the icon cache. - def Editor.fetch_icon(name) - @icon_cache ||= {} - unless @icon_cache.key?(name) - path = File.dirname(__FILE__) - @icon_cache[name] = Gdk::Pixbuf.new(File.join(path, name + '.xpm')) - end - @icon_cache[name] - end - - # Opens an error dialog on top of _window_ showing the error message - # _text_. - def Editor.error_dialog(window, text) - dialog = MessageDialog.new(window, Dialog::MODAL, - MessageDialog::ERROR, - MessageDialog::BUTTONS_CLOSE, text) - dialog.show_all - dialog.run - rescue TypeError - dialog = MessageDialog.new(Editor.window, Dialog::MODAL, - MessageDialog::ERROR, - MessageDialog::BUTTONS_CLOSE, text) - dialog.show_all - dialog.run - ensure - dialog.destroy if dialog - end - - # Opens a yes/no question dialog on top of _window_ showing the error - # message _text_. If yes was answered _true_ is returned, otherwise - # _false_. - def Editor.question_dialog(window, text) - dialog = MessageDialog.new(window, Dialog::MODAL, - MessageDialog::QUESTION, - MessageDialog::BUTTONS_YES_NO, text) - dialog.show_all - dialog.run do |response| - return Gtk::Dialog::RESPONSE_YES === response - end - ensure - dialog.destroy if dialog - end - - # Convert the tree model starting from Gtk::TreeIter _iter_ into a Ruby - # data structure and return it. - def Editor.model2data(iter) - return nil if iter.nil? - case iter.type - when 'Hash' - hash = {} - iter.each { |c| hash[c.content] = Editor.model2data(c.first_child) } - hash - when 'Array' - array = Array.new(iter.n_children) - iter.each_with_index { |c, i| array[i] = Editor.model2data(c) } - array - when 'Key' - iter.content - when 'String' - iter.content - when 'Numeric' - content = iter.content - if /\./.match(content) - content.to_f - else - content.to_i - end - when 'TrueClass' - true - when 'FalseClass' - false - when 'NilClass' - nil - else - fail "Unknown type found in model: #{iter.type}" - end - end - - # Convert the Ruby data structure _data_ into tree model data for Gtk and - # returns the whole model. If the parameter _model_ wasn't given a new - # Gtk::TreeStore is created as the model. The _parent_ parameter specifies - # the parent node (iter, Gtk:TreeIter instance) to which the data is - # appended, alternativeley the result of the yielded block is used as iter. - def Editor.data2model(data, model = nil, parent = nil) - model ||= TreeStore.new(Gdk::Pixbuf, String, String) - iter = if block_given? - yield model - else - model.append(parent) - end - case data - when Hash - iter.type = 'Hash' - data.sort.each do |key, value| - pair_iter = model.append(iter) - pair_iter.type = 'Key' - pair_iter.content = key.to_s - Editor.data2model(value, model, pair_iter) - end - when Array - iter.type = 'Array' - data.each do |value| - Editor.data2model(value, model, iter) - end - when Numeric - iter.type = 'Numeric' - iter.content = data.to_s - when String, true, false, nil - iter.type = data.class.name - iter.content = data.nil? ? 'null' : data.to_s - else - iter.type = 'String' - iter.content = data.to_s - end - model - end - - # The Gtk::TreeIter class is reopened and some auxiliary methods are added. - class Gtk::TreeIter - include Enumerable - - # Traverse each of this Gtk::TreeIter instance's children - # and yield to them. - def each - n_children.times { |i| yield nth_child(i) } - end - - # Recursively traverse all nodes of this Gtk::TreeIter's subtree - # (including self) and yield to them. - def recursive_each(&block) - yield self - each do |i| - i.recursive_each(&block) - end - end - - # Remove the subtree of this Gtk::TreeIter instance from the - # model _model_. - def remove_subtree(model) - while current = first_child - model.remove(current) - end - end - - # Returns the type of this node. - def type - self[TYPE_COL] - end - - # Sets the type of this node to _value_. This implies setting - # the respective icon accordingly. - def type=(value) - self[TYPE_COL] = value - self[ICON_COL] = Editor.fetch_icon(value) - end - - # Returns the content of this node. - def content - self[CONTENT_COL] - end - - # Sets the content of this node to _value_. - def content=(value) - self[CONTENT_COL] = value - end - end - - # This module bundles some method, that can be used to create a menu. It - # should be included into the class in question. - module MenuExtension - include Gtk - - # Creates a Menu, that includes MenuExtension. _treeview_ is the - # Gtk::TreeView, on which it operates. - def initialize(treeview) - @treeview = treeview - @menu = Menu.new - end - - # Returns the Gtk::TreeView of this menu. - attr_reader :treeview - - # Returns the menu. - attr_reader :menu - - # Adds a Gtk::SeparatorMenuItem to this instance's #menu. - def add_separator - menu.append SeparatorMenuItem.new - end - - # Adds a Gtk::MenuItem to this instance's #menu. _label_ is the label - # string, _klass_ is the item type, and _callback_ is the procedure, that - # is called if the _item_ is activated. - def add_item(label, keyval = nil, klass = MenuItem, &callback) - label = "#{label} (C-#{keyval.chr})" if keyval - item = klass.new(label) - item.signal_connect(:activate, &callback) - if keyval - self.signal_connect(:'key-press-event') do |item, event| - if event.state & Gdk::Window::ModifierType::CONTROL_MASK != 0 and - event.keyval == keyval - callback.call item - end - end - end - menu.append item - item - end - - # This method should be implemented in subclasses to create the #menu of - # this instance. It has to be called after an instance of this class is - # created, to build the menu. - def create - raise NotImplementedError - end - - def method_missing(*a, &b) - treeview.__send__(*a, &b) - end - end - - # This class creates the popup menu, that opens when clicking onto the - # treeview. - class PopUpMenu - include MenuExtension - - # Change the type or content of the selected node. - def change_node(item) - if current = selection.selected - parent = current.parent - old_type, old_content = current.type, current.content - if ALL_TYPES.include?(old_type) - @clipboard_data = Editor.model2data(current) - type, content = ask_for_element(parent, current.type, - current.content) - if type - current.type, current.content = type, content - current.remove_subtree(model) - toplevel.display_status("Changed a node in tree.") - window.change - end - else - toplevel.display_status( - "Cannot change node of type #{old_type} in tree!") - end - end - end - - # Cut the selected node and its subtree, and save it into the - # clipboard. - def cut_node(item) - if current = selection.selected - if current and current.type == 'Key' - @clipboard_data = { - current.content => Editor.model2data(current.first_child) - } - else - @clipboard_data = Editor.model2data(current) - end - model.remove(current) - window.change - toplevel.display_status("Cut a node from tree.") - end - end - - # Copy the selected node and its subtree, and save it into the - # clipboard. - def copy_node(item) - if current = selection.selected - if current and current.type == 'Key' - @clipboard_data = { - current.content => Editor.model2data(current.first_child) - } - else - @clipboard_data = Editor.model2data(current) - end - window.change - toplevel.display_status("Copied a node from tree.") - end - end - - # Paste the data in the clipboard into the selected Array or Hash by - # appending it. - def paste_node_appending(item) - if current = selection.selected - if @clipboard_data - case current.type - when 'Array' - Editor.data2model(@clipboard_data, model, current) - expand_collapse(current) - when 'Hash' - if @clipboard_data.is_a? Hash - parent = current.parent - hash = Editor.model2data(current) - model.remove(current) - hash.update(@clipboard_data) - Editor.data2model(hash, model, parent) - if parent - expand_collapse(parent) - elsif @expanded - expand_all - end - window.change - else - toplevel.display_status( - "Cannot paste non-#{current.type} data into '#{current.type}'!") - end - else - toplevel.display_status( - "Cannot paste node below '#{current.type}'!") - end - else - toplevel.display_status("Nothing to paste in clipboard!") - end - else - toplevel.display_status("Append a node into the root first!") - end - end - - # Paste the data in the clipboard into the selected Array inserting it - # before the selected element. - def paste_node_inserting_before(item) - if current = selection.selected - if @clipboard_data - parent = current.parent or return - parent_type = parent.type - if parent_type == 'Array' - selected_index = parent.each_with_index do |c, i| - break i if c == current - end - Editor.data2model(@clipboard_data, model, parent) do |m| - m.insert_before(parent, current) - end - expand_collapse(current) - toplevel.display_status("Inserted an element to " + - "'#{parent_type}' before index #{selected_index}.") - window.change - else - toplevel.display_status( - "Cannot insert node below '#{parent_type}'!") - end - else - toplevel.display_status("Nothing to paste in clipboard!") - end - else - toplevel.display_status("Append a node into the root first!") - end - end - - # Append a new node to the selected Hash or Array. - def append_new_node(item) - if parent = selection.selected - parent_type = parent.type - case parent_type - when 'Hash' - key, type, content = ask_for_hash_pair(parent) - key or return - iter = create_node(parent, 'Key', key) - iter = create_node(iter, type, content) - toplevel.display_status( - "Added a (key, value)-pair to '#{parent_type}'.") - window.change - when 'Array' - type, content = ask_for_element(parent) - type or return - iter = create_node(parent, type, content) - window.change - toplevel.display_status("Appendend an element to '#{parent_type}'.") - else - toplevel.display_status("Cannot append to '#{parent_type}'!") - end - else - type, content = ask_for_element - type or return - iter = create_node(nil, type, content) - window.change - end - end - - # Insert a new node into an Array before the selected element. - def insert_new_node(item) - if current = selection.selected - parent = current.parent or return - parent_parent = parent.parent - parent_type = parent.type - if parent_type == 'Array' - selected_index = parent.each_with_index do |c, i| - break i if c == current - end - type, content = ask_for_element(parent) - type or return - iter = model.insert_before(parent, current) - iter.type, iter.content = type, content - toplevel.display_status("Inserted an element to " + - "'#{parent_type}' before index #{selected_index}.") - window.change - else - toplevel.display_status( - "Cannot insert node below '#{parent_type}'!") - end - else - toplevel.display_status("Append a node into the root first!") - end - end - - # Recursively collapse/expand a subtree starting from the selected node. - def collapse_expand(item) - if current = selection.selected - if row_expanded?(current.path) - collapse_row(current.path) - else - expand_row(current.path, true) - end - else - toplevel.display_status("Append a node into the root first!") - end - end - - # Create the menu. - def create - add_item("Change node", ?n, &method(:change_node)) - add_separator - add_item("Cut node", ?X, &method(:cut_node)) - add_item("Copy node", ?C, &method(:copy_node)) - add_item("Paste node (appending)", ?A, &method(:paste_node_appending)) - add_item("Paste node (inserting before)", ?I, - &method(:paste_node_inserting_before)) - add_separator - add_item("Append new node", ?a, &method(:append_new_node)) - add_item("Insert new node before", ?i, &method(:insert_new_node)) - add_separator - add_item("Collapse/Expand node (recursively)", ?e, - &method(:collapse_expand)) - - menu.show_all - signal_connect(:button_press_event) do |widget, event| - if event.kind_of? Gdk::EventButton and event.button == 3 - menu.popup(nil, nil, event.button, event.time) - end - end - signal_connect(:popup_menu) do - menu.popup(nil, nil, 0, Gdk::Event::CURRENT_TIME) - end - end - end - - # This class creates the File pulldown menu. - class FileMenu - include MenuExtension - - # Clear the model and filename, but ask to save the JSON document, if - # unsaved changes have occured. - def new(item) - window.clear - end - - # Open a file and load it into the editor. Ask to save the JSON document - # first, if unsaved changes have occured. - def open(item) - window.file_open - end - - def open_location(item) - window.location_open - end - - # Revert the current JSON document in the editor to the saved version. - def revert(item) - window.instance_eval do - @filename and file_open(@filename) - end - end - - # Save the current JSON document. - def save(item) - window.file_save - end - - # Save the current JSON document under the given filename. - def save_as(item) - window.file_save_as - end - - # Quit the editor, after asking to save any unsaved changes first. - def quit(item) - window.quit - end - - # Create the menu. - def create - title = MenuItem.new('File') - title.submenu = menu - add_item('New', &method(:new)) - add_item('Open', ?o, &method(:open)) - add_item('Open location', ?l, &method(:open_location)) - add_item('Revert', &method(:revert)) - add_separator - add_item('Save', ?s, &method(:save)) - add_item('Save As', ?S, &method(:save_as)) - add_separator - add_item('Quit', ?q, &method(:quit)) - title - end - end - - # This class creates the Edit pulldown menu. - class EditMenu - include MenuExtension - - # Copy data from model into primary clipboard. - def copy(item) - data = Editor.model2data(model.iter_first) - json = JSON.pretty_generate(data, :max_nesting => false) - c = Gtk::Clipboard.get(Gdk::Selection::PRIMARY) - c.text = json - end - - # Copy json text from primary clipboard into model. - def paste(item) - c = Gtk::Clipboard.get(Gdk::Selection::PRIMARY) - if json = c.wait_for_text - window.ask_save if @changed - begin - window.edit json - rescue JSON::ParserError - window.clear - end - end - end - - # Find a string in all nodes' contents and select the found node in the - # treeview. - def find(item) - @search = ask_for_find_term(@search) or return - iter = model.get_iter('0') or return - iter.recursive_each do |i| - if @iter - if @iter != i - next - else - @iter = nil - next - end - elsif @search.match(i[CONTENT_COL]) - set_cursor(i.path, nil, false) - @iter = i - break - end - end - end - - # Repeat the last search given by #find. - def find_again(item) - @search or return - iter = model.get_iter('0') - iter.recursive_each do |i| - if @iter - if @iter != i - next - else - @iter = nil - next - end - elsif @search.match(i[CONTENT_COL]) - set_cursor(i.path, nil, false) - @iter = i - break - end - end - end - - # Sort (Reverse sort) all elements of the selected array by the given - # expression. _x_ is the element in question. - def sort(item) - if current = selection.selected - if current.type == 'Array' - parent = current.parent - ary = Editor.model2data(current) - order, reverse = ask_for_order - order or return - begin - block = eval "lambda { |x| #{order} }" - if reverse - ary.sort! { |a,b| block[b] <=> block[a] } - else - ary.sort! { |a,b| block[a] <=> block[b] } - end - rescue => e - Editor.error_dialog(self, "Failed to sort Array with #{order}: #{e}!") - else - Editor.data2model(ary, model, parent) do |m| - m.insert_before(parent, current) - end - model.remove(current) - expand_collapse(parent) - window.change - toplevel.display_status("Array has been sorted.") - end - else - toplevel.display_status("Only Array nodes can be sorted!") - end - else - toplevel.display_status("Select an Array to sort first!") - end - end - - # Create the menu. - def create - title = MenuItem.new('Edit') - title.submenu = menu - add_item('Copy', ?c, &method(:copy)) - add_item('Paste', ?v, &method(:paste)) - add_separator - add_item('Find', ?f, &method(:find)) - add_item('Find Again', ?g, &method(:find_again)) - add_separator - add_item('Sort', ?S, &method(:sort)) - title - end - end - - class OptionsMenu - include MenuExtension - - # Collapse/Expand all nodes by default. - def collapsed_nodes(item) - if expanded - self.expanded = false - collapse_all - else - self.expanded = true - expand_all - end - end - - # Toggle pretty saving mode on/off. - def pretty_saving(item) - @pretty_item.toggled - window.change - end - - attr_reader :pretty_item - - # Create the menu. - def create - title = MenuItem.new('Options') - title.submenu = menu - add_item('Collapsed nodes', nil, CheckMenuItem, &method(:collapsed_nodes)) - @pretty_item = add_item('Pretty saving', nil, CheckMenuItem, - &method(:pretty_saving)) - @pretty_item.active = true - window.unchange - title - end - end - - # This class inherits from Gtk::TreeView, to configure it and to add a lot - # of behaviour to it. - class JSONTreeView < Gtk::TreeView - include Gtk - - # Creates a JSONTreeView instance, the parameter _window_ is - # a MainWindow instance and used for self delegation. - def initialize(window) - @window = window - super(TreeStore.new(Gdk::Pixbuf, String, String)) - self.selection.mode = SELECTION_BROWSE - - @expanded = false - self.headers_visible = false - add_columns - add_popup_menu - end - - # Returns the MainWindow instance of this JSONTreeView. - attr_reader :window - - # Returns true, if nodes are autoexpanding, false otherwise. - attr_accessor :expanded - - private - - def add_columns - cell = CellRendererPixbuf.new - column = TreeViewColumn.new('Icon', cell, - 'pixbuf' => ICON_COL - ) - append_column(column) - - cell = CellRendererText.new - column = TreeViewColumn.new('Type', cell, - 'text' => TYPE_COL - ) - append_column(column) - - cell = CellRendererText.new - cell.editable = true - column = TreeViewColumn.new('Content', cell, - 'text' => CONTENT_COL - ) - cell.signal_connect(:edited, &method(:cell_edited)) - append_column(column) - end - - def unify_key(iter, key) - return unless iter.type == 'Key' - parent = iter.parent - if parent.any? { |c| c != iter and c.content == key } - old_key = key - i = 0 - begin - key = sprintf("%s.%d", old_key, i += 1) - end while parent.any? { |c| c != iter and c.content == key } - end - iter.content = key - end - - def cell_edited(cell, path, value) - iter = model.get_iter(path) - case iter.type - when 'Key' - unify_key(iter, value) - toplevel.display_status('Key has been changed.') - when 'FalseClass' - value.downcase! - if value == 'true' - iter.type, iter.content = 'TrueClass', 'true' - end - when 'TrueClass' - value.downcase! - if value == 'false' - iter.type, iter.content = 'FalseClass', 'false' - end - when 'Numeric' - iter.content = - if value == 'Infinity' - value - else - (Integer(value) rescue Float(value) rescue 0).to_s - end - when 'String' - iter.content = value - when 'Hash', 'Array' - return - else - fail "Unknown type found in model: #{iter.type}" - end - window.change - end - - def configure_value(value, type) - value.editable = false - case type - when 'Array', 'Hash' - value.text = '' - when 'TrueClass' - value.text = 'true' - when 'FalseClass' - value.text = 'false' - when 'NilClass' - value.text = 'null' - when 'Numeric', 'String' - value.text ||= '' - value.editable = true - else - raise ArgumentError, "unknown type '#{type}' encountered" - end - end - - def add_popup_menu - menu = PopUpMenu.new(self) - menu.create - end - - public - - # Create a _type_ node with content _content_, and add it to _parent_ - # in the model. If _parent_ is nil, create a new model and put it into - # the editor treeview. - def create_node(parent, type, content) - iter = if parent - model.append(parent) - else - new_model = Editor.data2model(nil) - toplevel.view_new_model(new_model) - new_model.iter_first - end - iter.type, iter.content = type, content - expand_collapse(parent) if parent - iter - end - - # Ask for a hash key, value pair to be added to the Hash node _parent_. - def ask_for_hash_pair(parent) - key_input = type_input = value_input = nil - - dialog = Dialog.new("New (key, value) pair for Hash", nil, nil, - [ Stock::OK, Dialog::RESPONSE_ACCEPT ], - [ Stock::CANCEL, Dialog::RESPONSE_REJECT ] - ) - dialog.width_request = 640 - - hbox = HBox.new(false, 5) - hbox.pack_start(Label.new("Key:"), false) - hbox.pack_start(key_input = Entry.new) - key_input.text = @key || '' - dialog.vbox.pack_start(hbox, false) - key_input.signal_connect(:activate) do - if parent.any? { |c| c.content == key_input.text } - toplevel.display_status('Key already exists in Hash!') - key_input.text = '' - else - toplevel.display_status('Key has been changed.') - end - end - - hbox = HBox.new(false, 5) - hbox.pack_start(Label.new("Type:"), false) - hbox.pack_start(type_input = ComboBox.new(true)) - ALL_TYPES.each { |t| type_input.append_text(t) } - type_input.active = @type || 0 - dialog.vbox.pack_start(hbox, false) - - type_input.signal_connect(:changed) do - value_input.editable = false - case ALL_TYPES[type_input.active] - when 'Array', 'Hash' - value_input.text = '' - when 'TrueClass' - value_input.text = 'true' - when 'FalseClass' - value_input.text = 'false' - when 'NilClass' - value_input.text = 'null' - else - value_input.text = '' - value_input.editable = true - end - end - - hbox = HBox.new(false, 5) - hbox.pack_start(Label.new("Value:"), false) - hbox.pack_start(value_input = Entry.new) - value_input.width_chars = 60 - value_input.text = @value || '' - dialog.vbox.pack_start(hbox, false) - - dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER) - dialog.show_all - self.focus = dialog - dialog.run do |response| - if response == Dialog::RESPONSE_ACCEPT - @key = key_input.text - type = ALL_TYPES[@type = type_input.active] - content = value_input.text - return @key, type, content - end - end - return - ensure - dialog.destroy - end - - # Ask for an element to be appended _parent_. - def ask_for_element(parent = nil, default_type = nil, value_text = @content) - type_input = value_input = nil - - dialog = Dialog.new( - "New element into #{parent ? parent.type : 'root'}", - nil, nil, - [ Stock::OK, Dialog::RESPONSE_ACCEPT ], - [ Stock::CANCEL, Dialog::RESPONSE_REJECT ] - ) - hbox = HBox.new(false, 5) - hbox.pack_start(Label.new("Type:"), false) - hbox.pack_start(type_input = ComboBox.new(true)) - default_active = 0 - types = parent ? ALL_TYPES : CONTAINER_TYPES - types.each_with_index do |t, i| - type_input.append_text(t) - if t == default_type - default_active = i - end - end - type_input.active = default_active - dialog.vbox.pack_start(hbox, false) - type_input.signal_connect(:changed) do - configure_value(value_input, types[type_input.active]) - end - - hbox = HBox.new(false, 5) - hbox.pack_start(Label.new("Value:"), false) - hbox.pack_start(value_input = Entry.new) - value_input.width_chars = 60 - value_input.text = value_text if value_text - configure_value(value_input, types[type_input.active]) - - dialog.vbox.pack_start(hbox, false) - - dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER) - dialog.show_all - self.focus = dialog - dialog.run do |response| - if response == Dialog::RESPONSE_ACCEPT - type = types[type_input.active] - @content = case type - when 'Numeric' - if (t = value_input.text) == 'Infinity' - 1 / 0.0 - else - Integer(t) rescue Float(t) rescue 0 - end - else - value_input.text - end.to_s - return type, @content - end - end - return - ensure - dialog.destroy if dialog - end - - # Ask for an order criteria for sorting, using _x_ for the element in - # question. Returns the order criterium, and true/false for reverse - # sorting. - def ask_for_order - dialog = Dialog.new( - "Give an order criterium for 'x'.", - nil, nil, - [ Stock::OK, Dialog::RESPONSE_ACCEPT ], - [ Stock::CANCEL, Dialog::RESPONSE_REJECT ] - ) - hbox = HBox.new(false, 5) - - hbox.pack_start(Label.new("Order:"), false) - hbox.pack_start(order_input = Entry.new) - order_input.text = @order || 'x' - order_input.width_chars = 60 - - hbox.pack_start(reverse_checkbox = CheckButton.new('Reverse'), false) - - dialog.vbox.pack_start(hbox, false) - - dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER) - dialog.show_all - self.focus = dialog - dialog.run do |response| - if response == Dialog::RESPONSE_ACCEPT - return @order = order_input.text, reverse_checkbox.active? - end - end - return - ensure - dialog.destroy if dialog - end - - # Ask for a find term to search for in the tree. Returns the term as a - # string. - def ask_for_find_term(search = nil) - dialog = Dialog.new( - "Find a node matching regex in tree.", - nil, nil, - [ Stock::OK, Dialog::RESPONSE_ACCEPT ], - [ Stock::CANCEL, Dialog::RESPONSE_REJECT ] - ) - hbox = HBox.new(false, 5) - - hbox.pack_start(Label.new("Regex:"), false) - hbox.pack_start(regex_input = Entry.new) - hbox.pack_start(icase_checkbox = CheckButton.new('Icase'), false) - regex_input.width_chars = 60 - if search - regex_input.text = search.source - icase_checkbox.active = search.casefold? - end - - dialog.vbox.pack_start(hbox, false) - - dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER) - dialog.show_all - self.focus = dialog - dialog.run do |response| - if response == Dialog::RESPONSE_ACCEPT - begin - return Regexp.new(regex_input.text, icase_checkbox.active? ? Regexp::IGNORECASE : 0) - rescue => e - Editor.error_dialog(self, "Evaluation of regex /#{regex_input.text}/ failed: #{e}!") - return - end - end - end - return - ensure - dialog.destroy if dialog - end - - # Expand or collapse row pointed to by _iter_ according - # to the #expanded attribute. - def expand_collapse(iter) - if expanded - expand_row(iter.path, true) - else - collapse_row(iter.path) - end - end - end - - # The editor main window - class MainWindow < Gtk::Window - include Gtk - - def initialize(encoding) - @changed = false - @encoding = encoding - super(TOPLEVEL) - display_title - set_default_size(800, 600) - signal_connect(:delete_event) { quit } - - vbox = VBox.new(false, 0) - add(vbox) - #vbox.border_width = 0 - - @treeview = JSONTreeView.new(self) - @treeview.signal_connect(:'cursor-changed') do - display_status('') - end - - menu_bar = create_menu_bar - vbox.pack_start(menu_bar, false, false, 0) - - sw = ScrolledWindow.new(nil, nil) - sw.shadow_type = SHADOW_ETCHED_IN - sw.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC) - vbox.pack_start(sw, true, true, 0) - sw.add(@treeview) - - @status_bar = Statusbar.new - vbox.pack_start(@status_bar, false, false, 0) - - @filename ||= nil - if @filename - data = read_data(@filename) - view_new_model Editor.data2model(data) - end - - signal_connect(:button_release_event) do |_,event| - if event.button == 2 - c = Gtk::Clipboard.get(Gdk::Selection::PRIMARY) - if url = c.wait_for_text - location_open url - end - false - else - true - end - end - end - - # Creates the menu bar with the pulldown menus and returns it. - def create_menu_bar - menu_bar = MenuBar.new - @file_menu = FileMenu.new(@treeview) - menu_bar.append @file_menu.create - @edit_menu = EditMenu.new(@treeview) - menu_bar.append @edit_menu.create - @options_menu = OptionsMenu.new(@treeview) - menu_bar.append @options_menu.create - menu_bar - end - - # Sets editor status to changed, to indicate that the edited data - # containts unsaved changes. - def change - @changed = true - display_title - end - - # Sets editor status to unchanged, to indicate that the edited data - # doesn't containt unsaved changes. - def unchange - @changed = false - display_title - end - - # Puts a new model _model_ into the Gtk::TreeView to be edited. - def view_new_model(model) - @treeview.model = model - @treeview.expanded = true - @treeview.expand_all - unchange - end - - # Displays _text_ in the status bar. - def display_status(text) - @cid ||= nil - @status_bar.pop(@cid) if @cid - @cid = @status_bar.get_context_id('dummy') - @status_bar.push(@cid, text) - end - - # Opens a dialog, asking, if changes should be saved to a file. - def ask_save - if Editor.question_dialog(self, - "Unsaved changes to JSON model. Save?") - if @filename - file_save - else - file_save_as - end - end - end - - # Quit this editor, that is, leave this editor's main loop. - def quit - ask_save if @changed - if Gtk.main_level > 0 - destroy - Gtk.main_quit - end - nil - end - - # Display the new title according to the editor's current state. - def display_title - title = TITLE.dup - title << ": #@filename" if @filename - title << " *" if @changed - self.title = title - end - - # Clear the current model, after asking to save all unsaved changes. - def clear - ask_save if @changed - @filename = nil - self.view_new_model nil - end - - def check_pretty_printed(json) - pretty = !!((nl_index = json.index("\n")) && nl_index != json.size - 1) - @options_menu.pretty_item.active = pretty - end - private :check_pretty_printed - - # Open the data at the location _uri_, if given. Otherwise open a dialog - # to ask for the _uri_. - def location_open(uri = nil) - uri = ask_for_location unless uri - uri or return - ask_save if @changed - data = load_location(uri) or return - view_new_model Editor.data2model(data) - end - - # Open the file _filename_ or call the #select_file method to ask for a - # filename. - def file_open(filename = nil) - filename = select_file('Open as a JSON file') unless filename - data = load_file(filename) or return - view_new_model Editor.data2model(data) - end - - # Edit the string _json_ in the editor. - def edit(json) - if json.respond_to? :read - json = json.read - end - data = parse_json json - view_new_model Editor.data2model(data) - end - - # Save the current file. - def file_save - if @filename - store_file(@filename) - else - file_save_as - end - end - - # Save the current file as the filename - def file_save_as - filename = select_file('Save as a JSON file') - store_file(filename) - end - - # Store the current JSON document to _path_. - def store_file(path) - if path - data = Editor.model2data(@treeview.model.iter_first) - File.open(path + '.tmp', 'wb') do |output| - data or break - if @options_menu.pretty_item.active? - output.puts JSON.pretty_generate(data, :max_nesting => false) - else - output.write JSON.generate(data, :max_nesting => false) - end - end - File.rename path + '.tmp', path - @filename = path - toplevel.display_status("Saved data to '#@filename'.") - unchange - end - rescue SystemCallError => e - Editor.error_dialog(self, "Failed to store JSON file: #{e}!") - end - - # Load the file named _filename_ into the editor as a JSON document. - def load_file(filename) - if filename - if File.directory?(filename) - Editor.error_dialog(self, "Try to select a JSON file!") - nil - else - @filename = filename - if data = read_data(filename) - toplevel.display_status("Loaded data from '#@filename'.") - end - display_title - data - end - end - end - - # Load the data at location _uri_ into the editor as a JSON document. - def load_location(uri) - data = read_data(uri) or return - @filename = nil - toplevel.display_status("Loaded data from '#{uri}'.") - display_title - data - end - - def parse_json(json) - check_pretty_printed(json) - if @encoding && !/^utf8$/i.match(@encoding) - iconverter = Iconv.new('utf8', @encoding) - json = iconverter.iconv(json) - end - JSON::parse(json, :max_nesting => false, :create_additions => false) - end - private :parse_json - - # Read a JSON document from the file named _filename_, parse it into a - # ruby data structure, and return the data. - def read_data(filename) - open(filename) do |f| - json = f.read - return parse_json(json) - end - rescue => e - Editor.error_dialog(self, "Failed to parse JSON file: #{e}!") - return - end - - # Open a file selecton dialog, displaying _message_, and return the - # selected filename or nil, if no file was selected. - def select_file(message) - filename = nil - fs = FileSelection.new(message) - fs.set_modal(true) - @default_dir = File.join(Dir.pwd, '') unless @default_dir - fs.set_filename(@default_dir) - fs.set_transient_for(self) - fs.signal_connect(:destroy) { Gtk.main_quit } - fs.ok_button.signal_connect(:clicked) do - filename = fs.filename - @default_dir = File.join(File.dirname(filename), '') - fs.destroy - Gtk.main_quit - end - fs.cancel_button.signal_connect(:clicked) do - fs.destroy - Gtk.main_quit - end - fs.show_all - Gtk.main - filename - end - - # Ask for location URI a to load data from. Returns the URI as a string. - def ask_for_location - dialog = Dialog.new( - "Load data from location...", - nil, nil, - [ Stock::OK, Dialog::RESPONSE_ACCEPT ], - [ Stock::CANCEL, Dialog::RESPONSE_REJECT ] - ) - hbox = HBox.new(false, 5) - - hbox.pack_start(Label.new("Location:"), false) - hbox.pack_start(location_input = Entry.new) - location_input.width_chars = 60 - location_input.text = @location || '' - - dialog.vbox.pack_start(hbox, false) - - dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER) - dialog.show_all - dialog.run do |response| - if response == Dialog::RESPONSE_ACCEPT - return @location = location_input.text - end - end - return - ensure - dialog.destroy if dialog - end - end - - class << self - # Starts a JSON Editor. If a block was given, it yields - # to the JSON::Editor::MainWindow instance. - def start(encoding = 'utf8') # :yield: window - Gtk.init - @window = Editor::MainWindow.new(encoding) - @window.icon_list = [ Editor.fetch_icon('json') ] - yield @window if block_given? - @window.show_all - Gtk.main - end - - # Edit the string _json_ with encoding _encoding_ in the editor. - def edit(json, encoding = 'utf8') - start(encoding) do |window| - window.edit json - end - end - - attr_reader :window - end - end -end diff --git a/ext/json/lib/json/ext.rb b/ext/json/lib/json/ext.rb index 719e56025c..a5e3148c57 100644 --- a/ext/json/lib/json/ext.rb +++ b/ext/json/lib/json/ext.rb @@ -6,10 +6,10 @@ module JSON module Ext require 'json/ext/parser' require 'json/ext/generator' - $DEBUG and warn "Using c extension for JSON." + $DEBUG and warn "Using Ext extension for JSON." JSON.parser = Parser JSON.generator = Generator end - JSON_LOADED = true + JSON_LOADED = true unless const_defined?(:JSON_LOADED) end diff --git a/ext/json/lib/json/version.rb b/ext/json/lib/json/version.rb index de7690b57c..beff08b1c7 100644 --- a/ext/json/lib/json/version.rb +++ b/ext/json/lib/json/version.rb @@ -1,6 +1,6 @@ module JSON # JSON version - VERSION = '1.4.2' + VERSION = '1.5.0' VERSION_ARRAY = VERSION.split(/\./).map { |x| x.to_i } # :nodoc: VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc: VERSION_MINOR = VERSION_ARRAY[1] # :nodoc: diff --git a/ext/json/parser/extconf.rb b/ext/json/parser/extconf.rb index f378479875..f61fc94660 100644 --- a/ext/json/parser/extconf.rb +++ b/ext/json/parser/extconf.rb @@ -1,4 +1,15 @@ require 'mkmf' require 'rbconfig' +unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O3') + $CFLAGS << ' -O3' +end +if CONFIG['CC'] =~ /gcc/ + $CFLAGS << ' -Wall' + #unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O0 -ggdb') + # $CFLAGS << ' -O0 -ggdb' + #end +end + +have_header("re.h") create_makefile 'json/ext/parser' diff --git a/ext/json/parser/parser.c b/ext/json/parser/parser.c index cf4bbfa531..a2f4601bc1 100644 --- a/ext/json/parser/parser.c +++ b/ext/json/parser/parser.c @@ -4,7 +4,7 @@ /* unicode */ -static const char digit_values[256] = { +static const char digit_values[256] = { -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, @@ -40,7 +40,7 @@ static UTF32 unescape_unicode(const unsigned char *p) return result; } -static int convert_UTF32_to_UTF8(char *buf, UTF32 ch) +static int convert_UTF32_to_UTF8(char *buf, UTF32 ch) { int len = 1; if (ch <= 0x7F) { @@ -228,7 +228,7 @@ tr11: #line 116 "parser.rl" { VALUE v = Qnil; - char *np = JSON_parse_value(json, p, pe, &v); + char *np = JSON_parse_value(json, p, pe, &v); if (np == NULL) { p--; {p++; cs = 9; goto _out;} } else { @@ -530,7 +530,7 @@ tr2: goto st21; tr5: #line 229 "parser.rl" - { + { char *np; json->current_nesting++; np = JSON_parse_array(json, p, pe, result); @@ -540,7 +540,7 @@ tr5: goto st21; tr9: #line 237 "parser.rl" - { + { char *np; json->current_nesting++; np = JSON_parse_object(json, p, pe, result); @@ -1093,7 +1093,7 @@ tr2: #line 339 "parser.rl" { VALUE v = Qnil; - char *np = JSON_parse_value(json, p, pe, &v); + char *np = JSON_parse_value(json, p, pe, &v); if (np == NULL) { p--; {p++; cs = 3; goto _out;} } else { @@ -1312,7 +1312,7 @@ static VALUE json_string_unescape(VALUE result, char *string, char *stringEnd) unescape = (char *) "\f"; break; case 'u': - if (pe > stringEnd - 4) { + if (pe > stringEnd - 4) { return Qnil; } else { char buf[4]; @@ -1404,13 +1404,13 @@ tr2: { *result = json_string_unescape(*result, json->memo + 1, p); if (NIL_P(*result)) { - p--; - {p++; cs = 8; goto _out;} - } else { - FORCE_UTF8(*result); - {p = (( p + 1))-1;} - } - } + p--; + {p++; cs = 8; goto _out;} + } else { + FORCE_UTF8(*result); + {p = (( p + 1))-1;} + } + } #line 468 "parser.rl" { p--; {p++; cs = 8; goto _out;} } goto st8; @@ -1519,7 +1519,7 @@ static const int JSON_en_main = 1; #line 518 "parser.rl" -/* +/* * Document-class: JSON::Ext::Parser * * This is the JSON parser implemented as a C extension. It can be configured diff --git a/ext/json/parser/parser.rl b/ext/json/parser/parser.rl index 05b4890366..dd07485f3a 100644 --- a/ext/json/parser/parser.rl +++ b/ext/json/parser/parser.rl @@ -2,7 +2,7 @@ /* unicode */ -static const char digit_values[256] = { +static const char digit_values[256] = { -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, @@ -38,7 +38,7 @@ static UTF32 unescape_unicode(const unsigned char *p) return result; } -static int convert_UTF32_to_UTF8(char *buf, UTF32 ch) +static int convert_UTF32_to_UTF8(char *buf, UTF32 ch) { int len = 1; if (ch <= 0x7F) { @@ -115,7 +115,7 @@ static ID i_json_creatable_p, i_json_create, i_create_id, i_create_additions, action parse_value { VALUE v = Qnil; - char *np = JSON_parse_value(json, fpc, pe, &v); + char *np = JSON_parse_value(json, fpc, pe, &v); if (np == NULL) { fhold; fbreak; } else { @@ -226,7 +226,7 @@ static char *JSON_parse_object(JSON_Parser *json, char *p, char *pe, VALUE *resu fhold; fbreak; } - action parse_array { + action parse_array { char *np; json->current_nesting++; np = JSON_parse_array(json, fpc, pe, result); @@ -234,7 +234,7 @@ static char *JSON_parse_object(JSON_Parser *json, char *p, char *pe, VALUE *resu if (np == NULL) { fhold; fbreak; } else fexec np; } - action parse_object { + action parse_object { char *np; json->current_nesting++; np = JSON_parse_object(json, fpc, pe, result); @@ -338,7 +338,7 @@ static char *JSON_parse_float(JSON_Parser *json, char *p, char *pe, VALUE *resul action parse_value { VALUE v = Qnil; - char *np = JSON_parse_value(json, fpc, pe, &v); + char *np = JSON_parse_value(json, fpc, pe, &v); if (np == NULL) { fhold; fbreak; } else { @@ -411,7 +411,7 @@ static VALUE json_string_unescape(VALUE result, char *string, char *stringEnd) unescape = (char *) "\f"; break; case 'u': - if (pe > stringEnd - 4) { + if (pe > stringEnd - 4) { return Qnil; } else { char buf[4]; @@ -457,13 +457,13 @@ static VALUE json_string_unescape(VALUE result, char *string, char *stringEnd) action parse_string { *result = json_string_unescape(*result, json->memo + 1, p); if (NIL_P(*result)) { - fhold; - fbreak; - } else { - FORCE_UTF8(*result); - fexec p + 1; - } - } + fhold; + fbreak; + } else { + FORCE_UTF8(*result); + fexec p + 1; + } + } action exit { fhold; fbreak; } @@ -517,7 +517,7 @@ static char *JSON_parse_string(JSON_Parser *json, char *p, char *pe, VALUE *resu ) ignore*; }%% -/* +/* * Document-class: JSON::Ext::Parser * * This is the JSON parser implemented as a C extension. It can be configured diff --git a/test/json/test_json.rb b/test/json/test_json.rb index f5a432f8bd..00e52f511a 100755 --- a/test/json/test_json.rb +++ b/test/json/test_json.rb @@ -160,6 +160,20 @@ class TC_JSON < Test::Unit::TestCase class SubArray < Array; end + class SubArray2 < Array + def to_json(*a) + { + JSON.create_id => self.class.name, + 'ary' => to_a, + }.to_json(*a) + end + + def self.json_create(o) + o.delete JSON.create_id + o['ary'] + end + end + def test_parse_array_custom_class res = parse('[]', :array_class => SubArray) assert_equal([], res) @@ -173,12 +187,52 @@ class TC_JSON < Test::Unit::TestCase assert_equal({'foo'=>'bar'}, parse(' { "foo" : "bar" } ')) end - class SubHash < Hash; end + class SubHash < Hash + end + + class SubHash2 < Hash + def to_json(*a) + { + JSON.create_id => self.class.name, + }.merge(self).to_json(*a) + end + + def self.json_create(o) + o.delete JSON.create_id + self[o] + end + end def test_parse_object_custom_class - res = parse('{}', :object_class => SubHash) + res = parse('{}', :object_class => SubHash2) assert_equal({}, res) - assert_equal(SubHash, res.class) + assert_equal(SubHash2, res.class) + end + + def test_generation_of_core_subclasses_with_new_to_json + obj = SubHash2["foo" => SubHash2["bar" => true]] + obj_json = JSON(obj) + obj_again = JSON(obj_json) + assert_kind_of SubHash2, obj_again + assert_kind_of SubHash2, obj_again['foo'] + assert obj_again['foo']['bar'] + assert_equal obj, obj_again + assert_equal ["foo"], JSON(JSON(SubArray2["foo"])) + end + + def test_generation_of_core_subclasses_with_default_to_json + assert_equal '{"foo":"bar"}', JSON(SubHash["foo" => "bar"]) + assert_equal '["foo"]', JSON(SubArray["foo"]) + end + + def test_generation_of_core_subclasses + obj = SubHash["foo" => SubHash["bar" => true]] + obj_json = JSON(obj) + obj_again = JSON(obj_json) + assert_kind_of Hash, obj_again + assert_kind_of Hash, obj_again['foo'] + assert obj_again['foo']['bar'] + assert_equal obj, obj_again end def test_parser_reset diff --git a/test/json/test_json_addition.rb b/test/json/test_json_addition.rb index 844cd4f7ae..34f0a71b48 100755 --- a/test/json/test_json_addition.rb +++ b/test/json/test_json_addition.rb @@ -7,7 +7,7 @@ when 'pure' then require 'json/pure' when 'ext' then require 'json/ext' else require 'json' end -require 'json/add/core' +load 'json/add/core.rb' require 'date' class TC_JSONAddition < Test::Unit::TestCase @@ -110,9 +110,9 @@ class TC_JSONAddition < Test::Unit::TestCase json_raw_object = raw.to_json_raw_object hash = { 'json_class' => 'String', 'raw'=> raw_array } assert_equal hash, json_raw_object - assert_match /\A\{.*\}\Z/, json - assert_match /"json_class":"String"/, json - assert_match /"raw":\[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json + assert_match(/\A\{.*\}\Z/, json) + assert_match(/"json_class":"String"/, json) + assert_match(/"raw":\[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json) raw_again = JSON.parse(json) assert_equal raw, raw_again end diff --git a/test/json/test_json_encoding.rb b/test/json/test_json_encoding.rb index f5221bbd82..fdea329605 100644 --- a/test/json/test_json_encoding.rb +++ b/test/json/test_json_encoding.rb @@ -1,3 +1,4 @@ +#!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'test/unit' diff --git a/test/json/test_json_generate.rb b/test/json/test_json_generate.rb index 26ca1adcf9..5380a0645e 100755 --- a/test/json/test_json_generate.rb +++ b/test/json/test_json_generate.rb @@ -84,6 +84,8 @@ EOT assert_raise(GeneratorError) { fast_generate(666) } end + + def test_states json = generate({1=>2}, nil) assert_equal('{"1":2}', json) @@ -102,6 +104,51 @@ EOT assert s[:check_circular?] end + def test_pretty_state + state = PRETTY_STATE_PROTOTYPE.dup + assert_equal({ + :allow_nan => false, + :array_nl => "\n", + :ascii_only => false, + :depth => 0, + :indent => " ", + :max_nesting => 19, + :object_nl => "\n", + :space => " ", + :space_before => "", + }.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s }) + end + + def test_safe_state + state = SAFE_STATE_PROTOTYPE.dup + assert_equal({ + :allow_nan => false, + :array_nl => "", + :ascii_only => false, + :depth => 0, + :indent => "", + :max_nesting => 19, + :object_nl => "", + :space => "", + :space_before => "", + }.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s }) + end + + def test_fast_state + state = FAST_STATE_PROTOTYPE.dup + assert_equal({ + :allow_nan => false, + :array_nl => "", + :ascii_only => false, + :depth => 0, + :indent => "", + :max_nesting => 0, + :object_nl => "", + :space => "", + :space_before => "", + }.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s }) + end + def test_allow_nan assert_raises(GeneratorError) { generate([JSON::NaN]) } assert_equal '[NaN]', generate([JSON::NaN], :allow_nan => true) @@ -119,4 +166,18 @@ EOT assert_raises(GeneratorError) { pretty_generate([JSON::MinusInfinity]) } assert_equal "[\n -Infinity\n]", pretty_generate([JSON::MinusInfinity], :allow_nan => true) end + + def test_depth + ary = []; ary << ary + assert_equal 0, JSON::SAFE_STATE_PROTOTYPE.depth + assert_raises(JSON::NestingError) { JSON.generate(ary) } + assert_equal 0, JSON::SAFE_STATE_PROTOTYPE.depth + assert_equal 0, JSON::PRETTY_STATE_PROTOTYPE.depth + assert_raises(JSON::NestingError) { JSON.pretty_generate(ary) } + assert_equal 0, JSON::PRETTY_STATE_PROTOTYPE.depth + s = JSON.state.new + assert_equal 0, s.depth + assert_raises(JSON::NestingError) { ary.to_json(s) } + assert_equal 19, s.depth + end end diff --git a/test/json/test_json_rails.rb b/test/json/test_json_rails.rb index 29903642c3..daa053c82d 100755 --- a/test/json/test_json_rails.rb +++ b/test/json/test_json_rails.rb @@ -7,20 +7,12 @@ when 'pure' then require 'json/pure' when 'ext' then require 'json/ext' else require 'json' end -require 'json/add/rails' +load 'json/add/rails.rb' require 'date' class TC_JSONRails < Test::Unit::TestCase include JSON - def setup - Symbol.class_eval do - def to_json(*a) - to_s.to_json(*a) - end - end - end - class A def initialize(a) @a = a @@ -139,9 +131,9 @@ class TC_JSONRails < Test::Unit::TestCase json_raw_object = raw.to_json_raw_object hash = { 'json_class' => 'String', 'raw'=> raw_array } assert_equal hash, json_raw_object - assert_match /\A\{.*\}\Z/, json - assert_match /"json_class":"String"/, json - assert_match /"raw":\[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json + assert_match(/\A\{.*\}\Z/, json) + assert_match(/"json_class":"String"/, json) + assert_match(/"raw":\[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json) raw_again = JSON.parse(json) assert_equal raw, raw_again end -- cgit v1.2.3