/
XS.pm
122 lines (90 loc) · 2.2 KB
/
XS.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package Mojo::JSON::XS;
use strict;
use warnings;
use base 'Mojo::Base';
use JSON::XS;
use Mojo::ByteStream 'b';
# Literal names
our $FALSE = Mojo::JSON::XS::_Bool->new(0);
our $TRUE = Mojo::JSON::XS::_Bool->new(1);
# Byte order marks
my $BOM_RE = qr/
(?:
\357\273\277 # UTF-8
|
\377\376\0\0 # UTF-32LE
|
\0\0\376\377 # UTF-32BE
|
\376\377 # UTF-16BE
|
\377\376 # UTF-16LE
)
/x;
# Unicode encoding detection
my $UTF_PATTERNS = {
"\0\0\0[^\0]" => 'UTF-32BE',
"\0[^\0]\0[^\0]" => 'UTF-16BE',
"[^\0]\0\0\0" => 'UTF-32LE',
"[^\0]\0[^\0]\0" => 'UTF-16LE'
};
__PACKAGE__->attr('_jsonxs' => sub { JSON::XS->new->convert_blessed(1) });
__PACKAGE__->attr('error');
sub decode {
my ($self, $string) = @_;
# Shortcut
return unless $string;
# Cleanup
$self->error(undef);
# Remove BOM
$string =~ s/^$BOM_RE//go;
# Detect and decode unicode
my $encoding = 'UTF-8';
for my $pattern (keys %$UTF_PATTERNS) {
if ($string =~ /^$pattern/) {
$encoding = $UTF_PATTERNS->{$pattern};
last;
}
}
$string = b($string)->decode($encoding)->to_string;
my $result;
eval {$result = $self->_jsonxs->decode($string);};
if ($@) {
$self->_exception($string, $@);
return;
}
return $result;
}
sub encode {
my ($self, $ref) = @_;
my $string = $self->_jsonxs->encode($ref);
# Unicode
return b($string)->encode('UTF-8')->to_string;
}
sub false {$FALSE}
sub true {$TRUE}
sub _exception {
my ($self, $string, $error) = @_;
# Message
$error ||= 'Syntax error';
chop $error;
$error =~ s/, at .*? line .*//;
# Context
my $context = substr $string, 0, 25;
$context = "\"$context\"" if $context;
$context ||= 'end of file';
# Error
$self->error(qq/$error near $context./) and return;
}
# Emulate boolean type
package Mojo::JSON::XS::_Bool;
use strict;
use warnings;
use base 'Mojo::Base';
use overload (
'0+' => sub { $_[0]->{_value} },
'""' => sub { $_[0]->{_value} }
);
sub new { shift->SUPER::new(_value => shift) }
sub TO_JSON { $_[0]->{_value} ? JSON::XS::true : JSON::XS::false }
1;