lib/mb/JSON.pm

filter: Statementstmt 97.7% 221 / 226 Branchbran 92.6% 113 / 122 Conditioncond 72.2% 26 / 36 MC/DCmcdc 56.5% 13 / 23 Subroutinesub 100% 33 / 33 Podpod 100% 6 / 6 totaltotal 92.3% 412 / 446 CC 74 SCAR 21.7
CC
74
Cov
94%
_parse_string
19.0
_enc_value
14.1
_parse_value
12.0
CRAP 8.7
↑ Summary
1 package mb::JSON;
2 ######################################################################
3 #
4 # mb::JSON - JSON encode/decode for multibyte (UTF-8) strings
5 #
6 # https://metacpan.org/dist/mb-JSON
7 #
8 # Copyright (c) 2021, 2022, 2026 INABA Hitoshi <ina.cpan@gmail.com>
9 ######################################################################
10 #
11 # Compatible: Perl 5.005_03 and later
12 # Platform: Windows and UNIX/Linux
13 #
14 ######################################################################
15  
16 6 ▶use 5.00503;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 6 ▶BEGIN { if ($] < 5.006 && !defined(&warnings::import)) {
Subroutine BEGIN: called CC=3 SCAR=16.5
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.006" and not defined &warnings::import) 0 6 6
Condition33%1/3
$] < "5.006" and not defined &warnings::import
!ll&&!rl&&r
600
MC/DC0%0/2
$] < "5.006" and not defined &warnings::import
$] < "5.006" not defined &warnings::import
Truth table33%1/3
A and not(B)
A= $] < "5.006"B= not defined &warnings::import
ABresult
0X0
100
111
19 0 $INC{'warnings.pm'} = 'stub';
20 0 eval 'package warnings; sub import {}' } }
21 # The stub above is the distribution-wide boilerplate, and it is skipped
22 # whenever something else installed a warnings stub first -- every t/*.t
23 # installs an import-only one before loading this module. This file also
24 # uses `no warnings 'recursion'`, which compiles to warnings->unimport on
25 # a perl without lexical warnings, so unimport is ensured separately and
26 # under its own guard rather than as part of the block above.
27 6 ▶BEGIN { if ($] < 5.006 && !defined(&warnings::unimport)) {
Subroutine BEGIN: called CC=3 SCAR=15.4
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.006" and not defined &warnings::unimport) 0 6 6
Condition33%1/3
$] < "5.006" and not defined &warnings::unimport
!ll&&!rl&&r
600
MC/DC0%0/2
$] < "5.006" and not defined &warnings::unimport
$] < "5.006" not defined &warnings::unimport
Truth table33%1/3
A and not(B)
A= $] < "5.006"B= not defined &warnings::unimport
ABresult
0X0
100
111
28 0 eval 'package warnings; sub unimport {}' } }
29 6 ▶use warnings; local $^W = 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 6 ▶BEGIN { pop @INC if $INC[-1] eq '.' }
Subroutine BEGIN: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $INC[-1] eq "." 0 6 6
31 6 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
32 6 $VERSION = '0.07';
33 6 $VERSION = $VERSION;
34  
35 6 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
36  
37 ######################################################################
38 # Configuration
39 ######################################################################
40  
41 6 ▶use vars qw($MAX_DEPTH $STRICT);
Subroutine BEGIN: called CC=1 SCAR=0.0
42  
43 # Maximum nesting depth for decode() and encode().
44 # A false value disables the check (not recommended for untrusted input).
45 6 $MAX_DEPTH = 512;
46  
47 # When true, decode() rejects raw control characters and malformed UTF-8
48 # inside strings. Default is false (bytes are passed through unchanged).
49 6 $STRICT = 0;
50  
51 ######################################################################
52 # Boolean type objects
53 ######################################################################
54  
55 package mb::JSON::Boolean;
56 6 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
57 6 $VERSION = '0.07';
58 6 $VERSION = $VERSION;
59  
60 use overload
61 14 ▶ '0+' => sub { ${ $_[0] } },
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
62 4 ▶ '""' => sub { ${ $_[0] } ? 'true' : 'false' },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
${$_[0];} ? : 2 2 4
63 4 ▶ 'bool' => sub { ${ $_[0] } },
Subroutine __ANON__: called CC=1 SCAR=0.0
64 6 fallback => 1;
65  
66 package mb::JSON;
67  
68 6 ▶use vars qw($true $false);
Subroutine BEGIN: called CC=1 SCAR=0.0
69 {
70 6 my $_t = 1; $true = bless \$_t, 'mb::JSON::Boolean';
71 6 my $_f = 0; $false = bless \$_f, 'mb::JSON::Boolean';
72 }
73  
74 23 ▶sub true { $true }
Subroutine true: called CC=1 SCAR=0.0
Pod documented
75 15 ▶sub false { $false }
Subroutine false: called CC=1 SCAR=0.0
Pod documented
76  
77 ######################################################################
78 # Well-formed UTF-8 byte sequence (used by $STRICT validation only).
79 # The lax (default) decoder does not validate UTF-8 at all; bytes that
80 # are not '"' and not '\' are copied through unchanged.
81 ######################################################################
82  
83 6 my $UTF8_VALID = join '|', (
84 '[\x00-\x7F]',
85 '[\xC2-\xDF][\x80-\xBF]',
86 '[\xE0][\xA0-\xBF][\x80-\xBF]',
87 '[\xE1-\xEC][\x80-\xBF][\x80-\xBF]',
88 '[\xED][\x80-\x9F][\x80-\xBF]',
89 '[\xEE-\xEF][\x80-\xBF][\x80-\xBF]',
90 '[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF]',
91 '[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]',
92 '[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF]',
93 );
94  
95 3 ▶sub _is_valid_utf8 {
Subroutine _is_valid_utf8: called CC=3 SCAR=11.0
96 3 my ($s) = @_;
97 3 my $len = length $s;
98 3 pos($s) = 0;
99 3 ▶ while (pos($s) < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if (pos $s < $len) 3 2 5
100 3 ▶ return 0 unless $s =~ /\G(?:$UTF8_VALID)/gcs;
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ /\G(?:$UTF8_VALID)/cgs 1 2 3
101 }
102 2 return 1;
103 }
104  
105 ######################################################################
106 # decode -- JSON text -> Perl data
107 # parse -- alias for decode()
108 #
109 # The scanner never modifies the buffer. It advances pos() with \G
110 # and the /gc modifiers, so decoding is linear in the input length.
111 ######################################################################
112  
113 109 ▶sub decode {
Subroutine decode: called CC=5 SCAR=16.2
Pod documented
114 # Perl warns "Deep recursion on subroutine" once a sub is entered more
115 # than 100 times recursively. That fixed threshold is well below the
116 # default $MAX_DEPTH of 512, so input this module decodes correctly
117 # could still print the warning, and a caller cannot silence it: it
118 # comes from the lexical `use warnings` in this file, not the
119 # caller's. From perl 5.006 the 'recursion' category is switched off
120 # lexically in the recursive subs below. Before lexical warnings
121 # existed there is no such category and $^W is the only control, so it
122 # is turned off for the extent of the parse on those perls. On 5.006
123 # and later this localizes $^W to the value it already had.
124 109 ▶ local $^W = ($] < 5.006) ? 0 : $^W;
Branch: 1 branch
BranchTrueFalseTotal
$] < 5.006 ? : 0 109 109
125 109 ▶ my $json = defined $_[0] ? $_[0] : $_;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 106 3 109
126 109 ▶ $json = '' unless defined $json;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $json 0 109 109
127 109 $json =~ s/\A\xEF\xBB\xBF//s;
128 109 pos($json) = 0;
129 109 my $val = _parse_value(\$json, 0);
130 86 $json =~ /\G[\x20\x09\x0A\x0D]+/gc;
131 86 ▶ croak "mb::JSON::decode: trailing garbage: " . substr($json, pos($json), 20)
Branch: 1 branch
BranchTrueFalseTotal
if pos $json < length $json 3 83 86
132 if pos($json) < length($json);
133 83 return $val;
134 }
135  
136 12 ▶sub parse { # alias for decode()
Subroutine parse: called CC=2 SCAR=6.9
Pod documented
137 # Delegating in one hop rather than copying the argument into a
138 # lexical first: decode() already resolves an omitted or undefined
139 # argument to $_, and already takes the one copy it needs. Copying
140 # here as well duplicated the whole document for nothing.
141 12 ▶ return decode(@_ ? $_[0] : $_);
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 10 2 12
142 }
143  
144 # Whitespace is skipped inline with /\G[\x20\x09\x0A\x0D]+/gc. The four
145 # bytes are spelled out rather than written \s on purpose. RFC 8259
146 # allows exactly space, tab, LF and CR between tokens, while perl's \s
147 # also matches form feed on every perl and, from perl 5.18, vertical tab
148 # as well. Using \s would therefore both accept input JSON forbids and
149 # make this module answer differently on perl 5.16 and perl 5.18 for the
150 # same document, which is the one thing a distribution targeting
151 # 5.005_03 through the latest perl must not do.
152 #
153 # The + quantifier means the pattern either consumes at least one
154 # character or fails outright, so it never records an empty match and is
155 # safe to repeat at the same position; /c keeps pos() on failure.
156  
157 905 ▶sub _parse_value {
Subroutine _parse_value: called CC=12 SCAR=24.8
158 6 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
159 905 my ($r, $depth) = @_;
160 905 $$r =~ /\G[\x20\x09\x0A\x0D]+/gc;
161 905 ▶ croak "mb::JSON::decode: unexpected end of input"
Branch: 1 branch
BranchTrueFalseTotal
if pos $$r >= length $$r 1 904 905
162 if pos($$r) >= length($$r);
163  
164 904 my $c = substr($$r, pos($$r), 1);
165  
166 904 ▶ if ($c eq '{') { return _parse_object($r, $depth) }
Branch: 7 branches
BranchTrueFalseTotal
if ($c eq '{') { } 34 870 904
elsif ($c eq '[') { } 729 141 870
elsif ($c eq '"') { } 43 98 141
elsif ($$r =~ /\Gnull(?![a-zA-Z0-9_])/cgs) { } 6 92 98
elsif ($$r =~ /\Gtrue(?![a-zA-Z0-9_])/cgs) { } 18 74 92
elsif ($$r =~ /\Gfalse(?![a-zA-Z0-9_])/cgs) { } 12 62 74
elsif ($$r =~ /\G(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/cgs) { } 60 2 62
167 729 elsif ($c eq '[') { return _parse_array($r, $depth) }
168 43 elsif ($c eq '"') { return _parse_string($r) }
169 6 elsif ($$r =~ /\Gnull(?![a-zA-Z0-9_])/gcs) { return undef }
170 18 elsif ($$r =~ /\Gtrue(?![a-zA-Z0-9_])/gcs) { return $true }
171 12 elsif ($$r =~ /\Gfalse(?![a-zA-Z0-9_])/gcs) { return $false }
172 elsif ($$r =~ /\G(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/gcs) {
173 60 my $literal = $1;
174 60 my $n = $literal + 0;
175 # A finite JSON number literal can still overflow perl's NV range
176 # (e.g. 1e400) and become Inf. Detect it the same way encode()
177 # detects Inf/NaN: by the spelling perl prints for it, since no
178 # portable numeric test exists on perl 5.005 (see encode() below).
179 60 ▶ croak "mb::JSON::decode: number out of range: $literal"
Branch: 1 branch
BranchTrueFalseTotal
if $n =~ /\A-?(?:inf(?:inity)?|nan|1\.#[a-z]+)\z/is 2 58 60
180 if $n =~ /\A-?(?:inf(?:inity)?|nan|1\.#[a-z]+)\z/is;
181 # The same literal can underflow to zero at the other end of the
182 # range (e.g. 1e-400). A literal whose mantissa has a nonzero
183 # digit yet converts to exactly zero lost every significant digit
184 # it had, so it is rejected too rather than quietly returning 0.
185 # Only the mantissa is examined: "0e-400" is a legitimate zero,
186 # and the digits of its exponent are not significant digits.
187 58 my $mantissa = $literal;
188 58 $mantissa =~ s/[eE].*\z//s;
189 58 ▶ croak "mb::JSON::decode: number out of range: $literal"
Branch: 1 branch
BranchTrueFalseTotal
if $n == 0 and $mantissa =~ /[1-9]/ 2 56 58
Condition100%3/3
$n == 0 and $mantissa =~ /[1-9]/
!ll&&!rl&&r
4972
MC/DC100%2/2
$n == 0 and $mantissa =~ /[1-9]/
$n == 0 $mantissa =~ /[1-9]/
Truth table100%3/3
A and B
A= $n == 0B= $mantissa =~ /[1-9]/
ABresult
0X0
100
111
190 if $n == 0 && $mantissa =~ /[1-9]/;
191 56 return $n;
192 }
193 else {
194 2 croak "mb::JSON::decode: unexpected token: "
195 . substr($$r, pos($$r), 20);
196 }
197 }
198  
199 34 ▶sub _parse_object {
Subroutine _parse_object: called CC=8 SCAR=20.8
200 6 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
201 34 my ($r, $depth) = @_;
202 34 ▶ croak "mb::JSON::decode: nesting too deep (max $MAX_DEPTH)"
Branch: 1 branch
BranchTrueFalseTotal
if $mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH 1 33 34
Condition66%2/3
$mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH
!ll&&!rl&&r
0331
MC/DC50%1/2
$mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH
$mb::JSON::MAX_DEPTH $depth >= $mb::JSON::MAX_DEPTH
Truth table66%2/3
A and B
A= $mb::JSON::MAX_DEPTHB= $depth >= $mb::JSON::MAX_DEPTH
ABresult
0X0
100
111
203 if $MAX_DEPTH && $depth >= $MAX_DEPTH;
204 33 $$r =~ /\G\{/gcs;
205 33 my %obj;
206 33 $$r =~ /\G[\x20\x09\x0A\x0D]+/gc;
207 33 ▶ if ($$r =~ /\G\}/gcs) { return { %obj } }
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ /\G\}/cgs) 1 32 33
208 32 while (1) {
209 53 $$r =~ /\G[\x20\x09\x0A\x0D]+/gc;
210 53 ▶ croak "mb::JSON::decode: expected string key in object"
Branch: 1 branch
BranchTrueFalseTotal
unless substr($$r, pos $$r, 1) eq "\"" 2 51 53
211 unless substr($$r, pos($$r), 1) eq '"';
212 51 my $key = _parse_string($r);
213 51 $$r =~ /\G[\x20\x09\x0A\x0D]+/gc;
214 51 ▶ $$r =~ /\G:/gcs
Branch: 1 branch
BranchTrueFalseTotal
$$r =~ /\G:/cgs or croak("mb::JSON::decode: expected ':' after key '${key}'") 50 1 51
215 or croak "mb::JSON::decode: expected ':' after key '$key'";
216 50 my $val = _parse_value($r, $depth + 1);
217 45 $obj{$key} = $val;
218 45 $$r =~ /\G[\x20\x09\x0A\x0D]+/gc;
219 45 ▶ if ($$r =~ /\G,/gcs) { next }
Branch: 2 branches
BranchTrueFalseTotal
if ($$r =~ /\G,/cgs) { } 21 24 45
elsif ($$r =~ /\G\}/cgs) { } 23 1 24
220 23 elsif ($$r =~ /\G\}/gcs) { last }
221 1 else { croak "mb::JSON::decode: expected ',' or '}' in object" }
222 }
223 23 return { %obj };
224 }
225  
226 729 ▶sub _parse_array {
Subroutine _parse_array: called CC=6 SCAR=17.9
227 6 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
228 729 my ($r, $depth) = @_;
229 729 ▶ croak "mb::JSON::decode: nesting too deep (max $MAX_DEPTH)"
Branch: 1 branch
BranchTrueFalseTotal
if $mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH 3 726 729
Condition100%3/3
$mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH
!ll&&!rl&&r
87183
MC/DC100%2/2
$mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH
$mb::JSON::MAX_DEPTH $depth >= $mb::JSON::MAX_DEPTH
Truth table100%3/3
A and B
A= $mb::JSON::MAX_DEPTHB= $depth >= $mb::JSON::MAX_DEPTH
ABresult
0X0
100
111
230 if $MAX_DEPTH && $depth >= $MAX_DEPTH;
231 726 $$r =~ /\G\[/gcs;
232 726 my @arr;
233 726 $$r =~ /\G[\x20\x09\x0A\x0D]+/gc;
234 726 ▶ if ($$r =~ /\G\]/gcs) { return [ @arr ] }
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ /\G\]/cgs) 5 721 726
235 721 while (1) {
236 746 push @arr, _parse_value($r, $depth + 1);
237 728 $$r =~ /\G[\x20\x09\x0A\x0D]+/gc;
238 728 ▶ if ($$r =~ /\G,/gcs) { next }
Branch: 2 branches
BranchTrueFalseTotal
if ($$r =~ /\G,/cgs) { } 25 703 728
elsif ($$r =~ /\G\]/cgs) { } 702 1 703
239 702 elsif ($$r =~ /\G\]/gcs) { last }
240 1 else { croak "mb::JSON::decode: expected ',' or ']' in array" }
241 }
242 702 return [ @arr ];
243 }
244  
245 6 my %UNESC = (
246 '"' => '"', '\\' => '\\', '/' => '/',
247 'b' => "\x08", 'f' => "\x0C",
248 'n' => "\n", 'r' => "\r", 't' => "\t",
249 );
250  
251 94 ▶sub _parse_string {
Subroutine _parse_string: called CC=19 SCAR=29.4
252 94 my ($r) = @_;
253 94 $$r =~ /\G"/gcs;
254 94 my $s = '';
255 94 while (1) {
256 191 ▶ if ($$r =~ /\G"/gcs) { last }
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ /\G"/cgs) 88 103 191
257  
258 # Fast path: a run of ordinary characters, copied verbatim.
259 103 ▶ if ($STRICT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mb::JSON::STRICT) { } 9 94 103
260 9 ▶ if ($$r =~ /\G([^"\\\x00-\x1F]+)/gcs) { $s .= $1; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ /\G([^"\\\x00-\x1F]+)/cgs) 6 3 9
261 }
262 else {
263 94 ▶ if ($$r =~ /\G([^"\\]+)/gcs) { $s .= $1; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ /\G([^"\\]+)/cgs) 84 10 94
264 }
265  
266 13 ▶ if ($$r =~ /\G\\(["\\\/bfnrt])/gcs) { $s .= $UNESC{$1}; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ m[\G\\(["\\/bfnrt])]cgs) 3 10 13
267  
268 10 ▶ if ($$r =~ /\G\\u([0-9a-fA-F]{4})/gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ /\G\\u([0-9a-fA-F]{4})/cgs) 7 3 10
269 7 my $cp = hex($1);
270 7 ▶ if ($cp >= 0xD800 && $cp <= 0xDBFF) {
Branch: 2 branches
BranchTrueFalseTotal
if ($cp >= 55296 and $cp <= 56319) { } 5 2 7
elsif ($cp >= 56320 and $cp <= 57343) { } 1 1 2
Condition100%3/3
$cp >= 55296 and $cp <= 56319
!ll&&!rl&&r
115
MC/DC100%2/2
$cp >= 55296 and $cp <= 56319
$cp >= 55296 $cp <= 56319
Truth table100%3/3
A and B
A= $cp >= 55296B= $cp <= 56319
ABresult
0X0
100
111
271 # high surrogate: a low surrogate \uDC00-\uDFFF must follow
272 5 ▶ if ($$r =~ /\G\\u([0-9a-fA-F]{4})/gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$r =~ /\G\\u([0-9a-fA-F]{4})/cgs) { } 4 1 5
273 4 my $lo = hex($1);
274 4 ▶ if ($lo >= 0xDC00 && $lo <= 0xDFFF) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo >= 56320 and $lo <= 57343) { } 3 1 4
Condition66%2/3
$lo >= 56320 and $lo <= 57343
!ll&&!rl&&r
103
MC/DC50%1/2
$lo >= 56320 and $lo <= 57343
$lo >= 56320 $lo <= 57343
Truth table66%2/3
A and B
A= $lo >= 56320B= $lo <= 57343
ABresult
0X0
100
111
275 3 $cp = 0x10000
276 + (($cp - 0xD800) << 10)
277 + ($lo - 0xDC00);
278 3 $s .= _cp_to_utf8($cp);
279 }
280 else {
281 1 croak "mb::JSON::decode: invalid low surrogate in Unicode escape sequence";
282 }
283 }
284 else {
285 1 croak "mb::JSON::decode: lone high surrogate in Unicode escape sequence";
286 }
287 }
288 ▶ elsif ($cp >= 0xDC00 && $cp <= 0xDFFF) {
Condition66%2/3
$cp >= 56320 and $cp <= 57343
!ll&&!rl&&r
101
MC/DC50%1/2
$cp >= 56320 and $cp <= 57343
$cp >= 56320 $cp <= 57343
Truth table66%2/3
A and B
A= $cp >= 56320B= $cp <= 57343
ABresult
0X0
100
111
289 1 croak "mb::JSON::decode: lone low surrogate in Unicode escape sequence";
290 }
291 else {
292 1 $s .= _cp_to_utf8($cp);
293 }
294 4 next;
295 }
296  
297 3 my $p = pos($$r);
298 3 ▶ if ($p >= length($$r)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p >= length $$r) 1 2 3
299 1 croak "mb::JSON::decode: unterminated string";
300 }
301 2 ▶ if (substr($$r, $p, 1) eq "\\") {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($$r, $p, 1) eq "\\") 1 1 2
302 1 croak "mb::JSON::decode: invalid escape sequence: "
303 . substr($$r, $p, 2);
304 }
305 1 croak "mb::JSON::decode: raw control character in string";
306 }
307 88 ▶ if ($STRICT && $s =~ /[\x80-\xFF]/ && !_is_valid_utf8($s)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mb::JSON::STRICT and $s =~ /[\x80-\xFF]/ and not _is_valid_utf8($s)) 1 87 88
Condition100%6/6
$mb::JSON::STRICT and $s =~ /[\x80-\xFF]/ and not _is_valid_utf8($s)
!ll&&!rl&&r
8521
$mb::JSON::STRICT and $s =~ /[\x80-\xFF]/
!ll&&!rl&&r
8323
MC/DC100%3/3
$mb::JSON::STRICT and $s =~ /[\x80-\xFF]/ and not _is_valid_utf8($s)
$mb::JSON::STRICT $s =~ /[\x80-\xFF]/ not _is_valid_utf8($s)
Truth table100%4/4
A and B and not(C)
A= $mb::JSON::STRICTB= $s =~ /[\x80-\xFF]/C= not _is_valid_utf8($s)
ABCresult
0XX0
10X0
1100
1111
308 1 croak "mb::JSON::decode: malformed UTF-8 in string";
309 }
310 87 return $s;
311 }
312  
313 4 ▶sub _cp_to_utf8 {
Subroutine _cp_to_utf8: called CC=4 SCAR=15.0
314 4 my ($cp) = @_;
315 4 ▶ return chr($cp) if $cp <= 0x7F;
Branch: 1 branch
BranchTrueFalseTotal
if $cp <= 127 1 3 4
316 3 ▶ if ($cp <= 0x7FF) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cp <= 2047) 0 3 3
317 0 return chr(0xC0|($cp>>6)) . chr(0x80|($cp&0x3F));
318 }
319 3 ▶ if ($cp <= 0xFFFF) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cp <= 65535) 0 3 3
320 0 return chr(0xE0|($cp>>12))
321 . chr(0x80|(($cp>>6)&0x3F))
322 . chr(0x80|($cp&0x3F));
323 }
324 # U+10000 .. U+10FFFF : 4-byte sequence. Codepoint is decomposed into
325 # bytes so every chr() argument stays <= 0xFF (safe on perl 5.005_03).
326 3 return chr(0xF0|($cp>>18))
327 . chr(0x80|(($cp>>12)&0x3F))
328 . chr(0x80|(($cp>>6)&0x3F))
329 . chr(0x80|($cp&0x3F));
330 }
331  
332 ######################################################################
333 # encode -- Perl data -> JSON text
334 # stringify -- alias for encode()
335 #
336 # Encoding rules:
337 # undef -> null
338 # mb::JSON::true -> true
339 # mb::JSON::false -> false
340 # number-like scalar -> number (no quotes)
341 # other scalar -> "string" (UTF-8 kept as-is)
342 # ARRAY ref -> [...]
343 # HASH ref -> {...} (keys sorted alphabetically)
344 ######################################################################
345  
346 115 ▶sub encode {
Subroutine encode: called CC=3 SCAR=11.1
Pod documented
347 # See the comment in decode() for why $^W is localized here.
348 115 ▶ local $^W = ($] < 5.006) ? 0 : $^W;
Branch: 1 branch
BranchTrueFalseTotal
$] < 5.006 ? : 0 115 115
349 115 ▶ my $data = @_ ? $_[0] : $_;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 114 1 115
350 115 return _enc_value($data, 0, {});
351 }
352  
353 45 ▶sub stringify { # alias for encode()
Subroutine stringify: called CC=2 SCAR=6.9
Pod documented
354 # One hop, for the same reason as parse() above.
355 45 ▶ return encode(@_ ? $_[0] : $_);
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 44 1 45
356 }
357  
358 1455 ▶sub _enc_value {
Subroutine _enc_value: called CC=14 SCAR=26.4
359 6 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
360 1455 my ($v, $depth, $seen) = @_;
361 1455 ▶ return 'null' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 14 1441 1455
362  
363 1441 ▶ if (ref $v eq 'mb::JSON::Boolean') { return $$v ? 'true' : 'false' }
Branch: 2 branches
BranchTrueFalseTotal
if (ref $v eq "mb::JSON::Boolean") 34 1407 1441
$$v ? : 21 13 34
364  
365 # The depth limit is applied where _parse_object() and _parse_array()
366 # apply it: on entering a container, with >=. Testing every value
367 # with > instead let encode() accept one more level of nesting than
368 # decode() would read back, and counted a leaf scalar as a level of
369 # its own, which the decoder never does. Both directions now stop at
370 # the same $MAX_DEPTH containers.
371 1407 ▶ if (ref $v eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq "ARRAY") 1251 156 1407
372 1251 ▶ croak "mb::JSON::encode: nesting too deep (max $MAX_DEPTH)"
Branch: 1 branch
BranchTrueFalseTotal
if $mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH 4 1247 1251
Condition66%2/3
$mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH
!ll&&!rl&&r
012474
MC/DC50%1/2
$mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH
$mb::JSON::MAX_DEPTH $depth >= $mb::JSON::MAX_DEPTH
Truth table66%2/3
A and B
A= $mb::JSON::MAX_DEPTHB= $depth >= $mb::JSON::MAX_DEPTH
ABresult
0X0
100
111
373 if $MAX_DEPTH && $depth >= $MAX_DEPTH;
374 1247 my $id = "$v";
375 1247 ▶ croak "mb::JSON::encode: circular reference detected" if $seen->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $seen->{$id} 2 1245 1247
376 1245 $seen->{$id} = 1;
377 my $out = '['
378 1245 . join(',', map { _enc_value($_, $depth + 1, $seen) } @$v)
379 . ']';
380 715 delete $seen->{$id};
381 715 return $out;
382 }
383  
384 156 ▶ if (ref $v eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq "HASH") 33 123 156
385 33 ▶ croak "mb::JSON::encode: nesting too deep (max $MAX_DEPTH)"
Branch: 1 branch
BranchTrueFalseTotal
if $mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH 0 33 33
Condition33%1/3
$mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH
!ll&&!rl&&r
0330
MC/DC0%0/2
$mb::JSON::MAX_DEPTH and $depth >= $mb::JSON::MAX_DEPTH
$mb::JSON::MAX_DEPTH $depth >= $mb::JSON::MAX_DEPTH
Truth table33%1/3
A and B
A= $mb::JSON::MAX_DEPTHB= $depth >= $mb::JSON::MAX_DEPTH
ABresult
0X0
100
111
386 if $MAX_DEPTH && $depth >= $MAX_DEPTH;
387 33 my $id = "$v";
388 33 ▶ croak "mb::JSON::encode: circular reference detected" if $seen->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $seen->{$id} 1 32 33
389 32 $seen->{$id} = 1;
390 my @pairs = map {
391 32 _enc_string($_) . ':' . _enc_value($v->{$_}, $depth + 1, $seen)
392 } sort keys %$v;
393 29 my $out = '{' . join(',', @pairs) . '}';
394 29 delete $seen->{$id};
395 29 return $out;
396 }
397  
398 # number: matches JSON number pattern exactly
399 123 ▶ if ($v =~ /\A-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?\z/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ /\A-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?\z/s) 70 53 123
400 70 return $v;
401 }
402  
403 # Inf / NaN have no JSON representation and would silently become the
404 # strings "Inf" / "NaN". A finite number always matches the pattern
405 # above, so anything reaching here that still spells one of the forms
406 # perl prints for a non-finite value is one. This is a plain string
407 # test on purpose: asking the scalar whether it holds a number needs
408 # B, whose constants are AUTOLOADed on perl 5.005 and cannot be called
409 # as functions there, and a numeric test alone is not portable either
410 # because from perl 5.22 the string "Inf" numifies to Inf. The cost
411 # is that a string spelling exactly "Inf" or "NaN" is rejected too;
412 # see LIMITATIONS.
413 53 ▶ if ($v =~ /\A-?(?:inf(?:inity)?|nan|1\.#[a-z]+)\z/is) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ /\A-?(?:inf(?:inity)?|nan|1\.#[a-z]+)\z/is) 5 48 53
414 5 croak "mb::JSON::encode: cannot encode Inf or NaN";
415 }
416  
417 48 return _enc_string($v);
418 }
419  
420 105 ▶sub _enc_string {
Subroutine _enc_string: called CC=1 SCAR=0.0
421 105 my ($s) = @_;
422 105 $s =~ s/\\/\\\\/g;
423 105 $s =~ s/"/\\"/g;
424 105 $s =~ s/\x08/\\b/g;
425 105 $s =~ s/\x0C/\\f/g;
426 105 $s =~ s/\n/\\n/g;
427 105 $s =~ s/\r/\\r/g;
428 105 $s =~ s/\t/\\t/g;
429 105 $s =~ s/([\x00-\x1F])/sprintf('\\u%04X', ord($1))/ge;
430 105 return '"' . $s . '"';
431 }
432  
433 6 1;
434  
435 =head1 NAME
436  
437 mb::JSON - JSON encode/decode for multibyte (UTF-8) strings
438  
439 =head1 VERSION
440  
441 Version 0.07
442  
443 =head1 SYNOPSIS
444  
445 use mb::JSON;
446  
447 # decode: JSON text -> Perl data
448 my $decoded = mb::JSON::decode("{\"name\":\"\\u7530\\u4e2d\",\"age\":30}");
449  
450 # parse: alias for decode()
451 my $parsed = mb::JSON::parse("{\"key\":\"value\"}");
452  
453 # encode: Perl data -> JSON text
454 my $json = mb::JSON::encode({ name => 'Tanaka', age => 30 });
455 # -> '{"age":30,"name":"Tanaka"}'
456  
457 # stringify: alias for encode()
458 my $text = mb::JSON::stringify({ name => 'Tanaka', age => 30 });
459 # -> '{"age":30,"name":"Tanaka"}'
460  
461 # Boolean values
462 my $flags = mb::JSON::encode({
463 active => mb::JSON::true,
464 locked => mb::JSON::false,
465 });
466 # -> '{"active":true,"locked":false}'
467  
468 # null
469 my $empty = mb::JSON::encode({ value => undef });
470 # -> '{"value":null}'
471  
472 =head1 TABLE OF CONTENTS
473  
474 =over 4
475  
476 =item * L</DESCRIPTION>
477  
478 =item * L</FUNCTIONS>
479  
480 =item * L</CONFIGURATION>
481  
482 =item * L</BOOLEAN VALUES>
483  
484 =item * L</ENCODING RULES>
485  
486 =item * L</DECODING RULES>
487  
488 =item * L</LIMITATIONS>
489  
490 =item * L</DIAGNOSTICS>
491  
492 =item * L</INCOMPATIBLE CHANGES>
493  
494 =item * L</PERFORMANCE>
495  
496 =item * L</SEE ALSO>
497  
498 =item * L</BUGS>
499  
500 =back
501  
502 =head1 DESCRIPTION
503  
504 C<mb::JSON> is a simple, dependency-free JSON encoder and decoder
505 designed for Perl 5.005_03 and later. It handles UTF-8 multibyte
506 strings correctly, making it suitable for environments where standard
507 JSON modules requiring Perl 5.8+ are unavailable.
508  
509 C<mb::JSON> provides two pairs of symmetric functions:
510 C<decode()>/C<parse()> convert JSON text to Perl data, and
511 C<encode()>/C<stringify()> convert Perl data to JSON text.
512 Within each pair, both names are aliases and produce identical output.
513  
514 The decoder scans its input with C<pos()> and the C<\G> anchor and never
515 modifies the buffer, so decoding time is linear in the length of the
516 input. See L</PERFORMANCE>.
517  
518 =head1 FUNCTIONS
519  
520 =head2 decode( $json_text )
521  
522 Converts a JSON text string to a Perl data structure.
523 If the argument is omitted or undefined, C<$_> is used.
524 A leading UTF-8 byte order mark is ignored.
525  
526 my $data = mb::JSON::decode($json_text);
527  
528 =head2 parse( $json_text )
529  
530 Alias for C<decode()>. Both names are interchangeable.
531  
532 my $data = mb::JSON::parse($json_text);
533  
534 =head2 encode( $data )
535  
536 Converts a Perl data structure to a JSON text string.
537 Returns a byte string encoded in UTF-8.
538 If called with no argument at all, C<$_> is used; note that
539 C<encode(undef)> still returns C<null>.
540  
541 my $json = mb::JSON::encode($data);
542  
543 =head2 stringify( $data )
544  
545 Alias for C<encode()>. Both names are interchangeable.
546 Mirrors the C<JSON.stringify()> function in JavaScript.
547  
548 my $json = mb::JSON::stringify($data);
549  
550 =head2 true
551  
552 Returns the singleton C<mb::JSON::Boolean> object representing JSON
553 C<true>. Numifies to C<1>, stringifies to C<"true">.
554  
555 =head2 false
556  
557 Returns the singleton C<mb::JSON::Boolean> object representing JSON
558 C<false>. Numifies to C<0>, stringifies to C<"false">.
559  
560 =head1 CONFIGURATION
561  
562 Two package variables tune the behaviour of the module. Both are
563 ordinary globals, so C<local> works as expected.
564  
565 =head2 $mb::JSON::MAX_DEPTH
566  
567 Maximum nesting depth accepted by C<decode()> and produced by
568 C<encode()>. The default is C<512>. Deeply nested input would
569 otherwise exhaust the Perl stack, so the limit matters when decoding
570 untrusted data. Setting the variable to a false value disables the
571 check entirely.
572  
573 The limit counts objects and arrays, not values, and both directions
574 stop at the same number of them, so any document C<decode()> accepts can
575 be handed straight back to C<encode()>.
576  
577 local $mb::JSON::MAX_DEPTH = 64;
578 my $data = mb::JSON::decode($untrusted);
579  
580 =head2 $mb::JSON::STRICT
581  
582 When false (the default), C<decode()> copies string bytes through
583 unchanged: raw control characters are accepted and UTF-8 is not
584 validated. This keeps the module usable as a byte-transparent filter.
585  
586 When true, C<decode()> rejects a raw control character C<U+0000>-C<U+001F>
587 inside a string, and rejects a string whose bytes are not well-formed
588 UTF-8.
589  
590 local $mb::JSON::STRICT = 1;
591 my $data = mb::JSON::decode($untrusted);
592  
593 =head1 BOOLEAN VALUES
594  
595 Perl has no native boolean type. To represent JSON C<true> and
596 C<false> unambiguously, C<mb::JSON> provides two singleton objects:
597  
598 mb::JSON::true -- stringifies as "true", numifies as 1
599 mb::JSON::false -- stringifies as "false", numifies as 0
600  
601 Use these when encoding a boolean value:
602  
603 my $json = mb::JSON::encode({ flag => mb::JSON::true });
604 # -> '{"flag":true}'
605  
606 A plain C<1> or C<0> encodes as a JSON number, not a boolean:
607  
608 my $json = mb::JSON::encode({ count => 1 });
609 # -> '{"count":1}'
610  
611 When decoding, JSON C<true> and C<false> are returned as
612 C<mb::JSON::Boolean> objects, which behave as C<1> and C<0>
613 in numeric and boolean context.
614  
615 C<stringify()> behaves identically to C<encode()> for boolean values.
616  
617 =head1 ENCODING RULES
618  
619 Applies to both C<encode()> and C<stringify()>.
620  
621 =over 4
622  
623 =item undef -> null
624  
625 =item mb::JSON::true -> true, mb::JSON::false -> false
626  
627 =item Number
628  
629 A scalar matching the JSON number pattern is encoded as a bare number.
630 C<Inf> and C<NaN> have no JSON representation and are rejected with an
631 error rather than silently emitted as the strings C<"Inf"> and C<"NaN">.
632  
633 =item String
634  
635 Encoded as a double-quoted JSON string. UTF-8 multibyte bytes are
636 output as-is (not C<\uXXXX>-escaped). Control characters U+0000-U+001F
637 are escaped.
638  
639 =item ARRAY reference -> JSON array C<[...]>
640  
641 =item HASH reference -> JSON object C<{...}>
642  
643 Hash keys are sorted alphabetically for deterministic output.
644  
645 =item Nesting
646  
647 A structure nested deeper than C<$mb::JSON::MAX_DEPTH> is rejected, and
648 a reference that contains itself is reported as a circular reference
649 instead of recursing forever.
650  
651 =back
652  
653 =head1 DECODING RULES
654  
655 Applies to both C<decode()> and C<parse()>.
656  
657 =over 4
658  
659 =item null -> undef
660  
661 =item true -> mb::JSON::Boolean (numifies to 1)
662  
663 =item false -> mb::JSON::Boolean (numifies to 0)
664  
665 =item Number -> Perl number
666  
667 =item String -> Perl string (\uXXXX converted to UTF-8)
668  
669 A C<\uXXXX> escape in the Basic Multilingual Plane is converted to its
670 UTF-8 byte sequence. A UTF-16 surrogate pair
671 (C<\uD800>-C<\uDBFF> followed by C<\uDC00>-C<\uDFFF>) is combined into
672 the single code point it represents and emitted as 4-byte UTF-8, so
673 characters above U+FFFF (e.g. emoji) decode correctly.
674  
675 =item Object -> hash reference
676  
677 When the same key appears more than once, the last occurrence wins.
678  
679 =item Array -> array reference
680  
681 =item Byte order mark
682  
683 A leading UTF-8 byte order mark (C<EF BB BF>) is skipped before parsing.
684  
685 =item Whitespace
686  
687 Space, tab, line feed and carriage return are allowed between tokens,
688 which is exactly the set RFC 8259 defines. Form feed and vertical tab
689 are not whitespace and are reported as an unexpected token. The set is
690 spelled out rather than written as perl's C<\s>, so it is the same on
691 every supported perl; C<\s> matches form feed everywhere and, from perl
692 5.18, vertical tab as well.
693  
694 =item Nesting
695  
696 Input nested deeper than C<$mb::JSON::MAX_DEPTH> is rejected. The limit
697 counts containers, so a scalar inside the deepest allowed object or
698 array is not a further level. C<encode()> applies the same rule, and
699 therefore can always write back out whatever C<decode()> accepted.
700  
701 =back
702  
703 =head1 LIMITATIONS
704  
705 =over 4
706  
707 =item *
708  
709 References other than ARRAY and HASH (e.g. code references, blessed
710 objects other than C<mb::JSON::Boolean>) are stringified rather than
711 raising an error. A blessed hash or array reference is stringified
712 too, because C<ref()> returns the class name rather than C<HASH> or
713 C<ARRAY>.
714  
715 =item *
716  
717 A scalar that matches the JSON number pattern is encoded as a number
718 even when it was intended as a string, so C<"30"> becomes C<30>.
719 Leading-zero strings such as C<"007"> are preserved as strings because
720 they do not match the JSON number pattern.
721  
722 =item *
723  
724 Numbers are decoded through Perl's own numeric conversion, so an
725 integer wider than the platform's floating point mantissa loses
726 precision, and C<1.0> or C<1e2> is re-encoded as C<1> or C<100>.
727  
728 =item *
729  
730 By default the decoder does not validate UTF-8 and accepts raw control
731 characters inside strings. Set C<$mb::JSON::STRICT> to enable those
732 checks.
733  
734 =item *
735  
736 C<Inf> and C<NaN> are recognised by how they print, so a string that
737 spells exactly C<"Inf">, C<"-Inf">, C<"Infinity">, C<"NaN"> or one of the
738 C<"1.#INF"> forms is rejected as well, even when it was meant as text.
739 Longer words are unaffected: C<"Info"> and C<"nano"> encode normally.
740 Perl offers no portable way to tell a numeric C<Inf> from a string
741 spelling it -- from perl 5.22 even C<"Info"> numifies to C<Inf> -- so the
742 module prefers a rule that behaves identically on every supported perl.
743  
744 =back
745  
746 =head1 DIAGNOSTICS
747  
748 =over 4
749  
750 =item C<mb::JSON::decode: unexpected end of input>
751  
752 The JSON text ended before a complete value was parsed.
753  
754 =item C<mb::JSON::decode: unexpected token: E<lt>textE<gt>>
755  
756 An unrecognised token was encountered while parsing.
757  
758 =item C<mb::JSON::decode: expected string key in object>
759  
760 An object key was not a quoted string.
761  
762 =item C<mb::JSON::decode: expected ':' after key 'E<lt>keyE<gt>'>
763  
764 The colon separator was missing after an object key.
765  
766 =item C<mb::JSON::decode: expected ',' or '}' in object>
767  
768 A JSON object was not properly terminated or separated.
769  
770 =item C<mb::JSON::decode: expected ',' or ']' in array>
771  
772 A JSON array was not properly terminated or separated.
773  
774 =item C<mb::JSON::decode: unterminated string>
775  
776 A JSON string was not closed with a double-quote.
777  
778 =item C<mb::JSON::decode: invalid escape sequence: E<lt>textE<gt>>
779  
780 A backslash inside a string was followed by a character that is not a
781 recognized escape (C<\">, C<\\>, C</>, C<\b>, C<\f>, C<\n>, C<\r>,
782 C<\t>) or a C<\uXXXX> sequence.
783  
784 =item C<mb::JSON::decode: trailing garbage: E<lt>textE<gt>>
785  
786 Extra text was found after a successfully parsed top-level value.
787  
788 =item C<mb::JSON::decode: lone high surrogate in Unicode escape sequence>
789  
790 A high surrogate C<\uD800>-C<\uDBFF> was not followed by a C<\uXXXX> escape.
791  
792 =item C<mb::JSON::decode: invalid low surrogate in Unicode escape sequence>
793  
794 A high surrogate was followed by a C<\uXXXX> escape that was not a low
795 surrogate C<\uDC00>-C<\uDFFF>.
796  
797 =item C<mb::JSON::decode: lone low surrogate in Unicode escape sequence>
798  
799 A low surrogate C<\uDC00>-C<\uDFFF> appeared without a preceding high surrogate.
800  
801 =item C<mb::JSON::decode: raw control character in string>
802  
803 C<$mb::JSON::STRICT> is set and an unescaped character in the range
804 U+0000-U+001F appeared inside a string.
805  
806 =item C<mb::JSON::decode: malformed UTF-8 in string>
807  
808 C<$mb::JSON::STRICT> is set and a decoded string is not a well-formed
809 UTF-8 byte sequence.
810  
811 =item C<mb::JSON::decode: number out of range: E<lt>textE<gt>>
812  
813 A JSON number literal is finite JSON syntax but outside the range of
814 this perl's floating point type. Too large and converting it would
815 silently produce C<Inf>, C<-Inf>, or C<NaN>; too small and it would
816 silently produce C<0>, having lost every significant digit the literal
817 carried. C<decode()> rejects both instead, mirroring C<encode()>'s
818 refusal to write a non-finite value out (see
819 C<mb::JSON::encode: cannot encode Inf or NaN> above). Where that range
820 ends depends on how perl was built: an ordinary double runs out around
821 C<1e308>, so C<1e400> and C<1e-400> are rejected there, while a perl
822 built C<-Duselongdouble> or C<-Dusequadmath> accepts both and rejects
823 only far more extreme literals. A literal that is genuinely zero is
824 unaffected on every build: only the mantissa is examined, so C<0>,
825 C<0.000> and C<0e-400> all decode to C<0>.
826  
827 =item C<mb::JSON::decode: nesting too deep (max E<lt>NE<gt>)>
828  
829 The JSON text nests objects or arrays deeper than
830 C<$mb::JSON::MAX_DEPTH>.
831  
832 =item C<mb::JSON::encode: nesting too deep (max E<lt>NE<gt>)>
833  
834 The Perl data structure nests deeper than C<$mb::JSON::MAX_DEPTH>.
835  
836 =item C<mb::JSON::encode: circular reference detected>
837  
838 The Perl data structure contains a reference to one of its own
839 ancestors, which has no JSON representation.
840  
841 =item C<mb::JSON::encode: cannot encode Inf or NaN>
842  
843 A numeric value was C<Inf>, C<-Inf>, or C<NaN>. JSON has no syntax for
844 these; encode them as C<null> or as a string yourself if you need them.
845  
846 =back
847  
848 =head1 INCOMPATIBLE CHANGES
849  
850 These changes in 0.07 can alter the behaviour of code written against
851 0.06.
852  
853 =over 4
854  
855 =item *
856  
857 C<decode()>/C<parse()> reject an unrecognized backslash escape inside a
858 string with C<mb::JSON::decode: invalid escape sequence>. Earlier
859 releases passed the backslash through literally.
860  
861 =item *
862  
863 C<encode()> croaks on C<Inf>/C<NaN>, and on a string spelling one of
864 them exactly, rather than emitting C<"Inf"> or C<"NaN"> as a JSON
865 string. See L</LIMITATIONS>.
866  
867 =item *
868  
869 C<encode()> croaks on a circular reference instead of recursing until
870 the process runs out of stack.
871  
872 =item *
873  
874 C<decode()> and C<encode()> croak on nesting deeper than
875 C<$mb::JSON::MAX_DEPTH>, which defaults to 512. Earlier releases had no
876 limit.
877  
878 =item *
879  
880 C<decode()> skips a leading UTF-8 byte order mark instead of reporting
881 an unexpected token.
882  
883 =item *
884  
885 C<encode()> called with no argument at all encodes C<$_> instead of
886 returning C<null>. An explicit C<encode(undef)> still returns C<null>.
887  
888 =item *
889  
890 C<decode()>/C<parse()> croak on a number literal outside perl's floating
891 point range instead of silently converting it. Too large (C<1e400>)
892 used to return C<Inf>, which C<encode()> would then refuse to re-encode;
893 too small (C<1e-400>) used to return C<0>.
894  
895 =item *
896  
897 C<decode()>/C<parse()> accept only the four whitespace bytes RFC 8259
898 allows between tokens. Earlier releases used perl's C<\s>, which also
899 accepted form feed on every perl and vertical tab on perl 5.18 and
900 later -- so a document containing one of those decoded on some perls and
901 not on others.
902  
903 =item *
904  
905 C<encode()>/C<stringify()> apply C<$mb::JSON::MAX_DEPTH> to objects and
906 arrays only, and stop at the same count C<decode()> does. Earlier
907 releases counted leaf scalars as a level of their own and allowed one
908 container more than C<decode()> would read back.
909  
910 =back
911  
912 =head1 PERFORMANCE
913  
914 Up to 0.06 the decoder consumed its input by repeatedly deleting the
915 front of the buffer, which copies the remainder of the text on every
916 token and makes decoding quadratic in the input length. Since 0.07 the
917 scanner advances C<pos()> instead, so decoding is linear. On one
918 reference machine an 800 KB document took over 12 seconds to decode
919 with the old scanner and about 0.2 seconds with the new one. Documents
920 of a few kilobytes are too small for the difference to matter.
921  
922 C<parse()> and C<stringify()> hand their argument straight to
923 C<decode()> and C<encode()>. Up to 0.06 each copied it into a lexical
924 first, so calling the alias rather than the primary name duplicated the
925 whole document for nothing.
926  
927 C<encode()> is roughly 20% slower than before. That is the cost of
928 tracking the current path so that a circular reference can be reported
929 instead of recursing until the process runs out of stack.
930  
931 =head1 SEE ALSO
932  
933 L<JSON::PP>, L<JSON::XS>
934  
935 =head1 BUGS
936  
937 Please report bugs to C<ina.cpan@gmail.com>.
938  
939 =head1 AUTHOR
940  
941 INABA Hitoshi E<lt>ina.cpan@gmail.comE<gt>
942  
943 =head1 COPYRIGHT AND LICENSE
944  
945 Copyright (c) 2021, 2022, 2026 INABA Hitoshi E<lt>ina.cpan@gmail.comE<gt>
946  
947 This software is free software; you can redistribute it and/or modify
948 it under the same terms as Perl itself.
949 See L<perlartistic>.
950  
951 =cut
↑ Summary