json 2.6.3 → 2.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/BSDL +22 -0
  3. data/CHANGES.md +188 -17
  4. data/LEGAL +8 -0
  5. data/README.md +67 -224
  6. data/ext/json/ext/fbuffer/fbuffer.h +144 -95
  7. data/ext/json/ext/generator/extconf.rb +8 -2
  8. data/ext/json/ext/generator/generator.c +1043 -810
  9. data/ext/json/ext/parser/extconf.rb +6 -27
  10. data/ext/json/ext/parser/parser.c +1227 -3209
  11. data/ext/json/ext/vendor/fpconv.c +479 -0
  12. data/ext/json/ext/vendor/jeaiii-ltoa.h +267 -0
  13. data/json.gemspec +48 -52
  14. data/lib/json/add/bigdecimal.rb +39 -10
  15. data/lib/json/add/complex.rb +29 -6
  16. data/lib/json/add/core.rb +1 -1
  17. data/lib/json/add/date.rb +27 -7
  18. data/lib/json/add/date_time.rb +26 -9
  19. data/lib/json/add/exception.rb +25 -7
  20. data/lib/json/add/ostruct.rb +32 -9
  21. data/lib/json/add/range.rb +33 -8
  22. data/lib/json/add/rational.rb +28 -6
  23. data/lib/json/add/regexp.rb +26 -8
  24. data/lib/json/add/set.rb +25 -6
  25. data/lib/json/add/struct.rb +29 -7
  26. data/lib/json/add/symbol.rb +34 -7
  27. data/lib/json/add/time.rb +29 -15
  28. data/lib/json/common.rb +648 -249
  29. data/lib/json/ext/generator/state.rb +106 -0
  30. data/lib/json/ext.rb +34 -4
  31. data/lib/json/generic_object.rb +7 -3
  32. data/lib/json/truffle_ruby/generator.rb +690 -0
  33. data/lib/json/version.rb +3 -7
  34. data/lib/json.rb +25 -21
  35. metadata +17 -26
  36. data/VERSION +0 -1
  37. data/ext/json/ext/generator/depend +0 -1
  38. data/ext/json/ext/generator/generator.h +0 -174
  39. data/ext/json/ext/parser/depend +0 -1
  40. data/ext/json/ext/parser/parser.h +0 -96
  41. data/ext/json/ext/parser/parser.rl +0 -986
  42. data/ext/json/extconf.rb +0 -3
  43. data/lib/json/pure/generator.rb +0 -479
  44. data/lib/json/pure/parser.rb +0 -337
  45. data/lib/json/pure.rb +0 -15
  46. /data/{LICENSE → COPYING} +0 -0
data/README.md CHANGED
@@ -1,22 +1,14 @@
1
1
  # JSON implementation for Ruby
2
2
 
3
- [![CI](https://github.com/flori/json/actions/workflows/ci.yml/badge.svg)](https://github.com/flori/json/actions/workflows/ci.yml)
3
+ [![CI](https://github.com/ruby/json/actions/workflows/ci.yml/badge.svg)](https://github.com/ruby/json/actions/workflows/ci.yml)
4
4
 
5
5
  ## Description
6
6
 
7
- This is a implementation of the JSON specification according to RFC 7159
8
- http://www.ietf.org/rfc/rfc7159.txt . Starting from version 1.0.0 on there
9
- will be two variants available:
7
+ This is an implementation of the JSON specification according to RFC 7159
8
+ http://www.ietf.org/rfc/rfc7159.txt .
10
9
 
11
- * A pure ruby variant, that relies on the iconv and the stringscan
12
- extensions, which are both part of the ruby standard library.
13
- * The quite a bit faster native extension variant, which is in parts
14
- implemented in C or Java and comes with its own unicode conversion
15
- functions and a parser generated by the ragel state machine compiler
16
- http://www.complang.org/ragel/ .
17
-
18
- Both variants of the JSON generator generate UTF-8 character sequences by
19
- default. If an :ascii\_only option with a true value is given, they escape all
10
+ The JSON generator generate UTF-8 character sequences by default.
11
+ If an :ascii\_only option with a true value is given, they escape all
20
12
  non-ASCII and control characters with \uXXXX escape sequences, and support
21
13
  UTF-16 surrogate pairs in order to be able to generate the whole range of
22
14
  unicode code points.
@@ -29,52 +21,15 @@ endpoint.
29
21
 
30
22
  ## Installation
31
23
 
32
- It's recommended to use the extension variant of JSON, because it's faster than
33
- the pure ruby variant. If you cannot build it on your system, you can settle
34
- for the latter.
35
-
36
- Just type into the command line as root:
37
-
38
- ```
39
- # rake install
40
- ```
41
-
42
- The above command will build the extensions and install them on your system.
43
-
44
- ```
45
- # rake install_pure
46
- ```
47
-
48
- or
49
-
50
- ```
51
- # ruby install.rb
52
- ```
53
-
54
- will just install the pure ruby implementation of JSON.
55
-
56
- If you use Rubygems you can type
57
-
58
- ```
59
- # gem install json
60
- ```
61
-
62
- instead, to install the newest JSON version.
63
-
64
- There is also a pure ruby json only variant of the gem, that can be installed
65
- with:
24
+ Install the gem and add to the application's Gemfile by executing:
66
25
 
67
- ```
68
- # gem install json_pure
69
- ```
26
+ $ bundle add json
70
27
 
71
- ## Compiling the extensions yourself
28
+ If bundler is not being used to manage dependencies, install the gem by executing:
72
29
 
73
- If you want to create the `parser.c` file from its `parser.rl` file or draw nice
74
- graphviz images of the state machines, you need ragel from:
75
- http://www.complang.org/ragel/
30
+ $ gem install json
76
31
 
77
- ## Usage
32
+ ## Basic Usage
78
33
 
79
34
  To use JSON you can
80
35
 
@@ -82,20 +37,6 @@ To use JSON you can
82
37
  require 'json'
83
38
  ```
84
39
 
85
- to load the installed variant (either the extension `'json'` or the pure
86
- variant `'json_pure'`). If you have installed the extension variant, you can
87
- pick either the extension variant or the pure variant by typing
88
-
89
- ```ruby
90
- require 'json/ext'
91
- ```
92
-
93
- or
94
-
95
- ```ruby
96
- require 'json/pure'
97
- ```
98
-
99
40
  Now you can parse a JSON document into a ruby data structure by calling
100
41
 
101
42
  ```ruby
@@ -111,59 +52,84 @@ You can also use the `pretty_generate` method (which formats the output more
111
52
  verbosely and nicely) or `fast_generate` (which doesn't do any of the security
112
53
  checks generate performs, e. g. nesting deepness checks).
113
54
 
114
- There are also the JSON and JSON[] methods which use parse on a String or
115
- generate a JSON document from an array or hash:
55
+ ## Casting non native types
116
56
 
117
- ```ruby
118
- document = JSON 'test' => 23 # => "{\"test\":23}"
119
- document = JSON['test' => 23] # => "{\"test\":23}"
120
- ```
57
+ JSON documents can only support Hashes, Arrays, Strings, Integers and Floats.
121
58
 
122
- and
59
+ By default if you attempt to serialize something else, `JSON.generate` will
60
+ search for a `#to_json` method on that object:
123
61
 
124
62
  ```ruby
125
- data = JSON '{"test":23}' # => {"test"=>23}
126
- data = JSON['{"test":23}'] # => {"test"=>23}
63
+ Position = Struct.new(:latitude, :longitude) do
64
+ def to_json(state = nil, *)
65
+ JSON::State.from_state(state).generate({
66
+ latitude: latitude,
67
+ longitude: longitude,
68
+ })
69
+ end
70
+ end
71
+
72
+ JSON.generate([
73
+ Position.new(12323.234, 435345.233),
74
+ Position.new(23434.676, 159435.324),
75
+ ]) # => [{"latitude":12323.234,"longitude":435345.233},{"latitude":23434.676,"longitude":159435.324}]
127
76
  ```
128
77
 
129
- You can choose to load a set of common additions to ruby core's objects if
130
- you
78
+ If a `#to_json` method isn't defined on the object, `JSON.generate` will fallback to call `#to_s`:
131
79
 
132
80
  ```ruby
133
- require 'json/add/core'
81
+ JSON.generate(Object.new) # => "#<Object:0x000000011e768b98>"
134
82
  ```
135
83
 
136
- After requiring this you can, e. g., serialise/deserialise Ruby ranges:
84
+ Both of these behavior can be disabled using the `strict: true` option:
137
85
 
138
86
  ```ruby
139
- JSON JSON(1..10) # => 1..10
87
+ JSON.generate(Object.new, strict: true) # => Object not allowed in JSON (JSON::GeneratorError)
88
+ JSON.generate(Position.new(1, 2)) # => Position not allowed in JSON (JSON::GeneratorError)
140
89
  ```
141
90
 
142
- To find out how to add JSON support to other or your own classes, read the
143
- section "More Examples" below.
91
+ ## JSON::Coder
92
+
93
+ Since `#to_json` methods are global, it can sometimes be problematic if you need a given type to be
94
+ serialized in different ways in different locations.
144
95
 
145
- To get the best compatibility to rails' JSON implementation, you can
96
+ Instead it is recommended to use the newer `JSON::Coder` API:
146
97
 
147
98
  ```ruby
148
- require 'json/add/rails'
149
- ```
99
+ module MyApp
100
+ API_JSON_CODER = JSON::Coder.new do |object|
101
+ case object
102
+ when Time
103
+ object.iso8601(3)
104
+ else
105
+ object
106
+ end
107
+ end
108
+ end
150
109
 
151
- Both of the additions attempt to require `'json'` (like above) first, if it has
152
- not been required yet.
110
+ puts MyApp::API_JSON_CODER.dump(Time.now.utc) # => "2025-01-21T08:41:44.286Z"
111
+ ```
153
112
 
154
- ## Serializing exceptions
113
+ The provided block is called for all objects that don't have a native JSON equivalent, and
114
+ must return a Ruby object that has a native JSON equivalent.
155
115
 
156
- The JSON module doesn't extend `Exception` by default. If you convert an `Exception`
157
- object to JSON, it will by default only include the exception message.
116
+ ## Combining JSON fragments
158
117
 
159
- To include the full details, you must either load the `json/add/core` mentioned
160
- above, or specifically load the exception addition:
118
+ To combine JSON fragments into a bigger JSON document, you can use `JSON::Fragment`:
161
119
 
162
120
  ```ruby
163
- require 'json/add/exception'
121
+ posts_json = cache.fetch_multi(post_ids) do |post_id|
122
+ JSON.generate(Post.find(post_id))
123
+ end
124
+ posts_json.map! { |post_json| JSON::Fragment.new(post_json) }
125
+ JSON.generate({ posts: posts_json, count: posts_json.count })
164
126
  ```
165
127
 
166
- ## More Examples
128
+ ## Round-tripping arbitrary types
129
+
130
+ > [!CAUTION]
131
+ > You should never use `JSON.unsafe_load` nor `JSON.parse(str, create_additions: true)` to parse untrusted user input,
132
+ > as it can lead to remote code execution vulnerabilities.
167
133
 
168
134
  To create a JSON document from a ruby data structure, you can call
169
135
  `JSON.generate` like that:
@@ -229,7 +195,7 @@ JSON.parse json
229
195
  # => [1, 2, {"a"=>3.141}, false, true, nil, 4..10]
230
196
  json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10]
231
197
  # => "[1,2,{\"a\":3.141},false,true,null,{\"json_class\":\"Range\",\"data\":[4,10,false]}]"
232
- JSON.parse json, :create_additions => true
198
+ JSON.unsafe_load json
233
199
  # => [1, 2, {"a"=>3.141}, false, true, nil, 4..10]
234
200
  ```
235
201
 
@@ -265,136 +231,11 @@ There are also the methods `Kernel#j` for generate, and `Kernel#jj` for
265
231
  `pretty_generate` output to the console, that work analogous to Core Ruby's `p` and
266
232
  the `pp` library's `pp` methods.
267
233
 
268
- The script `tools/server.rb` contains a small example if you want to test, how
269
- receiving a JSON object from a webrick server in your browser with the
270
- JavaScript prototype library http://www.prototypejs.org works.
271
-
272
- ## Speed Comparisons
273
-
274
- I have created some benchmark results (see the benchmarks/data-p4-3Ghz
275
- subdir of the package) for the JSON-parser to estimate the speed up in the C
276
- extension:
277
-
278
- ```
279
- Comparing times (call_time_mean):
280
- 1 ParserBenchmarkExt#parser 900 repeats:
281
- 553.922304770 ( real) -> 21.500x
282
- 0.001805307
283
- 2 ParserBenchmarkYAML#parser 1000 repeats:
284
- 224.513358139 ( real) -> 8.714x
285
- 0.004454078
286
- 3 ParserBenchmarkPure#parser 1000 repeats:
287
- 26.755020642 ( real) -> 1.038x
288
- 0.037376163
289
- 4 ParserBenchmarkRails#parser 1000 repeats:
290
- 25.763381731 ( real) -> 1.000x
291
- 0.038814780
292
- calls/sec ( time) -> speed covers
293
- secs/call
294
- ```
295
-
296
- In the table above 1 is `JSON::Ext::Parser`, 2 is `YAML.load` with YAML
297
- compatible JSON document, 3 is is `JSON::Pure::Parser`, and 4 is
298
- `ActiveSupport::JSON.decode`. The ActiveSupport JSON-decoder converts the
299
- input first to YAML and then uses the YAML-parser, the conversion seems to
300
- slow it down so much that it is only as fast as the `JSON::Pure::Parser`!
301
-
302
- If you look at the benchmark data you can see that this is mostly caused by
303
- the frequent high outliers - the median of the Rails-parser runs is still
304
- overall smaller than the median of the `JSON::Pure::Parser` runs:
305
-
306
- ```
307
- Comparing times (call_time_median):
308
- 1 ParserBenchmarkExt#parser 900 repeats:
309
- 800.592479481 ( real) -> 26.936x
310
- 0.001249075
311
- 2 ParserBenchmarkYAML#parser 1000 repeats:
312
- 271.002390644 ( real) -> 9.118x
313
- 0.003690004
314
- 3 ParserBenchmarkRails#parser 1000 repeats:
315
- 30.227910865 ( real) -> 1.017x
316
- 0.033082008
317
- 4 ParserBenchmarkPure#parser 1000 repeats:
318
- 29.722384421 ( real) -> 1.000x
319
- 0.033644676
320
- calls/sec ( time) -> speed covers
321
- secs/call
322
- ```
323
-
324
- I have benchmarked the `JSON-Generator` as well. This generated a few more
325
- values, because there are different modes that also influence the achieved
326
- speed:
327
-
328
- ```
329
- Comparing times (call_time_mean):
330
- 1 GeneratorBenchmarkExt#generator_fast 1000 repeats:
331
- 547.354332608 ( real) -> 15.090x
332
- 0.001826970
333
- 2 GeneratorBenchmarkExt#generator_safe 1000 repeats:
334
- 443.968212317 ( real) -> 12.240x
335
- 0.002252414
336
- 3 GeneratorBenchmarkExt#generator_pretty 900 repeats:
337
- 375.104545883 ( real) -> 10.341x
338
- 0.002665923
339
- 4 GeneratorBenchmarkPure#generator_fast 1000 repeats:
340
- 49.978706968 ( real) -> 1.378x
341
- 0.020008521
342
- 5 GeneratorBenchmarkRails#generator 1000 repeats:
343
- 38.531868759 ( real) -> 1.062x
344
- 0.025952543
345
- 6 GeneratorBenchmarkPure#generator_safe 1000 repeats:
346
- 36.927649925 ( real) -> 1.018x 7 (>=3859)
347
- 0.027079979
348
- 7 GeneratorBenchmarkPure#generator_pretty 1000 repeats:
349
- 36.272134441 ( real) -> 1.000x 6 (>=3859)
350
- 0.027569373
351
- calls/sec ( time) -> speed covers
352
- secs/call
353
- ```
354
-
355
- In the table above 1-3 are `JSON::Ext::Generator` methods. 4, 6, and 7 are
356
- `JSON::Pure::Generator` methods and 5 is the Rails JSON generator. It is now a
357
- bit faster than the `generator_safe` and `generator_pretty` methods of the pure
358
- variant but slower than the others.
359
-
360
- To achieve the fastest JSON document output, you can use the `fast_generate`
361
- method. Beware, that this will disable the checking for circular Ruby data
362
- structures, which may cause JSON to go into an infinite loop.
363
-
364
- Here are the median comparisons for completeness' sake:
365
-
366
- ```
367
- Comparing times (call_time_median):
368
- 1 GeneratorBenchmarkExt#generator_fast 1000 repeats:
369
- 708.258020939 ( real) -> 16.547x
370
- 0.001411915
371
- 2 GeneratorBenchmarkExt#generator_safe 1000 repeats:
372
- 569.105020353 ( real) -> 13.296x
373
- 0.001757145
374
- 3 GeneratorBenchmarkExt#generator_pretty 900 repeats:
375
- 482.825371244 ( real) -> 11.280x
376
- 0.002071142
377
- 4 GeneratorBenchmarkPure#generator_fast 1000 repeats:
378
- 62.717626652 ( real) -> 1.465x
379
- 0.015944481
380
- 5 GeneratorBenchmarkRails#generator 1000 repeats:
381
- 43.965681162 ( real) -> 1.027x
382
- 0.022745013
383
- 6 GeneratorBenchmarkPure#generator_safe 1000 repeats:
384
- 43.929073409 ( real) -> 1.026x 7 (>=3859)
385
- 0.022763968
386
- 7 GeneratorBenchmarkPure#generator_pretty 1000 repeats:
387
- 42.802514491 ( real) -> 1.000x 6 (>=3859)
388
- 0.023363113
389
- calls/sec ( time) -> speed covers
390
- secs/call
391
- ```
392
-
393
234
  ## Development
394
235
 
395
236
  ### Release
396
237
 
397
- Update the json.gemspec and json-java.gemspec.
238
+ Update the `lib/json/version.rb` file.
398
239
 
399
240
  ```
400
241
  rbenv shell 2.6.5
@@ -423,3 +264,5 @@ The latest version of this library can be downloaded at
423
264
  Online Documentation should be located at
424
265
 
425
266
  * https://www.rubydoc.info/gems/json
267
+
268
+ [Ragel]: http://www.colm.net/open-source/ragel/
@@ -1,89 +1,86 @@
1
-
2
1
  #ifndef _FBUFFER_H_
3
2
  #define _FBUFFER_H_
4
3
 
5
4
  #include "ruby.h"
6
-
7
- #ifndef RHASH_SIZE
8
- #define RHASH_SIZE(hsh) (RHASH(hsh)->tbl->num_entries)
5
+ #include "ruby/encoding.h"
6
+ #include "../vendor/jeaiii-ltoa.h"
7
+
8
+ /* shims */
9
+ /* This is the fallback definition from Ruby 3.4 */
10
+
11
+ #ifndef RBIMPL_STDBOOL_H
12
+ #if defined(__cplusplus)
13
+ # if defined(HAVE_STDBOOL_H) && (__cplusplus >= 201103L)
14
+ # include <cstdbool>
15
+ # endif
16
+ #elif defined(HAVE_STDBOOL_H)
17
+ # include <stdbool.h>
18
+ #elif !defined(HAVE__BOOL)
19
+ typedef unsigned char _Bool;
20
+ # define bool _Bool
21
+ # define true ((_Bool)+1)
22
+ # define false ((_Bool)+0)
23
+ # define __bool_true_false_are_defined
9
24
  #endif
10
-
11
- #ifndef RFLOAT_VALUE
12
- #define RFLOAT_VALUE(val) (RFLOAT(val)->value)
13
25
  #endif
14
26
 
15
- #ifndef RARRAY_LEN
16
- #define RARRAY_LEN(ARRAY) RARRAY(ARRAY)->len
17
- #endif
18
- #ifndef RSTRING_PTR
19
- #define RSTRING_PTR(string) RSTRING(string)->ptr
20
- #endif
21
- #ifndef RSTRING_LEN
22
- #define RSTRING_LEN(string) RSTRING(string)->len
27
+ #ifndef RB_UNLIKELY
28
+ #define RB_UNLIKELY(expr) expr
23
29
  #endif
24
30
 
25
- #ifdef PRIsVALUE
26
- # define RB_OBJ_CLASSNAME(obj) rb_obj_class(obj)
27
- # define RB_OBJ_STRING(obj) (obj)
28
- #else
29
- # define PRIsVALUE "s"
30
- # define RB_OBJ_CLASSNAME(obj) rb_obj_classname(obj)
31
- # define RB_OBJ_STRING(obj) StringValueCStr(obj)
31
+ #ifndef RB_LIKELY
32
+ #define RB_LIKELY(expr) expr
32
33
  #endif
33
34
 
34
- #ifdef HAVE_RUBY_ENCODING_H
35
- #include "ruby/encoding.h"
36
- #define FORCE_UTF8(obj) rb_enc_associate((obj), rb_utf8_encoding())
37
- #else
38
- #define FORCE_UTF8(obj)
35
+ #ifndef MAYBE_UNUSED
36
+ # define MAYBE_UNUSED(x) x
39
37
  #endif
40
38
 
41
- /* We don't need to guard objects for rbx, so let's do nothing at all. */
42
- #ifndef RB_GC_GUARD
43
- #define RB_GC_GUARD(object)
44
- #endif
39
+ enum fbuffer_type {
40
+ FBUFFER_HEAP_ALLOCATED = 0,
41
+ FBUFFER_STACK_ALLOCATED = 1,
42
+ };
45
43
 
46
44
  typedef struct FBufferStruct {
45
+ enum fbuffer_type type;
47
46
  unsigned long initial_length;
48
- char *ptr;
49
47
  unsigned long len;
50
48
  unsigned long capa;
49
+ char *ptr;
50
+ VALUE io;
51
51
  } FBuffer;
52
52
 
53
+ #define FBUFFER_STACK_SIZE 512
54
+ #define FBUFFER_IO_BUFFER_SIZE (16384 - 1)
53
55
  #define FBUFFER_INITIAL_LENGTH_DEFAULT 1024
54
56
 
55
- #define FBUFFER_PTR(fb) (fb->ptr)
56
- #define FBUFFER_LEN(fb) (fb->len)
57
- #define FBUFFER_CAPA(fb) (fb->capa)
57
+ #define FBUFFER_PTR(fb) ((fb)->ptr)
58
+ #define FBUFFER_LEN(fb) ((fb)->len)
59
+ #define FBUFFER_CAPA(fb) ((fb)->capa)
58
60
  #define FBUFFER_PAIR(fb) FBUFFER_PTR(fb), FBUFFER_LEN(fb)
59
61
 
60
- static FBuffer *fbuffer_alloc(unsigned long initial_length);
61
62
  static void fbuffer_free(FBuffer *fb);
62
63
  static void fbuffer_clear(FBuffer *fb);
63
64
  static void fbuffer_append(FBuffer *fb, const char *newstr, unsigned long len);
64
- #ifdef JSON_GENERATOR
65
65
  static void fbuffer_append_long(FBuffer *fb, long number);
66
- #endif
67
- static void fbuffer_append_char(FBuffer *fb, char newchr);
68
- #ifdef JSON_GENERATOR
69
- static FBuffer *fbuffer_dup(FBuffer *fb);
70
- static VALUE fbuffer_to_s(FBuffer *fb);
71
- #endif
66
+ static inline void fbuffer_append_char(FBuffer *fb, char newchr);
67
+ static VALUE fbuffer_finalize(FBuffer *fb);
72
68
 
73
- static FBuffer *fbuffer_alloc(unsigned long initial_length)
69
+ static void fbuffer_stack_init(FBuffer *fb, unsigned long initial_length, char *stack_buffer, long stack_buffer_size)
74
70
  {
75
- FBuffer *fb;
76
- if (initial_length <= 0) initial_length = FBUFFER_INITIAL_LENGTH_DEFAULT;
77
- fb = ALLOC(FBuffer);
78
- memset((void *) fb, 0, sizeof(FBuffer));
79
- fb->initial_length = initial_length;
80
- return fb;
71
+ fb->initial_length = (initial_length > 0) ? initial_length : FBUFFER_INITIAL_LENGTH_DEFAULT;
72
+ if (stack_buffer) {
73
+ fb->type = FBUFFER_STACK_ALLOCATED;
74
+ fb->ptr = stack_buffer;
75
+ fb->capa = stack_buffer_size;
76
+ }
81
77
  }
82
78
 
83
79
  static void fbuffer_free(FBuffer *fb)
84
80
  {
85
- if (fb->ptr) ruby_xfree(fb->ptr);
86
- ruby_xfree(fb);
81
+ if (fb->ptr && fb->type == FBUFFER_HEAP_ALLOCATED) {
82
+ ruby_xfree(fb->ptr);
83
+ }
87
84
  }
88
85
 
89
86
  static void fbuffer_clear(FBuffer *fb)
@@ -91,20 +88,57 @@ static void fbuffer_clear(FBuffer *fb)
91
88
  fb->len = 0;
92
89
  }
93
90
 
94
- static void fbuffer_inc_capa(FBuffer *fb, unsigned long requested)
91
+ static void fbuffer_flush(FBuffer *fb)
92
+ {
93
+ rb_io_write(fb->io, rb_utf8_str_new(fb->ptr, fb->len));
94
+ fbuffer_clear(fb);
95
+ }
96
+
97
+ static void fbuffer_realloc(FBuffer *fb, unsigned long required)
95
98
  {
99
+ if (required > fb->capa) {
100
+ if (fb->type == FBUFFER_STACK_ALLOCATED) {
101
+ const char *old_buffer = fb->ptr;
102
+ fb->ptr = ALLOC_N(char, required);
103
+ fb->type = FBUFFER_HEAP_ALLOCATED;
104
+ MEMCPY(fb->ptr, old_buffer, char, fb->len);
105
+ } else {
106
+ REALLOC_N(fb->ptr, char, required);
107
+ }
108
+ fb->capa = required;
109
+ }
110
+ }
111
+
112
+ static void fbuffer_do_inc_capa(FBuffer *fb, unsigned long requested)
113
+ {
114
+ if (RB_UNLIKELY(fb->io)) {
115
+ if (fb->capa < FBUFFER_IO_BUFFER_SIZE) {
116
+ fbuffer_realloc(fb, FBUFFER_IO_BUFFER_SIZE);
117
+ } else {
118
+ fbuffer_flush(fb);
119
+ }
120
+
121
+ if (RB_LIKELY(requested < fb->capa)) {
122
+ return;
123
+ }
124
+ }
125
+
96
126
  unsigned long required;
97
127
 
98
- if (!fb->ptr) {
128
+ if (RB_UNLIKELY(!fb->ptr)) {
99
129
  fb->ptr = ALLOC_N(char, fb->initial_length);
100
130
  fb->capa = fb->initial_length;
101
131
  }
102
132
 
103
133
  for (required = fb->capa; requested > required - fb->len; required <<= 1);
104
134
 
105
- if (required > fb->capa) {
106
- REALLOC_N(fb->ptr, char, required);
107
- fb->capa = required;
135
+ fbuffer_realloc(fb, required);
136
+ }
137
+
138
+ static inline void fbuffer_inc_capa(FBuffer *fb, unsigned long requested)
139
+ {
140
+ if (RB_UNLIKELY(requested > fb->capa - fb->len)) {
141
+ fbuffer_do_inc_capa(fb, requested);
108
142
  }
109
143
  }
110
144
 
@@ -117,7 +151,13 @@ static void fbuffer_append(FBuffer *fb, const char *newstr, unsigned long len)
117
151
  }
118
152
  }
119
153
 
120
- #ifdef JSON_GENERATOR
154
+ /* Appends a character into a buffer. The buffer needs to have sufficient capacity, via fbuffer_inc_capa(...). */
155
+ static inline void fbuffer_append_reserved_char(FBuffer *fb, char chr)
156
+ {
157
+ fb->ptr[fb->len] = chr;
158
+ fb->len += 1;
159
+ }
160
+
121
161
  static void fbuffer_append_str(FBuffer *fb, VALUE str)
122
162
  {
123
163
  const char *newstr = StringValuePtr(str);
@@ -127,61 +167,70 @@ static void fbuffer_append_str(FBuffer *fb, VALUE str)
127
167
 
128
168
  fbuffer_append(fb, newstr, len);
129
169
  }
130
- #endif
131
170
 
132
- static void fbuffer_append_char(FBuffer *fb, char newchr)
171
+ static inline void fbuffer_append_char(FBuffer *fb, char newchr)
133
172
  {
134
173
  fbuffer_inc_capa(fb, 1);
135
174
  *(fb->ptr + fb->len) = newchr;
136
175
  fb->len++;
137
176
  }
138
177
 
139
- #ifdef JSON_GENERATOR
140
- static void freverse(char *start, char *end)
178
+ static inline char *fbuffer_cursor(FBuffer *fb)
141
179
  {
142
- char c;
143
-
144
- while (end > start) {
145
- c = *end, *end-- = *start, *start++ = c;
146
- }
180
+ return fb->ptr + fb->len;
147
181
  }
148
182
 
149
- static long fltoa(long number, char *buf)
183
+ static inline void fbuffer_advance_to(FBuffer *fb, char *end)
150
184
  {
151
- static char digits[] = "0123456789";
152
- long sign = number;
153
- char* tmp = buf;
154
-
155
- if (sign < 0) number = -number;
156
- do *tmp++ = digits[number % 10]; while (number /= 10);
157
- if (sign < 0) *tmp++ = '-';
158
- freverse(buf, tmp - 1);
159
- return tmp - buf;
185
+ fb->len = end - fb->ptr;
160
186
  }
161
187
 
188
+ /*
189
+ * Appends the decimal string representation of \a number into the buffer.
190
+ */
162
191
  static void fbuffer_append_long(FBuffer *fb, long number)
163
192
  {
164
- char buf[20];
165
- unsigned long len = fltoa(number, buf);
166
- fbuffer_append(fb, buf, len);
167
- }
168
-
169
- static FBuffer *fbuffer_dup(FBuffer *fb)
170
- {
171
- unsigned long len = fb->len;
172
- FBuffer *result;
193
+ /*
194
+ * The jeaiii_ultoa() function produces digits left-to-right,
195
+ * allowing us to write directly into the buffer, but we don't know
196
+ * the number of resulting characters.
197
+ *
198
+ * We do know, however, that the `number` argument is always in the
199
+ * range 0xc000000000000000 to 0x3fffffffffffffff, or, in decimal,
200
+ * -4611686018427387904 to 4611686018427387903. The max number of chars
201
+ * generated is therefore 20 (including a potential sign character).
202
+ */
203
+
204
+ static const int MAX_CHARS_FOR_LONG = 20;
205
+
206
+ fbuffer_inc_capa(fb, MAX_CHARS_FOR_LONG);
207
+
208
+ if (number < 0) {
209
+ fbuffer_append_reserved_char(fb, '-');
210
+
211
+ /*
212
+ * Since number is always > LONG_MIN, `-number` will not overflow
213
+ * and is always the positive abs() value.
214
+ */
215
+ number = -number;
216
+ }
173
217
 
174
- result = fbuffer_alloc(len);
175
- fbuffer_append(result, FBUFFER_PAIR(fb));
176
- return result;
218
+ char *end = jeaiii_ultoa(fbuffer_cursor(fb), number);
219
+ fbuffer_advance_to(fb, end);
177
220
  }
178
221
 
179
- static VALUE fbuffer_to_s(FBuffer *fb)
222
+ static VALUE fbuffer_finalize(FBuffer *fb)
180
223
  {
181
- VALUE result = rb_str_new(FBUFFER_PTR(fb), FBUFFER_LEN(fb));
182
- fbuffer_free(fb);
183
- FORCE_UTF8(result);
184
- return result;
224
+ if (fb->io) {
225
+ fbuffer_flush(fb);
226
+ fbuffer_free(fb);
227
+ rb_io_flush(fb->io);
228
+ return fb->io;
229
+ } else {
230
+ VALUE result = rb_utf8_str_new(FBUFFER_PTR(fb), FBUFFER_LEN(fb));
231
+ fbuffer_free(fb);
232
+ return result;
233
+ }
185
234
  }
186
- #endif
235
+
187
236
  #endif