JSON/backportPP.pm untested

filter: Statementstmt 0.0% 0 / 767 Branchbran 0.0% 0 / 442 Conditioncond 0.0% 0 / 238 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 107 Podpod 0.0% 0 / 68 totaltotal 0.0% 0 / 1622 CC 220 SCAR 48.7
CC
220
Cov
0%
string
420.0
PP_decode_json
342.0
number
342.0
CRAP 129.9
1 package # This is JSON::backportPP
2 JSON::PP;
3  
4 # JSON-2.0
5  
6 use 5.005;
7 use strict;
8 use base qw(Exporter);
9 use overload ();
10  
11 use Carp ();
12 use B ();
13 #use Devel::Peek;
14  
15 $JSON::PP::VERSION = '2.27008';
16  
17 @JSON::PP::EXPORT = qw(encode_json decode_json from_json to_json);
18  
19 # instead of hash-access, i tried index-access for speed.
20 # but this method is not faster than what i expected. so it will be changed.
21  
22 use constant P_ASCII => 0;
23 use constant P_LATIN1 => 1;
24 use constant P_UTF8 => 2;
25 use constant P_INDENT => 3;
26 use constant P_CANONICAL => 4;
27 use constant P_SPACE_BEFORE => 5;
28 use constant P_SPACE_AFTER => 6;
29 use constant P_ALLOW_NONREF => 7;
30 use constant P_SHRINK => 8;
31 use constant P_ALLOW_BLESSED => 9;
32 use constant P_CONVERT_BLESSED => 10;
33 use constant P_RELAXED => 11;
34  
35 use constant P_LOOSE => 12;
36 use constant P_ALLOW_BIGNUM => 13;
37 use constant P_ALLOW_BAREKEY => 14;
38 use constant P_ALLOW_SINGLEQUOTE => 15;
39 use constant P_ESCAPE_SLASH => 16;
40 use constant P_AS_NONBLESSED => 17;
41  
42 use constant P_ALLOW_UNKNOWN => 18;
43  
44 use constant OLD_PERL => $] < 5.008 ? 1 : 0;
45  
46 BEGIN {
47 my @xs_compati_bit_properties = qw(
48 latin1 ascii utf8 indent canonical space_before space_after allow_nonref shrink
49 allow_blessed convert_blessed relaxed allow_unknown
50 );
51 my @pp_bit_properties = qw(
52 allow_singlequote allow_bignum loose
53 allow_barekey escape_slash as_nonblessed
54 );
55  
56 # Perl version check, Unicode handling is enable?
57 # Helper module sets @JSON::PP::_properties.
58 if ($] < 5.008 ) {
59 my $helper;
60 $helper = $] >= 5.006 ? 'JSON::backportPP::Compat5006' : 'JSON::backportPP::Compat5005';
61 eval qq| require $helper |;
62 if ($@) { Carp::croak $@; }
63 }
64  
65 for my $name (@xs_compati_bit_properties, @pp_bit_properties) {
66 my $flag_name = 'P_' . uc($name);
67  
68 eval qq/
69 sub $name {
70 my \$enable = defined \$_[1] ? \$_[1] : 1;
71  
72 if (\$enable) {
73 \$_[0]->{PROPS}->[$flag_name] = 1;
74 }
75 else {
76 \$_[0]->{PROPS}->[$flag_name] = 0;
77 }
78  
79 \$_[0];
80 }
81  
82 sub get_$name {
83 \$_[0]->{PROPS}->[$flag_name] ? 1 : '';
84 }
85 /;
86 }
87  
88 }
89  
90  
91  
92 # Functions
93  
94 my %encode_allow_method
95 = map {($_ => 1)} qw/utf8 pretty allow_nonref latin1 self_encode escape_slash
96 allow_blessed convert_blessed indent indent_length allow_bignum
97 as_nonblessed
98 /;
99 my %decode_allow_method
100 = map {($_ => 1)} qw/utf8 allow_nonref loose allow_singlequote allow_bignum
101 allow_barekey max_size relaxed/;
102  
103  
104 my $JSON; # cache
105  
106 sub encode_json ($) { # encode
107 ($JSON ||= __PACKAGE__->new->utf8)->encode(@_);
108 }
109  
110  
111 sub decode_json { # decode
112 ($JSON ||= __PACKAGE__->new->utf8)->decode(@_);
113 }
114  
115 # Obsoleted
116  
117 sub to_json($) {
118 Carp::croak ("JSON::PP::to_json has been renamed to encode_json.");
119 }
120  
121  
122 sub from_json($) {
123 Carp::croak ("JSON::PP::from_json has been renamed to decode_json.");
124 }
125  
126  
127 # Methods
128  
129 sub new {
130 my $class = shift;
131 my $self = {
132 max_depth => 512,
133 max_size => 0,
134 indent => 0,
135 FLAGS => 0,
136 fallback => sub { encode_error('Invalid value. JSON can only reference.') },
137 indent_length => 3,
138 };
139  
140 bless $self, $class;
141 }
142  
143  
144 sub encode {
145 return $_[0]->PP_encode_json($_[1]);
146 }
147  
148  
149 sub decode {
150 return $_[0]->PP_decode_json($_[1], 0x00000000);
151 }
152  
153  
154 sub decode_prefix {
155 return $_[0]->PP_decode_json($_[1], 0x00000001);
156 }
157  
158  
159 # accessor
160  
161  
162 # pretty printing
163  
164 sub pretty {
165 my ($self, $v) = @_;
166 my $enable = defined $v ? $v : 1;
167  
168 if ($enable) { # indent_length(3) for JSON::XS compatibility
169 $self->indent(1)->indent_length(3)->space_before(1)->space_after(1);
170 }
171 else {
172 $self->indent(0)->space_before(0)->space_after(0);
173 }
174  
175 $self;
176 }
177  
178 # etc
179  
180 sub max_depth {
181 my $max = defined $_[1] ? $_[1] : 0x80000000;
182 $_[0]->{max_depth} = $max;
183 $_[0];
184 }
185  
186  
187 sub get_max_depth { $_[0]->{max_depth}; }
188  
189  
190 sub max_size {
191 my $max = defined $_[1] ? $_[1] : 0;
192 $_[0]->{max_size} = $max;
193 $_[0];
194 }
195  
196  
197 sub get_max_size { $_[0]->{max_size}; }
198  
199  
200 sub filter_json_object {
201 $_[0]->{cb_object} = defined $_[1] ? $_[1] : 0;
202 $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
203 $_[0];
204 }
205  
206 sub filter_json_single_key_object {
207 if (@_ > 1) {
208 $_[0]->{cb_sk_object}->{$_[1]} = $_[2];
209 }
210 $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
211 $_[0];
212 }
213  
214 sub indent_length {
215 if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) {
216 Carp::carp "The acceptable range of indent_length() is 0 to 15.";
217 }
218 else {
219 $_[0]->{indent_length} = $_[1];
220 }
221 $_[0];
222 }
223  
224 sub get_indent_length {
225 $_[0]->{indent_length};
226 }
227  
228 sub sort_by {
229 $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1;
230 $_[0];
231 }
232  
233 sub allow_bigint {
234 Carp::carp("allow_bigint() is obsoleted. use allow_bignum() insted.");
235 }
236  
237 ###############################
238  
239 ###
240 ### Perl => JSON
241 ###
242  
243  
244 { # Convert
245  
246 my $max_depth;
247 my $indent;
248 my $ascii;
249 my $latin1;
250 my $utf8;
251 my $space_before;
252 my $space_after;
253 my $canonical;
254 my $allow_blessed;
255 my $convert_blessed;
256  
257 my $indent_length;
258 my $escape_slash;
259 my $bignum;
260 my $as_nonblessed;
261  
262 my $depth;
263 my $indent_count;
264 my $keysort;
265  
266  
267 sub PP_encode_json {
268 my $self = shift;
269 my $obj = shift;
270  
271 $indent_count = 0;
272 $depth = 0;
273  
274 my $idx = $self->{PROPS};
275  
276 ($ascii, $latin1, $utf8, $indent, $canonical, $space_before, $space_after, $allow_blessed,
277 $convert_blessed, $escape_slash, $bignum, $as_nonblessed)
278 = @{$idx}[P_ASCII .. P_SPACE_AFTER, P_ALLOW_BLESSED, P_CONVERT_BLESSED,
279 P_ESCAPE_SLASH, P_ALLOW_BIGNUM, P_AS_NONBLESSED];
280  
281 ($max_depth, $indent_length) = @{$self}{qw/max_depth indent_length/};
282  
283 $keysort = $canonical ? sub { $a cmp $b } : undef;
284  
285 if ($self->{sort_by}) {
286 $keysort = ref($self->{sort_by}) eq 'CODE' ? $self->{sort_by}
287 : $self->{sort_by} =~ /\D+/ ? $self->{sort_by}
288 : sub { $a cmp $b };
289 }
290  
291 encode_error("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)")
292 if(!ref $obj and !$idx->[ P_ALLOW_NONREF ]);
293  
294 my $str = $self->object_to_json($obj);
295  
296 $str .= "\n" if ( $indent ); # JSON::XS 2.26 compatible
297  
298 unless ($ascii or $latin1 or $utf8) {
299 utf8::upgrade($str);
300 }
301  
302 if ($idx->[ P_SHRINK ]) {
303 utf8::downgrade($str, 1);
304 }
305  
306 return $str;
307 }
308  
309  
310 sub object_to_json {
311 my ($self, $obj) = @_;
312 my $type = ref($obj);
313  
314 if($type eq 'HASH'){
315 return $self->hash_to_json($obj);
316 }
317 elsif($type eq 'ARRAY'){
318 return $self->array_to_json($obj);
319 }
320 elsif ($type) { # blessed object?
321 if (blessed($obj)) {
322  
323 return $self->value_to_json($obj) if ( $obj->isa('JSON::PP::Boolean') );
324  
325 if ( $convert_blessed and $obj->can('TO_JSON') ) {
326 my $result = $obj->TO_JSON();
327 if ( defined $result and overload::Overloaded( $obj ) ) {
328 if ( overload::StrVal( $obj ) eq $result ) {
329 encode_error( sprintf(
330 "%s::TO_JSON method returned same object as was passed instead of a new one",
331 ref $obj
332 ) );
333 }
334 }
335  
336 return $self->object_to_json( $result );
337 }
338  
339 return "$obj" if ( $bignum and _is_bignum($obj) );
340 return $self->blessed_to_json($obj) if ($allow_blessed and $as_nonblessed); # will be removed.
341  
342 encode_error( sprintf("encountered object '%s', but neither allow_blessed "
343 . "nor convert_blessed settings are enabled", $obj)
344 ) unless ($allow_blessed);
345  
346 return 'null';
347 }
348 else {
349 return $self->value_to_json($obj);
350 }
351 }
352 else{
353 return $self->value_to_json($obj);
354 }
355 }
356  
357  
358 sub hash_to_json {
359 my ($self, $obj) = @_;
360 my @res;
361  
362 encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
363 if (++$depth > $max_depth);
364  
365 my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
366 my $del = ($space_before ? ' ' : '') . ':' . ($space_after ? ' ' : '');
367  
368 for my $k ( _sort( $obj ) ) {
369 if ( OLD_PERL ) { utf8::decode($k) } # key for Perl 5.6 / be optimized
370 push @res, string_to_json( $self, $k )
371 . $del
372 . ( $self->object_to_json( $obj->{$k} ) || $self->value_to_json( $obj->{$k} ) );
373 }
374  
375 --$depth;
376 $self->_down_indent() if ($indent);
377  
378 return '{' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . '}';
379 }
380  
381  
382 sub array_to_json {
383 my ($self, $obj) = @_;
384 my @res;
385  
386 encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
387 if (++$depth > $max_depth);
388  
389 my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
390  
391 for my $v (@$obj){
392 push @res, $self->object_to_json($v) || $self->value_to_json($v);
393 }
394  
395 --$depth;
396 $self->_down_indent() if ($indent);
397  
398 return '[' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . ']';
399 }
400  
401  
402 sub value_to_json {
403 my ($self, $value) = @_;
404  
405 return 'null' if(!defined $value);
406  
407 my $b_obj = B::svref_2object(\$value); # for round trip problem
408 my $flags = $b_obj->FLAGS;
409  
410 return $value # as is
411 if $flags & ( B::SVp_IOK | B::SVp_NOK ) and !( $flags & B::SVp_POK ); # SvTYPE is IV or NV?
412  
413 my $type = ref($value);
414  
415 if(!$type){
416 return string_to_json($self, $value);
417 }
418 elsif( blessed($value) and $value->isa('JSON::PP::Boolean') ){
419 return $$value == 1 ? 'true' : 'false';
420 }
421 elsif ($type) {
422 if ((overload::StrVal($value) =~ /=(\w+)/)[0]) {
423 return $self->value_to_json("$value");
424 }
425  
426 if ($type eq 'SCALAR' and defined $$value) {
427 return $$value eq '1' ? 'true'
428 : $$value eq '0' ? 'false'
429 : $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ? 'null'
430 : encode_error("cannot encode reference to scalar");
431 }
432  
433 if ( $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ) {
434 return 'null';
435 }
436 else {
437 if ( $type eq 'SCALAR' or $type eq 'REF' ) {
438 encode_error("cannot encode reference to scalar");
439 }
440 else {
441 encode_error("encountered $value, but JSON can only represent references to arrays or hashes");
442 }
443 }
444  
445 }
446 else {
447 return $self->{fallback}->($value)
448 if ($self->{fallback} and ref($self->{fallback}) eq 'CODE');
449 return 'null';
450 }
451  
452 }
453  
454  
455 my %esc = (
456 "\n" => '\n',
457 "\r" => '\r',
458 "\t" => '\t',
459 "\f" => '\f',
460 "\b" => '\b',
461 "\"" => '\"',
462 "\\" => '\\\\',
463 "\'" => '\\\'',
464 );
465  
466  
467 sub string_to_json {
468 my ($self, $arg) = @_;
469  
470 $arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
471 $arg =~ s/\//\\\//g if ($escape_slash);
472 $arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg;
473  
474 if ($ascii) {
475 $arg = JSON_PP_encode_ascii($arg);
476 }
477  
478 if ($latin1) {
479 $arg = JSON_PP_encode_latin1($arg);
480 }
481  
482 if ($utf8) {
483 utf8::encode($arg);
484 }
485  
486 return '"' . $arg . '"';
487 }
488  
489  
490 sub blessed_to_json {
491 my $reftype = reftype($_[1]) || '';
492 if ($reftype eq 'HASH') {
493 return $_[0]->hash_to_json($_[1]);
494 }
495 elsif ($reftype eq 'ARRAY') {
496 return $_[0]->array_to_json($_[1]);
497 }
498 else {
499 return 'null';
500 }
501 }
502  
503  
504 sub encode_error {
505 my $error = shift;
506 Carp::croak "$error";
507 }
508  
509  
510 sub _sort {
511 defined $keysort ? (sort $keysort (keys %{$_[0]})) : keys %{$_[0]};
512 }
513  
514  
515 sub _up_indent {
516 my $self = shift;
517 my $space = ' ' x $indent_length;
518  
519 my ($pre,$post) = ('','');
520  
521 $post = "\n" . $space x $indent_count;
522  
523 $indent_count++;
524  
525 $pre = "\n" . $space x $indent_count;
526  
527 return ($pre,$post);
528 }
529  
530  
531 sub _down_indent { $indent_count--; }
532  
533  
534 sub PP_encode_box {
535 {
536 depth => $depth,
537 indent_count => $indent_count,
538 };
539 }
540  
541 } # Convert
542  
543  
544 sub _encode_ascii {
545 join('',
546 map {
547 $_ <= 127 ?
548 chr($_) :
549 $_ <= 65535 ?
550 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
551 } unpack('U*', $_[0])
552 );
553 }
554  
555  
556 sub _encode_latin1 {
557 join('',
558 map {
559 $_ <= 255 ?
560 chr($_) :
561 $_ <= 65535 ?
562 sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
563 } unpack('U*', $_[0])
564 );
565 }
566  
567  
568 sub _encode_surrogates { # from perlunicode
569 my $uni = $_[0] - 0x10000;
570 return ($uni / 0x400 + 0xD800, $uni % 0x400 + 0xDC00);
571 }
572  
573  
574 sub _is_bignum {
575 $_[0]->isa('Math::BigInt') or $_[0]->isa('Math::BigFloat');
576 }
577  
578  
579  
580 #
581 # JSON => Perl
582 #
583  
584 my $max_intsize;
585  
586 BEGIN {
587 my $checkint = 1111;
588 for my $d (5..64) {
589 $checkint .= 1;
590 my $int = eval qq| $checkint |;
591 if ($int =~ /[eE]/) {
592 $max_intsize = $d - 1;
593 last;
594 }
595 }
596 }
597  
598 { # PARSE
599  
600 my %escapes = ( # by Jeremy Muhlich <jmuhlich [at] bitflood.org>
601 b => "\x8",
602 t => "\x9",
603 n => "\xA",
604 f => "\xC",
605 r => "\xD",
606 '\\' => '\\',
607 '"' => '"',
608 '/' => '/',
609 );
610  
611 my $text; # json data
612 my $at; # offset
613 my $ch; # 1chracter
614 my $len; # text length (changed according to UTF8 or NON UTF8)
615 # INTERNAL
616 my $depth; # nest counter
617 my $encoding; # json text encoding
618 my $is_valid_utf8; # temp variable
619 my $utf8_len; # utf8 byte length
620 # FLAGS
621 my $utf8; # must be utf8
622 my $max_depth; # max nest nubmer of objects and arrays
623 my $max_size;
624 my $relaxed;
625 my $cb_object;
626 my $cb_sk_object;
627  
628 my $F_HOOK;
629  
630 my $allow_bigint; # using Math::BigInt
631 my $singlequote; # loosely quoting
632 my $loose; #
633 my $allow_barekey; # bareKey
634  
635 # $opt flag
636 # 0x00000001 .... decode_prefix
637 # 0x10000000 .... incr_parse
638  
639 sub PP_decode_json {
640 my ($self, $opt); # $opt is an effective flag during this decode_json.
641  
642 ($self, $text, $opt) = @_;
643  
644 ($at, $ch, $depth) = (0, '', 0);
645  
646 if ( !defined $text or ref $text ) {
647 decode_error("malformed JSON string, neither array, object, number, string or atom");
648 }
649  
650 my $idx = $self->{PROPS};
651  
652 ($utf8, $relaxed, $loose, $allow_bigint, $allow_barekey, $singlequote)
653 = @{$idx}[P_UTF8, P_RELAXED, P_LOOSE .. P_ALLOW_SINGLEQUOTE];
654  
655 if ( $utf8 ) {
656 utf8::downgrade( $text, 1 ) or Carp::croak("Wide character in subroutine entry");
657 }
658 else {
659 utf8::upgrade( $text );
660 }
661  
662 $len = length $text;
663  
664 ($max_depth, $max_size, $cb_object, $cb_sk_object, $F_HOOK)
665 = @{$self}{qw/max_depth max_size cb_object cb_sk_object F_HOOK/};
666  
667 if ($max_size > 1) {
668 use bytes;
669 my $bytes = length $text;
670 decode_error(
671 sprintf("attempted decode of JSON text of %s bytes size, but max_size is set to %s"
672 , $bytes, $max_size), 1
673 ) if ($bytes > $max_size);
674 }
675  
676 # Currently no effect
677 # should use regexp
678 my @octets = unpack('C4', $text);
679 $encoding = ( $octets[0] and $octets[1]) ? 'UTF-8'
680 : (!$octets[0] and $octets[1]) ? 'UTF-16BE'
681 : (!$octets[0] and !$octets[1]) ? 'UTF-32BE'
682 : ( $octets[2] ) ? 'UTF-16LE'
683 : (!$octets[2] ) ? 'UTF-32LE'
684 : 'unknown';
685  
686 white(); # remove head white space
687  
688 my $valid_start = defined $ch; # Is there a first character for JSON structure?
689  
690 my $result = value();
691  
692 return undef if ( !$result && ( $opt & 0x10000000 ) ); # for incr_parse
693  
694 decode_error("malformed JSON string, neither array, object, number, string or atom") unless $valid_start;
695  
696 if ( !$idx->[ P_ALLOW_NONREF ] and !ref $result ) {
697 decode_error(
698 'JSON text must be an object or array (but found number, string, true, false or null,'
699 . ' use allow_nonref to allow this)', 1);
700 }
701  
702 Carp::croak('something wrong.') if $len < $at; # we won't arrive here.
703  
704 my $consumed = defined $ch ? $at - 1 : $at; # consumed JSON text length
705  
706 white(); # remove tail white space
707  
708 if ( $ch ) {
709 return ( $result, $consumed ) if ($opt & 0x00000001); # all right if decode_prefix
710 decode_error("garbage after JSON object");
711 }
712  
713 ( $opt & 0x00000001 ) ? ( $result, $consumed ) : $result;
714 }
715  
716  
717 sub next_chr {
718 return $ch = undef if($at >= $len);
719 $ch = substr($text, $at++, 1);
720 }
721  
722  
723 sub value {
724 white();
725 return if(!defined $ch);
726 return object() if($ch eq '{');
727 return array() if($ch eq '[');
728 return string() if($ch eq '"' or ($singlequote and $ch eq "'"));
729 return number() if($ch =~ /[0-9]/ or $ch eq '-');
730 return word();
731 }
732  
733 sub string {
734 my ($i, $s, $t, $u);
735 my $utf16;
736 my $is_utf8;
737  
738 ($is_valid_utf8, $utf8_len) = ('', 0);
739  
740 $s = ''; # basically UTF8 flag on
741  
742 if($ch eq '"' or ($singlequote and $ch eq "'")){
743 my $boundChar = $ch;
744  
745 OUTER: while( defined(next_chr()) ){
746  
747 if($ch eq $boundChar){
748 next_chr();
749  
750 if ($utf16) {
751 decode_error("missing low surrogate character in surrogate pair");
752 }
753  
754 utf8::decode($s) if($is_utf8);
755  
756 return $s;
757 }
758 elsif($ch eq '\\'){
759 next_chr();
760 if(exists $escapes{$ch}){
761 $s .= $escapes{$ch};
762 }
763 elsif($ch eq 'u'){ # UNICODE handling
764 my $u = '';
765  
766 for(1..4){
767 $ch = next_chr();
768 last OUTER if($ch !~ /[0-9a-fA-F]/);
769 $u .= $ch;
770 }
771  
772 # U+D800 - U+DBFF
773 if ($u =~ /^[dD][89abAB][0-9a-fA-F]{2}/) { # UTF-16 high surrogate?
774 $utf16 = $u;
775 }
776 # U+DC00 - U+DFFF
777 elsif ($u =~ /^[dD][c-fC-F][0-9a-fA-F]{2}/) { # UTF-16 low surrogate?
778 unless (defined $utf16) {
779 decode_error("missing high surrogate character in surrogate pair");
780 }
781 $is_utf8 = 1;
782 $s .= JSON_PP_decode_surrogates($utf16, $u) || next;
783 $utf16 = undef;
784 }
785 else {
786 if (defined $utf16) {
787 decode_error("surrogate pair expected");
788 }
789  
790 if ( ( my $hex = hex( $u ) ) > 127 ) {
791 $is_utf8 = 1;
792 $s .= JSON_PP_decode_unicode($u) || next;
793 }
794 else {
795 $s .= chr $hex;
796 }
797 }
798  
799 }
800 else{
801 unless ($loose) {
802 $at -= 2;
803 decode_error('illegal backslash escape sequence in string');
804 }
805 $s .= $ch;
806 }
807 }
808 else{
809  
810 if ( ord $ch > 127 ) {
811 if ( $utf8 ) {
812 unless( $ch = is_valid_utf8($ch) ) {
813 $at -= 1;
814 decode_error("malformed UTF-8 character in JSON string");
815 }
816 else {
817 $at += $utf8_len - 1;
818 }
819 }
820 else {
821 utf8::encode( $ch );
822 }
823  
824 $is_utf8 = 1;
825 }
826  
827 if (!$loose) {
828 if ($ch =~ /[\x00-\x1f\x22\x5c]/) { # '/' ok
829 $at--;
830 decode_error('invalid character encountered while parsing JSON string');
831 }
832 }
833  
834 $s .= $ch;
835 }
836 }
837 }
838  
839 decode_error("unexpected end of string while parsing JSON string");
840 }
841  
842  
843 sub white {
844 while( defined $ch ){
845 if($ch le ' '){
846 next_chr();
847 }
848 elsif($ch eq '/'){
849 next_chr();
850 if(defined $ch and $ch eq '/'){
851 1 while(defined(next_chr()) and $ch ne "\n" and $ch ne "\r");
852 }
853 elsif(defined $ch and $ch eq '*'){
854 next_chr();
855 while(1){
856 if(defined $ch){
857 if($ch eq '*'){
858 if(defined(next_chr()) and $ch eq '/'){
859 next_chr();
860 last;
861 }
862 }
863 else{
864 next_chr();
865 }
866 }
867 else{
868 decode_error("Unterminated comment");
869 }
870 }
871 next;
872 }
873 else{
874 $at--;
875 decode_error("malformed JSON string, neither array, object, number, string or atom");
876 }
877 }
878 else{
879 if ($relaxed and $ch eq '#') { # correctly?
880 pos($text) = $at;
881 $text =~ /\G([^\n]*(?:\r\n|\r|\n|$))/g;
882 $at = pos($text);
883 next_chr;
884 next;
885 }
886  
887 last;
888 }
889 }
890 }
891  
892  
893 sub array {
894 my $a = [];
895  
896 decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
897 if (++$depth > $max_depth);
898  
899 next_chr();
900 white();
901  
902 if(defined $ch and $ch eq ']'){
903 --$depth;
904 next_chr();
905 return $a;
906 }
907 else {
908 while(defined($ch)){
909 push @$a, value();
910  
911 white();
912  
913 if (!defined $ch) {
914 last;
915 }
916  
917 if($ch eq ']'){
918 --$depth;
919 next_chr();
920 return $a;
921 }
922  
923 if($ch ne ','){
924 last;
925 }
926  
927 next_chr();
928 white();
929  
930 if ($relaxed and $ch eq ']') {
931 --$depth;
932 next_chr();
933 return $a;
934 }
935  
936 }
937 }
938  
939 decode_error(", or ] expected while parsing array");
940 }
941  
942  
943 sub object {
944 my $o = {};
945 my $k;
946  
947 decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
948 if (++$depth > $max_depth);
949 next_chr();
950 white();
951  
952 if(defined $ch and $ch eq '}'){
953 --$depth;
954 next_chr();
955 if ($F_HOOK) {
956 return _json_object_hook($o);
957 }
958 return $o;
959 }
960 else {
961 while (defined $ch) {
962 $k = ($allow_barekey and $ch ne '"' and $ch ne "'") ? bareKey() : string();
963 white();
964  
965 if(!defined $ch or $ch ne ':'){
966 $at--;
967 decode_error("':' expected");
968 }
969  
970 next_chr();
971 $o->{$k} = value();
972 white();
973  
974 last if (!defined $ch);
975  
976 if($ch eq '}'){
977 --$depth;
978 next_chr();
979 if ($F_HOOK) {
980 return _json_object_hook($o);
981 }
982 return $o;
983 }
984  
985 if($ch ne ','){
986 last;
987 }
988  
989 next_chr();
990 white();
991  
992 if ($relaxed and $ch eq '}') {
993 --$depth;
994 next_chr();
995 if ($F_HOOK) {
996 return _json_object_hook($o);
997 }
998 return $o;
999 }
1000  
1001 }
1002  
1003 }
1004  
1005 $at--;
1006 decode_error(", or } expected while parsing object/hash");
1007 }
1008  
1009  
1010 sub bareKey { # doesn't strictly follow Standard ECMA-262 3rd Edition
1011 my $key;
1012 while($ch =~ /[^\x00-\x23\x25-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/){
1013 $key .= $ch;
1014 next_chr();
1015 }
1016 return $key;
1017 }
1018  
1019  
1020 sub word {
1021 my $word = substr($text,$at-1,4);
1022  
1023 if($word eq 'true'){
1024 $at += 3;
1025 next_chr;
1026 return $JSON::PP::true;
1027 }
1028 elsif($word eq 'null'){
1029 $at += 3;
1030 next_chr;
1031 return undef;
1032 }
1033 elsif($word eq 'fals'){
1034 $at += 3;
1035 if(substr($text,$at,1) eq 'e'){
1036 $at++;
1037 next_chr;
1038 return $JSON::PP::false;
1039 }
1040 }
1041  
1042 $at--; # for decode_error report
1043  
1044 decode_error("'null' expected") if ($word =~ /^n/);
1045 decode_error("'true' expected") if ($word =~ /^t/);
1046 decode_error("'false' expected") if ($word =~ /^f/);
1047 decode_error("malformed JSON string, neither array, object, number, string or atom");
1048 }
1049  
1050  
1051 sub number {
1052 my $n = '';
1053 my $v;
1054  
1055 # According to RFC4627, hex or oct digts are invalid.
1056 if($ch eq '0'){
1057 my $peek = substr($text,$at,1);
1058 my $hex = $peek =~ /[xX]/; # 0 or 1
1059  
1060 if($hex){
1061 decode_error("malformed number (leading zero must not be followed by another digit)");
1062 ($n) = ( substr($text, $at+1) =~ /^([0-9a-fA-F]+)/);
1063 }
1064 else{ # oct
1065 ($n) = ( substr($text, $at) =~ /^([0-7]+)/);
1066 if (defined $n and length $n > 1) {
1067 decode_error("malformed number (leading zero must not be followed by another digit)");
1068 }
1069 }
1070  
1071 if(defined $n and length($n)){
1072 if (!$hex and length($n) == 1) {
1073 decode_error("malformed number (leading zero must not be followed by another digit)");
1074 }
1075 $at += length($n) + $hex;
1076 next_chr;
1077 return $hex ? hex($n) : oct($n);
1078 }
1079 }
1080  
1081 if($ch eq '-'){
1082 $n = '-';
1083 next_chr;
1084 if (!defined $ch or $ch !~ /\d/) {
1085 decode_error("malformed number (no digits after initial minus)");
1086 }
1087 }
1088  
1089 while(defined $ch and $ch =~ /\d/){
1090 $n .= $ch;
1091 next_chr;
1092 }
1093  
1094 if(defined $ch and $ch eq '.'){
1095 $n .= '.';
1096  
1097 next_chr;
1098 if (!defined $ch or $ch !~ /\d/) {
1099 decode_error("malformed number (no digits after decimal point)");
1100 }
1101 else {
1102 $n .= $ch;
1103 }
1104  
1105 while(defined(next_chr) and $ch =~ /\d/){
1106 $n .= $ch;
1107 }
1108 }
1109  
1110 if(defined $ch and ($ch eq 'e' or $ch eq 'E')){
1111 $n .= $ch;
1112 next_chr;
1113  
1114 if(defined($ch) and ($ch eq '+' or $ch eq '-')){
1115 $n .= $ch;
1116 next_chr;
1117 if (!defined $ch or $ch =~ /\D/) {
1118 decode_error("malformed number (no digits after exp sign)");
1119 }
1120 $n .= $ch;
1121 }
1122 elsif(defined($ch) and $ch =~ /\d/){
1123 $n .= $ch;
1124 }
1125 else {
1126 decode_error("malformed number (no digits after exp sign)");
1127 }
1128  
1129 while(defined(next_chr) and $ch =~ /\d/){
1130 $n .= $ch;
1131 }
1132  
1133 }
1134  
1135 $v .= $n;
1136  
1137 if ($v !~ /[.eE]/ and length $v > $max_intsize) {
1138 if ($allow_bigint) { # from Adam Sussman
1139 require Math::BigInt;
1140 return Math::BigInt->new($v);
1141 }
1142 else {
1143 return "$v";
1144 }
1145 }
1146 elsif ($allow_bigint) {
1147 require Math::BigFloat;
1148 return Math::BigFloat->new($v);
1149 }
1150  
1151 return 0+$v;
1152 }
1153  
1154  
1155 sub is_valid_utf8 {
1156  
1157 $utf8_len = $_[0] =~ /[\x00-\x7F]/ ? 1
1158 : $_[0] =~ /[\xC2-\xDF]/ ? 2
1159 : $_[0] =~ /[\xE0-\xEF]/ ? 3
1160 : $_[0] =~ /[\xF0-\xF4]/ ? 4
1161 : 0
1162 ;
1163  
1164 return unless $utf8_len;
1165  
1166 my $is_valid_utf8 = substr($text, $at - 1, $utf8_len);
1167  
1168 return ( $is_valid_utf8 =~ /^(?:
1169 [\x00-\x7F]
1170 |[\xC2-\xDF][\x80-\xBF]
1171 |[\xE0][\xA0-\xBF][\x80-\xBF]
1172 |[\xE1-\xEC][\x80-\xBF][\x80-\xBF]
1173 |[\xED][\x80-\x9F][\x80-\xBF]
1174 |[\xEE-\xEF][\x80-\xBF][\x80-\xBF]
1175 |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF]
1176 |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]
1177 |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF]
1178 )$/x ) ? $is_valid_utf8 : '';
1179 }
1180  
1181  
1182 sub decode_error {
1183 my $error = shift;
1184 my $no_rep = shift;
1185 my $str = defined $text ? substr($text, $at) : '';
1186 my $mess = '';
1187 my $type = $] >= 5.008 ? 'U*'
1188 : $] < 5.006 ? 'C*'
1189 : utf8::is_utf8( $str ) ? 'U*' # 5.6
1190 : 'C*'
1191 ;
1192  
1193 for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ?
1194 $mess .= $c == 0x07 ? '\a'
1195 : $c == 0x09 ? '\t'
1196 : $c == 0x0a ? '\n'
1197 : $c == 0x0d ? '\r'
1198 : $c == 0x0c ? '\f'
1199 : $c < 0x20 ? sprintf('\x{%x}', $c)
1200 : $c == 0x5c ? '\\\\'
1201 : $c < 0x80 ? chr($c)
1202 : sprintf('\x{%x}', $c)
1203 ;
1204 if ( length $mess >= 20 ) {
1205 $mess .= '...';
1206 last;
1207 }
1208 }
1209  
1210 unless ( length $mess ) {
1211 $mess = '(end of string)';
1212 }
1213  
1214 Carp::croak (
1215 $no_rep ? "$error" : "$error, at character offset $at (before \"$mess\")"
1216 );
1217  
1218 }
1219  
1220  
1221 sub _json_object_hook {
1222 my $o = $_[0];
1223 my @ks = keys %{$o};
1224  
1225 if ( $cb_sk_object and @ks == 1 and exists $cb_sk_object->{ $ks[0] } and ref $cb_sk_object->{ $ks[0] } ) {
1226 my @val = $cb_sk_object->{ $ks[0] }->( $o->{$ks[0]} );
1227 if (@val == 1) {
1228 return $val[0];
1229 }
1230 }
1231  
1232 my @val = $cb_object->($o) if ($cb_object);
1233 if (@val == 0 or @val > 1) {
1234 return $o;
1235 }
1236 else {
1237 return $val[0];
1238 }
1239 }
1240  
1241  
1242 sub PP_decode_box {
1243 {
1244 text => $text,
1245 at => $at,
1246 ch => $ch,
1247 len => $len,
1248 depth => $depth,
1249 encoding => $encoding,
1250 is_valid_utf8 => $is_valid_utf8,
1251 };
1252 }
1253  
1254 } # PARSE
1255  
1256  
1257 sub _decode_surrogates { # from perlunicode
1258 my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00);
1259 my $un = pack('U*', $uni);
1260 utf8::encode( $un );
1261 return $un;
1262 }
1263  
1264  
1265 sub _decode_unicode {
1266 my $un = pack('U', hex shift);
1267 utf8::encode( $un );
1268 return $un;
1269 }
1270  
1271  
1272 #
1273 # Setup for various Perl versions (the code from JSON::PP58)
1274 #
1275  
1276 BEGIN {
1277  
1278 unless ( defined &utf8::is_utf8 ) {
1279 require Encode;
1280 *utf8::is_utf8 = *Encode::is_utf8;
1281 }
1282  
1283 if ( $] >= 5.008 ) {
1284 *JSON::PP::JSON_PP_encode_ascii = \&_encode_ascii;
1285 *JSON::PP::JSON_PP_encode_latin1 = \&_encode_latin1;
1286 *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates;
1287 *JSON::PP::JSON_PP_decode_unicode = \&_decode_unicode;
1288 }
1289  
1290 if ($] >= 5.008 and $] < 5.008003) { # join() in 5.8.0 - 5.8.2 is broken.
1291 package JSON::PP;
1292 require subs;
1293 subs->import('join');
1294 eval q|
1295 sub join {
1296 return '' if (@_ < 2);
1297 my $j = shift;
1298 my $str = shift;
1299 for (@_) { $str .= $j . $_; }
1300 return $str;
1301 }
1302 |;
1303 }
1304  
1305 sub JSON::PP::incr_parse {
1306 local $Carp::CarpLevel = 1;
1307 ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_parse( @_ );
1308 }
1309  
1310 sub JSON::PP::incr_skip {
1311 ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_skip;
1312 }
1313  
1314 sub JSON::PP::incr_reset {
1315 ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_reset;
1316 }
1317  
1318 eval q{
1319 sub JSON::PP::incr_text : lvalue {
1320 $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new;
1321  
1322 if ( $_[0]->{_incr_parser}->{incr_parsing} ) {
1323 Carp::croak("incr_text can not be called when the incremental parser already started parsing");
1324 }
1325 $_[0]->{_incr_parser}->{incr_text};
1326 }
1327 } if ( $] >= 5.006 );
1328  
1329 } # Setup for various Perl versions (the code from JSON::PP58)
1330  
1331 ###############################
1332 # Utilities
1333 #
1334  
1335 BEGIN {
1336 eval 'require Scalar::Util';
1337 unless($@){
1338 *JSON::PP::blessed = \&Scalar::Util::blessed;
1339 *JSON::PP::reftype = \&Scalar::Util::reftype;
1340 }
1341 else{ # This code is from Sclar::Util.
1342 # warn $@;
1343 eval 'sub UNIVERSAL::a_sub_not_likely_to_be_here { ref($_[0]) }';
1344 *JSON::PP::blessed = sub {
1345 local($@, $SIG{__DIE__}, $SIG{__WARN__});
1346 ref($_[0]) ? eval { $_[0]->a_sub_not_likely_to_be_here } : undef;
1347 };
1348 my %tmap = qw(
1349 B::NULL SCALAR
1350 B::HV HASH
1351 B::AV ARRAY
1352 B::CV CODE
1353 B::IO IO
1354 B::GV GLOB
1355 B::REGEXP REGEXP
1356 );
1357 *JSON::PP::reftype = sub {
1358 my $r = shift;
1359  
1360 return undef unless length(ref($r));
1361  
1362 my $t = ref(B::svref_2object($r));
1363  
1364 return
1365 exists $tmap{$t} ? $tmap{$t}
1366 : length(ref($$r)) ? 'REF'
1367 : 'SCALAR';
1368 };
1369 }
1370 }
1371  
1372  
1373 # shamely copied and modified from JSON::XS code.
1374  
1375 $JSON::PP::true = do { bless \(my $dummy = 1), "JSON::backportPP::Boolean" };
1376 $JSON::PP::false = do { bless \(my $dummy = 0), "JSON::backportPP::Boolean" };
1377  
1378 sub is_bool { defined $_[0] and UNIVERSAL::isa($_[0], "JSON::PP::Boolean"); }
1379  
1380 sub true { $JSON::PP::true }
1381 sub false { $JSON::PP::false }
1382 sub null { undef; }
1383  
1384 ###############################
1385  
1386 package JSON::backportPP::Boolean;
1387  
1388 @JSON::backportPP::Boolean::ISA = ('JSON::PP::Boolean');
1389 use overload (
1390 "0+" => sub { ${$_[0]} },
1391 "++" => sub { $_[0] = ${$_[0]} + 1 },
1392 "--" => sub { $_[0] = ${$_[0]} - 1 },
1393 fallback => 1,
1394 );
1395  
1396  
1397 ###############################
1398  
1399 package JSON::PP::IncrParser;
1400  
1401 use strict;
1402  
1403 use constant INCR_M_WS => 0; # initial whitespace skipping
1404 use constant INCR_M_STR => 1; # inside string
1405 use constant INCR_M_BS => 2; # inside backslash
1406 use constant INCR_M_JSON => 3; # outside anything, count nesting
1407 use constant INCR_M_C0 => 4;
1408 use constant INCR_M_C1 => 5;
1409  
1410 $JSON::PP::IncrParser::VERSION = '1.01';
1411  
1412 my $unpack_format = $] < 5.006 ? 'C*' : 'U*';
1413  
1414 sub new {
1415 my ( $class ) = @_;
1416  
1417 bless {
1418 incr_nest => 0,
1419 incr_text => undef,
1420 incr_parsing => 0,
1421 incr_p => 0,
1422 }, $class;
1423 }
1424  
1425  
1426 sub incr_parse {
1427 my ( $self, $coder, $text ) = @_;
1428  
1429 $self->{incr_text} = '' unless ( defined $self->{incr_text} );
1430  
1431 if ( defined $text ) {
1432 if ( utf8::is_utf8( $text ) and !utf8::is_utf8( $self->{incr_text} ) ) {
1433 utf8::upgrade( $self->{incr_text} ) ;
1434 utf8::decode( $self->{incr_text} ) ;
1435 }
1436 $self->{incr_text} .= $text;
1437 }
1438  
1439  
1440 my $max_size = $coder->get_max_size;
1441  
1442 if ( defined wantarray ) {
1443  
1444 $self->{incr_mode} = INCR_M_WS;
1445  
1446 if ( wantarray ) {
1447 my @ret;
1448  
1449 $self->{incr_parsing} = 1;
1450  
1451 do {
1452 push @ret, $self->_incr_parse( $coder, $self->{incr_text} );
1453  
1454 unless ( !$self->{incr_nest} and $self->{incr_mode} == INCR_M_JSON ) {
1455 $self->{incr_mode} = INCR_M_WS;
1456 }
1457  
1458 } until ( !$self->{incr_text} );
1459  
1460 $self->{incr_parsing} = 0;
1461  
1462 return @ret;
1463 }
1464 else { # in scalar context
1465 $self->{incr_parsing} = 1;
1466 my $obj = $self->_incr_parse( $coder, $self->{incr_text} );
1467 $self->{incr_parsing} = 0 if defined $obj; # pointed by Martin J. Evans
1468 return $obj ? $obj : undef; # $obj is an empty string, parsing was completed.
1469 }
1470  
1471 }
1472  
1473 }
1474  
1475  
1476 sub _incr_parse {
1477 my ( $self, $coder, $text, $skip ) = @_;
1478 my $p = $self->{incr_p};
1479 my $restore = $p;
1480  
1481 my @obj;
1482 my $len = length $text;
1483  
1484 if ( $self->{incr_mode} == INCR_M_WS ) {
1485 while ( $len > $p ) {
1486 my $s = substr( $text, $p, 1 );
1487 $p++ and next if ( 0x20 >= unpack($unpack_format, $s) );
1488 $self->{incr_mode} = INCR_M_JSON;
1489 last;
1490 }
1491 }
1492  
1493 while ( $len > $p ) {
1494 my $s = substr( $text, $p++, 1 );
1495  
1496 if ( $s eq '"' ) {
1497 if ( $self->{incr_mode} != INCR_M_STR ) {
1498 $self->{incr_mode} = INCR_M_STR;
1499 }
1500 else {
1501 $self->{incr_mode} = INCR_M_JSON;
1502 unless ( $self->{incr_nest} ) {
1503 last;
1504 }
1505 }
1506 }
1507  
1508 if ( $self->{incr_mode} == INCR_M_JSON ) {
1509  
1510 if ( $s eq '[' or $s eq '{' ) {
1511 if ( ++$self->{incr_nest} > $coder->get_max_depth ) {
1512 Carp::croak('json text or perl structure exceeds maximum nesting level (max_depth set too low?)');
1513 }
1514 }
1515 elsif ( $s eq ']' or $s eq '}' ) {
1516 last if ( --$self->{incr_nest} <= 0 );
1517 }
1518 elsif ( $s eq '#' ) {
1519 while ( $len > $p ) {
1520 last if substr( $text, $p++, 1 ) eq "\n";
1521 }
1522 }
1523  
1524 }
1525  
1526 }
1527  
1528 $self->{incr_p} = $p;
1529  
1530 return if ( $self->{incr_mode} == INCR_M_JSON and $self->{incr_nest} > 0 );
1531  
1532 return '' unless ( length substr( $self->{incr_text}, 0, $p ) );
1533  
1534 local $Carp::CarpLevel = 2;
1535  
1536 $self->{incr_p} = $restore;
1537 $self->{incr_c} = $p;
1538  
1539 my ( $obj, $tail ) = $coder->PP_decode_json( substr( $self->{incr_text}, 0, $p ), 0x10000001 );
1540  
1541 $self->{incr_text} = substr( $self->{incr_text}, $p );
1542 $self->{incr_p} = 0;
1543  
1544 return $obj or '';
1545 }
1546  
1547  
1548 sub incr_text {
1549 if ( $_[0]->{incr_parsing} ) {
1550 Carp::croak("incr_text can not be called when the incremental parser already started parsing");
1551 }
1552 $_[0]->{incr_text};
1553 }
1554  
1555  
1556 sub incr_skip {
1557 my $self = shift;
1558 $self->{incr_text} = substr( $self->{incr_text}, $self->{incr_c} );
1559 $self->{incr_p} = 0;
1560 }
1561  
1562  
1563 sub incr_reset {
1564 my $self = shift;
1565 $self->{incr_text} = undef;
1566 $self->{incr_p} = 0;
1567 $self->{incr_mode} = 0;
1568 $self->{incr_nest} = 0;
1569 $self->{incr_parsing} = 0;
1570 }
1571  
1572 ###############################
1573  
1574  
1575 1;
1576 __END__