Perlito5/JSON.pm untested

filter: Statementstmt 0.0% 0 / 44 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 3 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 94 CC 18 SCAR 45.6
CC
18
Cov
0%
escape_string
110.0
_dumper
90.0
ast_dumper
2.0
CRAP 95.6
1 package Perlito5::JSON;
2  
3 sub ast_dumper {
4 my $seen = {};
5 my $level = '';
6 my $pos = '[TODO - recursive structure is not supported]';
7 return _dumper( $_[0], $level, $seen, $pos );
8 }
9  
10 sub _dumper {
11 my ( $obj, $tab, $seen, $pos ) = @_;
12 return 'null' if !defined $obj;
13 my $ref = ref($obj);
14 return escape_string($obj) if !$ref;
15 my $as_string = "$obj";
16 return $seen->{$as_string} if $seen->{$as_string};
17 $seen->{$as_string} = $pos;
18 my $tab1 = $tab . ' ';
19  
20 if ( $ref eq 'ARRAY' ) {
21 return '[]' unless @$obj;
22 my @out;
23 for my $i ( 0 .. $#$obj ) {
24 my $here = $pos . '[' . $i . ']';
25 push @out, $tab1 . _dumper( $obj->[$i], $tab1, $seen, $here );
26 }
27 return "[\n" . join( ",\n", @out ) . "\n" . $tab . ']';
28 }
29 elsif ( $ref eq 'SCALAR' ) {
30 return '{ "_type": "SCALAR", "value": ' . _dumper( $$obj, $tab1, $seen, $pos ) . ' }';
31 }
32 elsif ( $ref eq 'CODE' ) {
33 return '{ "_type": "CODE", "value": "DUMMY" }';
34 }
35 $ref =~ s/^Perlito5::AST:://; # shorten
36 my @out;
37 push @out, qq{"_type": "$ref"} if $ref ne 'HASH';
38 for my $i ( sort keys %$obj ) {
39 my $here = $pos . '{' . $i . '}';
40 push @out, $tab1 . qq{"$i": } . _dumper( $obj->{$i}, $tab1, $seen, $here );
41 }
42 return "{\n" . join( ",\n", @out ) . "\n" . $tab . "}";
43 }
44  
45 sub escape_string {
46 my $s = shift;
47 my @out;
48 return qq{""} if $s eq '';
49 return 0 + $s if ( 0 + $s ) eq $s && $s =~ /[0-9]/;
50 for my $i ( 0 .. length($s) - 1 ) {
51 my $c = substr( $s, $i, 1 );
52 if ( $c eq "\\" || $c eq '"' ) {
53 push @out, '\\' . $c;
54 }
55 elsif ( $c eq "\n" ) {
56 push @out, '\\n';
57 }
58 elsif ( $c eq "\r" ) {
59 push @out, '\\r';
60 }
61 elsif ( $c eq "\t" ) {
62 push @out, '\\t';
63 }
64 elsif ( $c eq "\b" ) {
65 push @out, '\\b';
66 }
67 elsif ( $c eq "\f" ) {
68 push @out, '\\f';
69 }
70 elsif ( $c le chr(0x1F) ) {
71 push @out, sprintf( "\\u%04x", ord($c) );
72 }
73 else {
74 push @out, $c;
75 }
76 }
77 return join( '', '"', @out, '"' );
78 }
79  
80 1;
81