BSON.pm

filter: Statementstmt 72.4% 247 / 341 Branchbran 54.7% 127 / 232 Conditioncond 46.3% 50 / 108 MC/DCmcdc 21.6% 13 / 60 Subroutinesub 86.4% 32 / 37 Podpod 90.0% 9 / 10 totaltotal 60.6% 478 / 788 CC 159 SCAR 45.3
CC
159
Cov
62%
_inflate_hash
600.0
inflate_extjson
56.0
_extjson_to_perl
40.8
CRAP 92.9
↑ Summary BSON/PP.pm »
1 71 ▶use 5.010001;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 71 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 71 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 package BSON;
6 # ABSTRACT: BSON serialization and deserialization
7  
8 71 ▶use base 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 71 our @EXPORT_OK = qw/encode decode/;
10  
11 71 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 71 our $VERSION = 'v1.12.0';
13  
14 71 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 71 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 71 ▶use Scalar::Util qw/blessed looks_like_number/;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 71 ▶use Moo 2.002004; # safer generated code
Subroutine BEGIN: called CC=1 SCAR=0.0
19 71 ▶use boolean;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 71 ▶use BSON::OID;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 use constant {
23 HAS_INT64 => $Config{use64bitint},
24 HAS_LD => $Config{uselongdouble},
25 71 ▶};
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 71 ▶use if !HAS_INT64, "Math::BigInt";
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 71 my $bools_re = qr/::(?:Boolean|_Bool|Bool)\z/;
30  
31 71 ▶use namespace::clean -except => 'meta';
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 71 my $max_int32 = 2147483647;
34  
35 # Dependency-free equivalent of what we need from Module::Runtime
36 sub _try_load {
37 141 ▶ my ( $mod, $ver ) = @_;
Subroutine _try_load: called CC=4 SCAR=13.9
38 141 ( my $file = "$mod.pm" ) =~ s{::}{/}g;
39 141 ▶ my $load = eval { require $file; $mod->VERSION($ver) if defined $ver; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if defined $ver 0 71 71
40 141 ▶ delete $INC{$file} if !$load; # for old, broken perls
Branch: 1 branch
BranchTrueFalseTotal
unless $load 70 71 141
41 141 ▶ die $@ if !$load;
Branch: 1 branch
BranchTrueFalseTotal
unless $load 70 71 141
42 71 return 1;
43 }
44  
45 BEGIN {
46 71 ▶ my ($class, @errs);
Subroutine BEGIN: called CC=10 SCAR=29.5
47 71 ▶ if ( $class = $ENV{PERL_BSON_BACKEND} ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($class = $ENV{'PERL_BSON_BACKEND'}) { } 1 70 71
elsif (eval { do { _try_load($class = 'BSON::XS') } } or do { push @errs, $@; 0 }) { } 0 70 70
elsif (eval { do { _try_load($class = 'BSON::PP') } } or do { push @errs, $@; 0 }) { } 70 0 70
48 1 eval { _try_load($class) };
49 1 ▶ if ( my $err = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 1 1
50 0 $err =~ s{ at \S+ line .*}{};
51 0 die "Error: PERL_BSON_BACKEND '$class' could not be loaded: $err\n";
52 }
53 1 ▶ unless ($class->can("_encode_bson") && $class->can("_decode_bson") ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class->can("_encode_bson") and $class->can("_decode_bson")) 0 1 1
Condition33%1/3
$class->can("_encode_bson") and $class->can("_decode_bson")
!ll&&!rl&&r
001
MC/DC0%0/2
$class->can("_encode_bson") and $class->can("_decode_bson")
$class->can("_encode_bson") $class->can("_decode_bson")
Truth table33%1/3
A and B
A= $class->can("_encode_bson")B= $class->can("_decode_bson")
ABresult
0X0
100
111
54 0 die "Error: PERL_BSON_BACKEND '$class' does not implement the correct API.\n";
55 }
56 }
57 70 ▶ elsif ( eval { _try_load( $class = "BSON::XS" ) } or do { push @errs, $@; 0 } ) {
Condition33%1/3
eval { do { _try_load($class = "BSON::XS") } } or do { push @errs, $@; 0 }
l!l&&r!l&&!r
0070
MC/DC0%0/2
eval { do { _try_load($class = "BSON::XS") } } or do { push @errs, $@; 0 }
eval { do { _try_load($class = "BSON::XS") } } do { push @errs, $@; 0 }
Truth table33%1/3
A or B
A= eval { do { _try_load($class = "BSON::XS") } }B= do { push @errs, $@; 0 }
ABresult
1X1
011
000
58 # module loaded; nothing else to do
59 }
60 70 ▶ elsif ( eval { _try_load( $class = "BSON::PP" ) } or do { push @errs, $@; 0 } ) {
Condition33%1/3
eval { do { _try_load($class = "BSON::PP") } } or do { push @errs, $@; 0 }
l!l&&r!l&&!r
7000
MC/DC0%0/2
eval { do { _try_load($class = "BSON::PP") } } or do { push @errs, $@; 0 }
eval { do { _try_load($class = "BSON::PP") } } do { push @errs, $@; 0 }
Truth table33%1/3
A or B
A= eval { do { _try_load($class = "BSON::PP") } }B= do { push @errs, $@; 0 }
ABresult
1X1
011
000
61 # module loaded; nothing else to do
62 }
63 else {
64 0 s/\n/ /g for @errs;
65 0 die join( "\n* ", "Error: Couldn't load a BSON backend:", @errs ) . "\n";
66 }
67  
68 71 *_encode_bson = $class->can("_encode_bson");
69 71 *_decode_bson = $class->can("_decode_bson");
70 71 ▶ *_backend_class = sub { $class }; # for debugging
Subroutine __ANON__: not called CC=1 SCAR=1.2
71 }
72  
73 # LOAD AFTER XS/PP, so that modules can pick up right version of helpers
74 71 ▶use BSON::Types (); # loads types for extjson inflation
Subroutine BEGIN: called CC=1 SCAR=0.0
75  
76 #--------------------------------------------------------------------------#
77 # public attributes
78 #--------------------------------------------------------------------------#
79  
80 #pod =attr error_callback
81 #pod
82 #pod This attribute specifies a function reference that will be called with
83 #pod three positional arguments:
84 #pod
85 #pod =for :list
86 #pod * an error string argument describing the error condition
87 #pod * a reference to the problematic document or byte-string
88 #pod * the method in which the error occurred (e.g. C<encode_one> or C<decode_one>)
89 #pod
90 #pod Note: for decoding errors, the byte-string is passed as a reference to avoid
91 #pod copying possibly large strings.
92 #pod
93 #pod If not provided, errors messages will be thrown with C<Carp::croak>.
94 #pod
95 #pod =cut
96  
97 has error_callback => (
98 is => 'ro',
99 1 ▶ isa => sub { die "not a code reference" if defined $_[0] && ! ref $_[0] eq 'CODE' },
Subroutine __ANON__: called CC=3 SCAR=14.2
Branch: 1 branch
BranchTrueFalseTotal
if defined $_[0] and !ref($_[0]) eq "CODE" 0 1 1
Condition33%1/3
defined $_[0] and !ref($_[0]) eq "CODE"
!ll&&!rl&&r
010
MC/DC0%0/2
defined $_[0] and !ref($_[0]) eq "CODE"
defined $_[0] !ref($_[0]) eq "CODE"
Truth table33%1/3
A and not(B)
A= defined $_[0]B= !ref($_[0]) eq "CODE"
ABresult
0X0
100
111
100 71 );
101  
102 #pod =attr invalid_chars
103 #pod
104 #pod A string containing ASCII characters that must not appear in keys. The default
105 #pod is the empty string, meaning there are no invalid characters.
106 #pod
107 #pod =cut
108  
109 has invalid_chars => (
110 is => 'ro',
111 2 ▶ isa => sub { die "not a string" if ! defined $_[0] || ref $_[0] },
Subroutine __ANON__: called CC=3 SCAR=14.2
Branch: 1 branch
BranchTrueFalseTotal
if not defined $_[0] or ref $_[0] 0 2 2
Condition33%1/3
not defined $_[0] or ref $_[0]
l!l&&r!l&&!r
002
MC/DC0%0/2
not defined $_[0] or ref $_[0]
not defined $_[0] ref $_[0]
Truth table33%1/3
not(A) or B
A= not defined $_[0]B= ref $_[0]
ABresult
1X1
011
000
112 71 );
113  
114 #pod =attr max_length
115 #pod
116 #pod This attribute defines the maximum document size. The default is 0, which
117 #pod disables any maximum.
118 #pod
119 #pod If set to a positive number, it applies to both encoding B<and> decoding (the
120 #pod latter is necessary for prevention of resource consumption attacks).
121 #pod
122 #pod =cut
123  
124 has max_length => (
125 is => 'ro',
126 1 ▶ isa => sub { die "not a non-negative number" unless defined $_[0] && $_[0] >= 0 },
Subroutine __ANON__: called CC=3 SCAR=14.2
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] and $_[0] >= 0 0 1 1
Condition33%1/3
defined $_[0] and $_[0] >= 0
!ll&&!rl&&r
001
MC/DC0%0/2
defined $_[0] and $_[0] >= 0
defined $_[0] $_[0] >= 0
Truth table33%1/3
A and B
A= defined $_[0]B= $_[0] >= 0
ABresult
0X0
100
111
127 71 );
128  
129 #pod =attr op_char
130 #pod
131 #pod This is a single character to use for special MongoDB-specific query
132 #pod operators. If a key starts with C<op_char>, the C<op_char> character will
133 #pod be replaced with "$".
134 #pod
135 #pod The default is "$", meaning that no replacement is necessary.
136 #pod
137 #pod =cut
138  
139 has op_char => (
140 is => 'ro',
141 1 ▶ isa => sub { die "not a single character" if defined $_[0] && length $_[0] > 1 },
Subroutine __ANON__: called CC=3 SCAR=14.2
Branch: 1 branch
BranchTrueFalseTotal
if defined $_[0] and length $_[0] > 1 0 1 1
Condition33%1/3
defined $_[0] and length $_[0] > 1
!ll&&!rl&&r
010
MC/DC0%0/2
defined $_[0] and length $_[0] > 1
defined $_[0] length $_[0] > 1
Truth table33%1/3
A and B
A= defined $_[0]B= length $_[0] > 1
ABresult
0X0
100
111
142 71 );
143  
144 #pod =attr ordered
145 #pod
146 #pod If set to a true value, then decoding will return a reference to a tied
147 #pod hash that preserves key order. Otherwise, a regular (unordered) hash
148 #pod reference will be returned.
149 #pod
150 #pod B<IMPORTANT CAVEATS>:
151 #pod
152 #pod =for :list
153 #pod * When 'ordered' is true, users must not rely on the return value being any
154 #pod particular tied hash implementation. It may change in the future for
155 #pod efficiency.
156 #pod * Turning this option on entails a significant speed penalty as tied hashes
157 #pod are slower than regular Perl hashes.
158 #pod
159 #pod The default is false.
160 #pod
161 #pod =cut
162  
163 71 has ordered => (
164 is => 'ro',
165 );
166  
167 #pod =attr prefer_numeric
168 #pod
169 #pod When false, scalar values will be encoded as a number if they were
170 #pod originally a number or were ever used in a numeric context. However, a
171 #pod string that looks like a number but was never used in a numeric context
172 #pod (e.g. "42") will be encoded as a string.
173 #pod
174 #pod If C<prefer_numeric> is set to true, the encoder will attempt to coerce
175 #pod strings that look like a number into a numeric value. If the string
176 #pod doesn't look like a double or integer, it will be encoded as a string.
177 #pod
178 #pod B<IMPORTANT CAVEAT>: the heuristics for determining whether something is a
179 #pod string or number are less accurate on older Perls. See L<BSON::Types>
180 #pod for wrapper classes that specify exact serialization types.
181 #pod
182 #pod The default is false.
183 #pod
184 #pod =cut
185  
186 71 has prefer_numeric => (
187 is => 'ro',
188 );
189  
190 #pod =attr wrap_dbrefs
191 #pod
192 #pod If set to true, during decoding, documents with the fields C<'$id'> and
193 #pod C<'$ref'> (literal dollar signs, not variables) will be wrapped as
194 #pod L<BSON::DBRef> objects. If false, they are decoded into ordinary hash
195 #pod references (or ordered hashes, if C<ordered> is true).
196 #pod
197 #pod The default is true.
198 #pod
199 #pod =cut
200  
201 71 has wrap_dbrefs => (
202 is => 'ro',
203 );
204  
205 #pod =attr wrap_numbers
206 #pod
207 #pod If set to true, during decoding, numeric values will be wrapped into
208 #pod BSON type-wrappers: L<BSON::Double>, L<BSON::Int64> or L<BSON::Int32>.
209 #pod While very slow, this can help ensure fields can round-trip if unmodified.
210 #pod
211 #pod The default is false.
212 #pod
213 #pod =cut
214  
215 71 has wrap_numbers => (
216 is => 'ro',
217 );
218  
219 #pod =attr wrap_strings
220 #pod
221 #pod If set to true, during decoding, string values will be wrapped into a BSON
222 #pod type-wrappers, L<BSON::String>. While very slow, this can help ensure
223 #pod fields can round-trip if unmodified.
224 #pod
225 #pod The default is false.
226 #pod
227 #pod =cut
228  
229 71 has wrap_strings => (
230 is => 'ro',
231 );
232  
233 #pod =attr dt_type (Discouraged)
234 #pod
235 #pod Sets the type of object which is returned for BSON DateTime fields. The
236 #pod default is C<undef>, which returns objects of type L<BSON::Time>. This is
237 #pod overloaded to be the integer epoch value when used as a number or string,
238 #pod so is somewhat backwards compatible with C<dt_type> in the L<MongoDB>
239 #pod driver.
240 #pod
241 #pod Other acceptable values are L<BSON::Time> (explicitly), L<DateTime>,
242 #pod L<Time::Moment>, L<DateTime::Tiny>, L<Mango::BSON::Time>.
243 #pod
244 #pod Because BSON::Time objects have methods to convert to DateTime,
245 #pod Time::Moment or DateTime::Tiny, use of this field is discouraged. Users
246 #pod should use these methods on demand. This option is provided for backwards
247 #pod compatibility only.
248 #pod
249 #pod =cut
250  
251 has dt_type => (
252 is => 'ro',
253 3 ▶ isa => sub { return if !defined($_[0]); die "not a string" if ref $_[0] },
Subroutine __ANON__: called CC=3 SCAR=11.1
Branch: 2 branches
BranchTrueFalseTotal
unless defined $_[0] 1 2 3
if ref $_[0] 0 2 2
254 71 );
255  
256 sub BUILD {
257 762 ▶ my ($self) = @_;
Subroutine BUILD: called CC=3 SCAR=11.1
Pod undocumented
258 762 ▶ $self->{wrap_dbrefs} = 1 unless defined $self->{wrap_dbrefs};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"wrap_dbrefs"} 762 0 762
259 762 ▶ $self->{invalid_chars} = "" unless defined $self->{invalid_chars};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"invalid_chars"} 760 2 762
260 }
261  
262 #--------------------------------------------------------------------------#
263 # public methods
264 #--------------------------------------------------------------------------#
265  
266 #pod =method encode_one
267 #pod
268 #pod $byte_string = $codec->encode_one( $doc );
269 #pod $byte_string = $codec->encode_one( $doc, \%options );
270 #pod
271 #pod Takes a "document", typically a hash reference, an array reference, or a
272 #pod Tie::IxHash object and returns a byte string with the BSON representation of
273 #pod the document.
274 #pod
275 #pod An optional hash reference of options may be provided. Valid options include:
276 #pod
277 #pod =for :list
278 #pod * first_key – if C<first_key> is defined, it and C<first_value>
279 #pod will be encoded first in the output BSON; any matching key found in the
280 #pod document will be ignored.
281 #pod * first_value - value to assign to C<first_key>; will encode as Null if omitted
282 #pod * error_callback – overrides codec default
283 #pod * invalid_chars – overrides codec default
284 #pod * max_length – overrides codec default
285 #pod * op_char – overrides codec default
286 #pod * prefer_numeric – overrides codec default
287 #pod
288 #pod =cut
289  
290 sub encode_one {
291 2485 ▶ my ( $self, $document, $options ) = @_;
Subroutine encode_one: called CC=13 SCAR=25.7
Pod documented
292 2485 my $type = ref($document);
293  
294 2485 ▶ Carp::croak "Can't encode scalars" unless $type;
Branch: 1 branch
BranchTrueFalseTotal
unless $type 1 2484 2485
295 # qr// is blessed to 'Regexp';
296 2484 ▶ if ( $type eq "Regexp"
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "Regexp" or not builtin::blessed($document) || $type eq "HASH" || $type eq "ARRAY") 2 2482 2484
Condition100%9/9
$type eq "Regexp" or not builtin::blessed($document) || $type eq "HASH" || $type eq "ARRAY"
l!l&&r!l&&!r
112482
builtin::blessed($document) || $type eq 'HASH' || $type eq 'ARRAY'
l!l&&r!l&&!r
248111
builtin::blessed($document) or $type eq "HASH"
l!l&&r!l&&!r
2024612
MC/DC100%4/4
$type eq "Regexp" or not builtin::blessed($document) || $type eq "HASH" || $type eq "ARRAY"
$type eq "Regexp" builtin::blessed($document) $type eq "HASH" $type eq 'ARRAY'
Truth table100%5/5
A or not(B or C || D)
A= $type eq "Regexp"B= builtin::blessed($document)C= $type eq "HASH"D= $type eq 'ARRAY'
ABCDresult
1XXX1
00001
01XX0
001X0
00010
297 || !( blessed($document) || $type eq 'HASH' || $type eq 'ARRAY' ) )
298 {
299 2 Carp::croak "Can't encode non-container of type '$type'";
300 }
301  
302 2482 ▶ $document = BSON::Doc->new(@$document)
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "ARRAY" 1 2481 2482
303 if $type eq 'ARRAY';
304  
305 2482 ▶ my $merged_opts = { %$self, ( $options ? %$options : () ) };
Branch: 1 branch
BranchTrueFalseTotal
$options ? : 731 1751 2482
306  
307 2482 my $bson = eval { _encode_bson( $document, $merged_opts ) };
308 # XXX this is a late max_length check -- it should be checked during
309 # encoding after each key
310 2482 ▶ if ( $@ or ( $merged_opts->{max_length} && length($bson) > $merged_opts->{max_length} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or $merged_opts->{"max_length"} and length $bson > $merged_opts->{"max_length"}) 12 2470 2482
Condition83%5/6
$@ or $merged_opts->{"max_length"} and length $bson > $merged_opts->{"max_length"}
l!l&&r!l&&!r
1122469
$merged_opts->{"max_length"} and length $bson > $merged_opts->{"max_length"}
!ll&&!rl&&r
247001
MC/DC66%2/3
$@ or $merged_opts->{"max_length"} and length $bson > $merged_opts->{"max_length"}
$@ $merged_opts->{"max_length"} length $bson > $merged_opts->{"max_length"}
Truth table75%3/4
A or B and C
A= $@B= $merged_opts->{"max_length"}C= length $bson > $merged_opts->{"max_length"}
ABCresult
1XX1
0111
00X0
0100
311 12 ▶ my $msg = $@ || "Document exceeds maximum size $merged_opts->{max_length}";
Condition100%2/2
$@ || "Document exceeds maximum size $merged_opts->{'max_length'}"
l!l
111
MC/DC100%1/1
$@ || "Document exceeds maximum size $merged_opts->{'max_length'}"
$@
Truth table100%2/2
A
A= $@
Aresult
11
00
312 12 ▶ if ( $merged_opts->{error_callback} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($merged_opts->{'error_callback'}) { } 0 12 12
313 0 $merged_opts->{error_callback}->( $msg, $document, 'encode_one' );
314 }
315 else {
316 12 Carp::croak("During encode_one, $msg");
317 }
318 }
319  
320 2470 return $bson;
321 }
322  
323 #pod =method decode_one
324 #pod
325 #pod $doc = $codec->decode_one( $byte_string );
326 #pod $doc = $codec->decode_one( $byte_string, \%options );
327 #pod
328 #pod Takes a byte string with a BSON-encoded document and returns a
329 #pod hash reference representing the decoded document.
330 #pod
331 #pod An optional hash reference of options may be provided. Valid options include:
332 #pod
333 #pod =for :list
334 #pod * dt_type – overrides codec default
335 #pod * error_callback – overrides codec default
336 #pod * max_length – overrides codec default
337 #pod * ordered - overrides codec default
338 #pod * wrap_dbrefs - overrides codec default
339 #pod * wrap_numbers - overrides codec default
340 #pod * wrap_strings - overrides codec default
341 #pod
342 #pod =cut
343  
344 sub decode_one {
345 2150 ▶ my ( $self, $string, $options ) = @_;
Subroutine decode_one: called CC=7 SCAR=19.6
Pod documented
346  
347 2150 ▶ my $merged_opts = { %$self, ( $options ? %$options : () ) };
Branch: 1 branch
BranchTrueFalseTotal
$options ? : 690 1460 2150
348  
349 2150 ▶ if ( $merged_opts->{max_length} && length($string) > $merged_opts->{max_length} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($merged_opts->{"max_length"} and length $string > $merged_opts->{"max_length"}) 1 2149 2150
Condition66%2/3
$merged_opts->{"max_length"} and length $string > $merged_opts->{"max_length"}
!ll&&!rl&&r
214901
MC/DC50%1/2
$merged_opts->{"max_length"} and length $string > $merged_opts->{"max_length"}
$merged_opts->{"max_length"} length $string > $merged_opts->{"max_length"}
Truth table66%2/3
A and B
A= $merged_opts->{"max_length"}B= length $string > $merged_opts->{"max_length"}
ABresult
0X0
100
111
350 1 my $msg = "Document exceeds maximum size $merged_opts->{max_length}";
351 1 ▶ if ( $merged_opts->{error_callback} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($merged_opts->{'error_callback'}) { } 0 1 1
352 0 $merged_opts->{error_callback}->( $msg, \$string, 'decode_one' );
353 }
354 else {
355 1 Carp::croak("During decode_one, $msg");
356 }
357 }
358  
359 2149 my $document = eval { _decode_bson( $string, $merged_opts ) };
360 2149 ▶ if ( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 79 2070 2149
361 79 ▶ if ( $merged_opts->{error_callback} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($merged_opts->{'error_callback'}) { } 1 78 79
362 1 $merged_opts->{error_callback}->( $@, \$string, 'decode_one' );
363 }
364 else {
365 78 Carp::croak("During decode_one, $@");
366 }
367 }
368  
369 2071 return $document;
370 }
371  
372 #pod =method clone
373 #pod
374 #pod $copy = $codec->clone( ordered => 1 );
375 #pod
376 #pod Constructs a copy of the original codec, but allows changing
377 #pod attributes in the copy.
378 #pod
379 #pod =cut
380  
381 sub clone {
382 0 ▶ my ($self, @args) = @_;
Subroutine clone: not called CC=3 SCAR=24.8
Pod documented
383 0 my $class = ref($self);
384 0 ▶ if ( @args == 1 && ref( $args[0] ) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args == 1 and ref $args[0] eq "HASH") 0 0 0
Condition0%0/3
@args == 1 and ref $args[0] eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
@args == 1 and ref $args[0] eq "HASH"
@args == 1 ref $args[0] eq "HASH"
Truth table0%0/3
A and B
A= @args == 1B= ref $args[0] eq "HASH"
ABresult
0X0
100
111
385 0 return $class->new( %$self, %{$args[0]} );
386 }
387  
388 0 return $class->new( %$self, @args );
389 }
390  
391  
392 #--------------------------------------------------------------------------#
393 # public class methods
394 #--------------------------------------------------------------------------#
395  
396 #pod =method create_oid
397 #pod
398 #pod $oid = BSON->create_oid;
399 #pod
400 #pod This class method returns a new L<BSON::OID>. This abstracts OID
401 #pod generation away from any specific Object ID class and makes it an interface
402 #pod on a BSON codec. Alternative BSON codecs should define a similar class
403 #pod method that returns an Object ID of whatever type is appropriate.
404 #pod
405 #pod =cut
406  
407 3 ▶sub create_oid { return BSON::OID->new }
Subroutine create_oid: called CC=1 SCAR=0.0
Pod documented
408  
409 #pod =method inflate_extjson (DEPRECATED)
410 #pod
411 #pod This legacy method does not follow the L<MongoDB Extended JSON|https://github.com/mongodb/specifications/blob/master/source/extended-json.rst>
412 #pod specification.
413 #pod
414 #pod Use L</extjson_to_perl> instead.
415 #pod
416 #pod =cut
417  
418 sub inflate_extjson {
419 0 ▶ my ( $self, $hash ) = @_;
Subroutine inflate_extjson: not called CC=7 SCAR=40.3
Pod documented
420  
421 0 for my $k ( keys %$hash ) {
422 0 my $v = $hash->{$k};
423 0 ▶ if ( substr( $k, 0, 1 ) eq '$' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($k, 0, 1) eq "\$") 0 0 0
424 0 croak "Dollar-prefixed key '$k' is not legal in top-level hash";
425 }
426 0 my $type = ref($v);
427 0 ▶ $hash->{$k} =
Branch: 4 branches
BranchTrueFalseTotal
$type eq 'HASH' ? : 0 0 0
$type eq 'ARRAY' ? : 0 0 0
$type =~ /$bools_re/ ? : 0 0 0
$v ? : 0 0 0
428 $type eq 'HASH' ? $self->_inflate_hash($v)
429 : $type eq 'ARRAY' ? $self->_inflate_array($v)
430 : $type =~ $bools_re ? ( $v ? true : false )
431 : $v;
432 }
433  
434 0 return $hash;
435 }
436  
437 #pod =method perl_to_extjson
438 #pod
439 #pod use JSON::MaybeXS;
440 #pod my $ext = BSON->perl_to_extjson($data, \%options);
441 #pod my $json = encode_json($ext);
442 #pod
443 #pod Takes a perl data structure (i.e. hashref) and turns it into an
444 #pod L<MongoDB Extended JSON|https://github.com/mongodb/specifications/blob/master/source/extended-json.rst>
445 #pod structure. Note that the structure will still have to be serialized.
446 #pod
447 #pod Possible options are:
448 #pod
449 #pod =for :list
450 #pod * C<relaxed> A boolean indicating if "relaxed extended JSON" should
451 #pod be generated. If not set, the default value is taken from the
452 #pod C<BSON_EXTJSON_RELAXED> environment variable.
453 #pod
454 #pod =cut
455  
456 71 ▶my $use_win32_specials = ($^O eq 'MSWin32' && $] lt "5.022");
Condition33%1/3
$^O eq 'MSWin32' && $] lt '5.022'
!ll&&!rl&&r
7100
MC/DC0%0/2
$^O eq 'MSWin32' && $] lt '5.022'
$^O eq 'MSWin32' $] lt '5.022'
Truth table33%1/3
A && B
A= $^O eq 'MSWin32'B= $] lt '5.022'
ABresult
0X0
100
111
457  
458 71 ▶my $is_inf = $use_win32_specials ? qr/^1.\#INF/i : qr/^inf/i;
Branch: 1 branch
BranchTrueFalseTotal
$use_win32_specials ? : 0 71 71
459 71 ▶my $is_ninf = $use_win32_specials ? qr/^-1.\#INF/i : qr/^-inf/i;
Branch: 1 branch
BranchTrueFalseTotal
$use_win32_specials ? : 0 71 71
460 71 ▶my $is_nan = $use_win32_specials ? qr/^-?1.\#(?:IND|QNAN)/i : qr/^-?nan/i;
Branch: 1 branch
BranchTrueFalseTotal
$use_win32_specials ? : 0 71 71
461  
462 sub perl_to_extjson {
463 3667 ▶ my ($class, $data, $options) = @_;
Subroutine perl_to_extjson: called CC=22 SCAR=35.2
Pod documented
464  
465 3667 local $ENV{BSON_EXTJSON} = 1;
466 3667 local $ENV{BSON_EXTJSON_RELAXED} = $ENV{BSON_EXTJSON_RELAXED};
467 3667 $ENV{BSON_EXTJSON_RELAXED} = $options->{relaxed};
468  
469 3667 ▶ if (not defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 6 3661 3667
470 6 return undef; ## no critic
471 }
472  
473 3661 ▶ if (blessed($data) and $data->can('TO_JSON')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($data) and $data->can("TO_JSON")) 1766 1895 3661
Condition100%3/3
builtin::blessed($data) and $data->can("TO_JSON")
!ll&&!rl&&r
188961766
MC/DC100%2/2
builtin::blessed($data) and $data->can("TO_JSON")
builtin::blessed($data) $data->can("TO_JSON")
Truth table100%3/3
A and B
A= builtin::blessed($data)B= $data->can("TO_JSON")
ABresult
0X0
100
111
474 1766 my $json_data = $data->TO_JSON;
475 1766 return $json_data;
476 }
477  
478 1895 ▶ if (not ref $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $data) 67 1828 1895
479  
480 67 ▶ if (looks_like_number($data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&looks_like_number($data)) 25 42 67
481 25 ▶ if ($ENV{BSON_EXTJSON_RELAXED}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"BSON_EXTJSON_RELAXED"}) 16 9 25
482 16 return $data;
483 }
484  
485 9 ▶ if ($data =~ m{\A-?[0-9_]+\z}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data =~ /\A-?[0-9_]+\z/) { } 9 0 9
486 9 ▶ if ($data <= $max_int32) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data <= $max_int32) { } 9 0 9
487 9 return { '$numberInt' => "$data" };
488 }
489 else {
490 0 return { '$numberLong' => "$data" };
491 }
492 }
493 else {
494 0 ▶ return { '$numberDouble' => 'Infinity' }
Branch: 1 branch
BranchTrueFalseTotal
if $data =~ /$is_inf/ 0 0 0
495 if $data =~ $is_inf;
496 0 ▶ return { '$numberDouble' => '-Infinity' }
Branch: 1 branch
BranchTrueFalseTotal
if $data =~ /$is_ninf/ 0 0 0
497 if $data =~ $is_ninf;
498 0 ▶ return { '$numberDouble' => 'NaN' }
Branch: 1 branch
BranchTrueFalseTotal
if $data =~ /$is_nan/ 0 0 0
499 if $data =~ $is_nan;
500 0 my $value = "$data";
501 0 $value = $value / 1.0;
502 0 return { '$numberDouble' => "$value" };
503 }
504 }
505  
506 42 return $data;
507 }
508  
509 1828 ▶ if (boolean::isBoolean($data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&boolean::isBoolean($data)) 0 1828 1828
510 0 return $data;
511 }
512  
513 1828 ▶ if (ref $data eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH") 1812 16 1828
514 1812 for my $key (keys %$data) {
515 1850 my $value = $data->{$key};
516 1850 $data->{$key} = $class->perl_to_extjson($value, $options);
517 }
518 1812 return $data;
519 }
520  
521 16 ▶ if (ref $data eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "ARRAY") 10 6 16
522 10 for my $index (0 .. $#$data) {
523 16 my $value = $data->[$index];
524 16 $data->[$index] = $class->perl_to_extjson($value, $options);
525 }
526 10 return $data;
527 }
528  
529 6 ▶ if (blessed($data) and $data->isa('JSON::PP::Boolean')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($data) and $data->isa("JSON::PP::Boolean")) 4 2 6
Condition66%2/3
builtin::blessed($data) and $data->isa("JSON::PP::Boolean")
!ll&&!rl&&r
024
MC/DC50%1/2
builtin::blessed($data) and $data->isa("JSON::PP::Boolean")
builtin::blessed($data) $data->isa("JSON::PP::Boolean")
Truth table66%2/3
A and B
A= builtin::blessed($data)B= $data->isa("JSON::PP::Boolean")
ABresult
0X0
100
111
530 4 return $data;
531 }
532  
533 2 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($data) and $data->isa("Math::BigInt") || $data->isa("Math::BigFloat")) 2 0 2
Condition33%2/6
builtin::blessed($data) and $data->isa("Math::BigInt") || $data->isa("Math::BigFloat")
!ll&&!rl&&r
002
$data->isa("Math::BigInt") or $data->isa("Math::BigFloat")
l!l&&r!l&&!r
020
MC/DC0%0/3
builtin::blessed($data) and $data->isa("Math::BigInt") || $data->isa("Math::BigFloat")
builtin::blessed($data) $data->isa("Math::BigInt") $data->isa("Math::BigFloat")
Truth table25%1/4
A and B or C
A= builtin::blessed($data)B= $data->isa("Math::BigInt")C= $data->isa("Math::BigFloat")
ABCresult
0XX0
1000
11X1
1011
534 blessed($data) and (
535 $data->isa('Math::BigInt') or
536 $data->isa('Math::BigFloat')
537 )
538 ) {
539 2 return $data;
540 }
541  
542 0 die sprintf "Unsupported ref value (%s)", ref($data);
543 }
544  
545 #pod =method extjson_to_perl
546 #pod
547 #pod use JSON::MaybeXS;
548 #pod my $ext = decode_json($json);
549 #pod my $data = $bson->extjson_to_perl($ext);
550 #pod
551 #pod Takes an
552 #pod L<MongoDB Extended JSON|https://github.com/mongodb/specifications/blob/master/source/extended-json.rst>
553 #pod data structure and inflates it into a Perl data structure. Note that
554 #pod you have to decode the JSON string manually beforehand.
555 #pod
556 #pod Canonically specified numerical values like C<{"$numberInt":"23"}> will
557 #pod be inflated into their respective C<BSON::*> wrapper types. Plain numeric
558 #pod values will be left as-is.
559 #pod
560 #pod =cut
561  
562 sub extjson_to_perl {
563 2054 ▶ my ($class, $data) = @_;
Subroutine extjson_to_perl: called CC=2 SCAR=6.9
Pod documented
564 # top level keys are never extended JSON elements, so we wrap the
565 # _extjson_to_perl inflater so it applies only to values, not the
566 # original data structure
567 2054 for my $key (keys %$data) {
568 2102 my $value = $data->{$key};
569 2102 $data->{$key} = $class->_extjson_to_perl($value);
570 }
571 2054 return $data;
572 }
573  
574 sub _extjson_to_perl {
575 2177 ▶ my ($class, $data) = @_;
Subroutine _extjson_to_perl: called CC=36 SCAR=37.1
576  
577 2177 ▶ if (ref $data eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH") 2101 76 2177
578  
579 2101 ▶ if ( exists $data->{'$oid'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$oid"}) 26 2075 2101
580 26 return BSON::OID->new( oid => pack( "H*", $data->{'$oid'} ) );
581 }
582  
583 2075 ▶ if ( exists $data->{'$numberInt'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$numberInt"}) 38 2037 2075
584 38 return BSON::Int32->new( value => $data->{'$numberInt'} );
585 }
586  
587 2037 ▶ if ( exists $data->{'$numberLong'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$numberLong"}) 27 2010 2037
588 27 if (HAS_INT64) {
589 27 return BSON::Int64->new( value => $data->{'$numberLong'} );
590 }
591 else {
592 return BSON::Int64->new( value => Math::BigInt->new($data->{'$numberLong'}) );
593 }
594 }
595  
596 2010 ▶ if ( exists $data->{'$binary'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$binary"}) 24 1986 2010
597 24 require MIME::Base64;
598 24 ▶ if (exists $data->{'$type'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{'$type'}) { } 0 24 24
599 return BSON::Bytes->new(
600 data => MIME::Base64::decode_base64($data->{'$binary'}),
601 0 ▶ subtype => hex( $data->{'$type'} || 0 ),
Condition0%0/2
$data->{'$type'} || 0
l!l
00
MC/DC0%0/1
$data->{'$type'} || 0
$data->{'$type'}
Truth table0%0/2
A
A= $data->{'$type'}
Aresult
11
00
602 );
603 }
604 else {
605 24 my $value = $data->{'$binary'};
606 return BSON::Bytes->new(
607 data => MIME::Base64::decode_base64($value->{base64}),
608 24 ▶ subtype => hex( $value->{subType} || 0 ),
Condition50%1/2
$value->{'subType'} || 0
l!l
240
MC/DC0%0/1
$value->{'subType'} || 0
$value->{'subType'}
Truth table50%1/2
A
A= $value->{'subType'}
Aresult
11
00
609 );
610 }
611 }
612  
613 1986 ▶ if ( exists $data->{'$date'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$date"}) 17 1969 1986
614 17 my $v = $data->{'$date'};
615 17 ▶ $v = ref($v) eq 'HASH' ? $class->_extjson_to_perl($v) : _iso8601_to_epochms($v);
Branch: 1 branch
BranchTrueFalseTotal
ref $v eq 'HASH' ? : 15 2 17
616 17 return BSON::Time->new( value => $v );
617 }
618  
619 1969 ▶ if ( exists $data->{'$minKey'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$minKey"}) 4 1965 1969
620 4 return BSON::MinKey->new;
621 }
622  
623 1965 ▶ if ( exists $data->{'$maxKey'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$maxKey"}) 4 1961 1965
624 4 return BSON::MaxKey->new;
625 }
626  
627 1961 ▶ if ( exists $data->{'$timestamp'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$timestamp"}) 10 1951 1961
628 return BSON::Timestamp->new(
629 seconds => $data->{'$timestamp'}{t},
630 increment => $data->{'$timestamp'}{i},
631 10 );
632 }
633  
634 1951 ▶ if ( exists $data->{'$regex'} and not ref $data->{'$regex'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$regex"} and not ref $data->{"\$regex"}) 0 1951 1951
Condition33%1/3
exists $data->{"\$regex"} and not ref $data->{"\$regex"}
!ll&&!rl&&r
195100
MC/DC0%0/2
exists $data->{"\$regex"} and not ref $data->{"\$regex"}
exists $data->{"\$regex"} not ref $data->{"\$regex"}
Truth table33%1/3
A and not(B)
A= exists $data->{"\$regex"}B= not ref $data->{"\$regex"}
ABresult
0X0
100
111
635 return BSON::Regex->new(
636 pattern => $data->{'$regex'},
637 0 ▶ ( exists $data->{'$options'} ? ( flags => $data->{'$options'} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
exists $data->{'$options'} ? : 0 0 0
638 );
639 }
640  
641 1951 ▶ if ( exists $data->{'$regularExpression'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$regularExpression"}) 24 1927 1951
642 24 my $value = $data->{'$regularExpression'};
643 return BSON::Regex->new(
644 pattern => $value->{pattern},
645 24 ▶ ( exists $value->{options} ? ( flags => $value->{options} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
exists $value->{'options'} ? : 24 0 24
646 );
647 }
648  
649 1927 ▶ if ( exists $data->{'$code'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$code"}) 20 1907 1927
650 return BSON::Code->new(
651 code => $data->{'$code'},
652 ( exists $data->{'$scope'}
653 20 ▶ ? ( scope => $class->_extjson_to_perl($data->{'$scope'}) )
Branch: 1 branch
BranchTrueFalseTotal
exists $data->{'$scope'} ? : 12 8 20
654 : ()
655 ),
656 );
657 }
658  
659 1907 ▶ if ( exists $data->{'$undefined'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$undefined"}) 2 1905 1907
660 2 return undef; ## no critic
661 }
662  
663 1905 ▶ if ( exists $data->{'$dbPointer'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$dbPointer"}) 8 1897 1905
664 8 my $data = $data->{'$dbPointer'};
665 8 my $id = $data->{'$id'};
666 8 ▶ $id = $class->_extjson_to_perl($id) if ref($id) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $id eq "HASH" 8 0 8
667 return BSON::DBPointer->new(
668 8 '$ref' => $data->{'$ref'},
669 '$id' => $id,
670 );
671 }
672  
673 1897 ▶ if ( exists $data->{'$ref'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$ref"}) 10 1887 1897
674 10 my $id = delete $data->{'$id'};
675 10 ▶ $id = $class->_extjson_to_perl($id) if ref($id) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $id eq "HASH" 10 0 10
676 return BSON::DBRef->new(
677 '$ref' => delete $data->{'$ref'},
678 '$id' => $id,
679 10 '$db' => delete $data->{'$db'},
680 %$data, # extra
681 );
682 }
683  
684 1887 ▶ if ( exists $data->{'$numberDecimal'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$numberDecimal"}) 1823 64 1887
685 1823 return BSON::Decimal128->new( value => $data->{'$numberDecimal'} );
686 }
687  
688 # Following extended JSON is non-standard
689  
690 64 ▶ if ( exists $data->{'$numberDouble'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$numberDouble"}) 28 36 64
691 28 ▶ if ( $data->{'$numberDouble'} eq '-0' && $] lt '5.014' && ! HAS_LD ) {
Branch: 1 branch
BranchTrueFalseTotal
if () 0 28 28
Condition40%2/5
$data->{"\$numberDouble"} eq "-0" and $] lt "5.014" and
!ll
280
$data->{"\$numberDouble"} eq "-0" and $] lt "5.014"
!ll&&!rl&&r
2800
MC/DC0%0/2
$data->{"\$numberDouble"} eq "-0" and $] lt "5.014" and
$data->{"\$numberDouble"} eq "-0" $] lt "5.014"
Truth table33%1/3
A and B
A= $data->{"\$numberDouble"} eq "-0"B= $] lt "5.014"
ABresult
0X0
100
111
692 0 $data->{'$numberDouble'} = '-0.0';
693 }
694 28 return BSON::Double->new( value => $data->{'$numberDouble'} );
695 }
696  
697 36 ▶ if ( exists $data->{'$symbol'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{"\$symbol"}) 12 24 36
698 12 return BSON::Symbol->new(value => $data->{'$symbol'});
699 }
700  
701 24 for my $key (keys %$data) {
702 14 my $value = $data->{$key};
703 14 $data->{$key} = $class->_extjson_to_perl($value);
704 }
705 24 return $data;
706 }
707  
708 76 ▶ if (ref $data eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "ARRAY") 10 66 76
709 10 for my $index (0 .. $#$data) {
710 16 my $value = $data->[$index];
711 16 ▶ $data->[$index] = ref($value)
Branch: 1 branch
BranchTrueFalseTotal
ref $value ? : 16 0 16
712 ? $class->_extjson_to_perl($value)
713 : $value;
714 }
715 10 return $data;
716 }
717  
718 66 return $data;
719 }
720  
721 #--------------------------------------------------------------------------#
722 # legacy functional interface
723 #--------------------------------------------------------------------------#
724  
725 #pod =func encode
726 #pod
727 #pod my $bson = encode({ bar => 'foo' }, \%options);
728 #pod
729 #pod This is the legacy, functional interface and is only exported on demand.
730 #pod It takes a hashref and returns a BSON string.
731 #pod It uses an internal codec singleton with default attributes.
732 #pod
733 #pod =func decode
734 #pod
735 #pod my $hash = decode( $bson, \%options );
736 #pod
737 #pod This is the legacy, functional interface and is only exported on demand.
738 #pod It takes a BSON string and returns a hashref.
739 #pod It uses an internal codec singleton with default attributes.
740 #pod
741 #pod =cut
742  
743 {
744 71 my $CODEC;
745  
746 sub encode {
747 732 ▶ if ( defined $_[0] && ( $_[0] eq 'BSON' || ( blessed($_[0]) && $_[0]->isa('BSON') ) ) ) {
Subroutine encode: called CC=9 SCAR=25.4
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_[0] and $_[0] eq "BSON" || builtin::blessed($_[0]) && $_[0]->isa("BSON")) 0 732 732
Condition44%4/9
defined $_[0] and $_[0] eq "BSON" || builtin::blessed($_[0]) && $_[0]->isa("BSON")
!ll&&!rl&&r
07320
$_[0] eq "BSON" or builtin::blessed($_[0]) and $_[0]->isa("BSON")
l!l&&r!l&&!r
00732
builtin::blessed($_[0]) and $_[0]->isa("BSON")
!ll&&!rl&&r
715170
MC/DC0%0/4
defined $_[0] and $_[0] eq "BSON" || builtin::blessed($_[0]) && $_[0]->isa("BSON")
defined $_[0] $_[0] eq "BSON" builtin::blessed($_[0]) $_[0]->isa("BSON")
Truth table40%2/5
A and B or C and D
A= defined $_[0]B= $_[0] eq "BSON"C= builtin::blessed($_[0])D= $_[0]->isa("BSON")
ABCDresult
0XXX0
100X0
10100
11XX1
10111
748 0 Carp::croak("Error: 'encode' is a function, not a method");
749 }
750 732 my $doc = shift;
751 732 ▶ $CODEC = BSON->new unless defined $CODEC;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $CODEC 20 712 732
752 732 ▶ if ( @_ == 1 && ref( $_[0] ) eq 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_ == 1 and ref $_[0] eq 'HASH') { } 101 631 732
elsif (@_ % 2 == 0) { } 631 0 631
Condition66%2/3
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
6310101
MC/DC50%1/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table66%2/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
753 101 return $CODEC->encode_one( $doc, $_[0] );
754 }
755 elsif ( @_ % 2 == 0 ) {
756 631 return $CODEC->encode_one( $doc, {@_} );
757 }
758 else {
759 0 Carp::croak("Options for 'encode' must be a hashref or key-value pairs");
760 }
761 }
762  
763 sub decode {
764 690 ▶ if ( defined $_[0] && ( $_[0] eq 'BSON' || ( blessed($_[0]) && $_[0]->isa('BSON') ) ) ) {
Subroutine decode: called CC=11 SCAR=29.8
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_[0] and $_[0] eq "BSON" || builtin::blessed($_[0]) && $_[0]->isa("BSON")) 0 690 690
Condition33%3/9
defined $_[0] and $_[0] eq "BSON" || builtin::blessed($_[0]) && $_[0]->isa("BSON")
!ll&&!rl&&r
06900
$_[0] eq "BSON" or builtin::blessed($_[0]) and $_[0]->isa("BSON")
l!l&&r!l&&!r
00690
builtin::blessed($_[0]) and $_[0]->isa("BSON")
!ll&&!rl&&r
69000
MC/DC0%0/4
defined $_[0] and $_[0] eq "BSON" || builtin::blessed($_[0]) && $_[0]->isa("BSON")
defined $_[0] $_[0] eq "BSON" builtin::blessed($_[0]) $_[0]->isa("BSON")
Truth table0%0/5
A and B or C and D
A= defined $_[0]B= $_[0] eq "BSON"C= builtin::blessed($_[0])D= $_[0]->isa("BSON")
ABCDresult
0XXX0
100X0
10100
11XX1
10111
765 0 Carp::croak("Error: 'decode' is a function, not a method");
766 }
767 690 my $doc = shift;
768 690 ▶ $CODEC = BSON->new unless defined $CODEC;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $CODEC 18 672 690
769 690 my $args;
770 690 ▶ if ( @_ == 1 && ref( $_[0] ) eq 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_ == 1 and ref $_[0] eq 'HASH') { } 0 690 690
elsif (@_ % 2 == 0) { } 690 0 690
Condition33%1/3
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
69000
MC/DC0%0/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table33%1/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
771 0 $args = shift;
772 }
773 elsif ( @_ % 2 == 0 ) {
774 690 $args = { @_ };
775 }
776 else {
777 0 Carp::croak("Options for 'decode' must be a hashref or key-value pairs");
778 }
779 $args->{ordered} = delete $args->{ixhash}
780 690 ▶ if exists $args->{ixhash} && !exists $args->{ordered};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args->{"ixhash"} and not exists $args->{"ordered"} 1 689 690
Condition66%2/3
exists $args->{"ixhash"} and not exists $args->{"ordered"}
!ll&&!rl&&r
68901
MC/DC50%1/2
exists $args->{"ixhash"} and not exists $args->{"ordered"}
exists $args->{"ixhash"} not exists $args->{"ordered"}
Truth table66%2/3
A and not(B)
A= exists $args->{"ixhash"}B= not exists $args->{"ordered"}
ABresult
0X0
100
111
781 690 return $CODEC->decode_one( $doc, $args );
782 }
783 }
784  
785 #--------------------------------------------------------------------------#
786 # private functions
787 #--------------------------------------------------------------------------#
788  
789 71 sub _inflate_hash {
790 0 ▶ my ( $class, $hash ) = @_;
Subroutine _inflate_hash: not called CC=24 SCAR=64.0
791  
792 0 ▶ if ( exists $hash->{'$oid'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$oid"}) 0 0 0
793 0 return BSON::OID->new( oid => pack( "H*", $hash->{'$oid'} ) );
794 }
795  
796 0 ▶ if ( exists $hash->{'$numberInt'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$numberInt"}) 0 0 0
797 0 return BSON::Int32->new( value => $hash->{'$numberInt'} );
798 }
799  
800 0 ▶ if ( exists $hash->{'$numberLong'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$numberLong"}) 0 0 0
801 0 if (HAS_INT64) {
802 0 return BSON::Int64->new( value => $hash->{'$numberLong'} );
803 }
804 else {
805 return BSON::Int64->new( value => Math::BigInt->new($hash->{'$numberLong'}) );
806 }
807 }
808  
809 0 ▶ if ( exists $hash->{'$binary'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$binary"}) 0 0 0
810 0 require MIME::Base64;
811 return BSON::Bytes->new(
812 data => MIME::Base64::decode_base64($hash->{'$binary'}),
813 0 ▶ subtype => hex( $hash->{'$type'} || 0 )
Condition0%0/2
$hash->{'$type'} || 0
l!l
00
MC/DC0%0/1
$hash->{'$type'} || 0
$hash->{'$type'}
Truth table0%0/2
A
A= $hash->{'$type'}
Aresult
11
00
814 );
815 }
816  
817 0 ▶ if ( exists $hash->{'$date'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$date"}) 0 0 0
818 0 my $v = $hash->{'$date'};
819 0 ▶ $v = ref($v) eq 'HASH' ? BSON->_inflate_hash($v) : _iso8601_to_epochms($v);
Branch: 1 branch
BranchTrueFalseTotal
ref $v eq 'HASH' ? : 0 0 0
820 0 return BSON::Time->new( value => $v );
821 }
822  
823 0 ▶ if ( exists $hash->{'$minKey'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$minKey"}) 0 0 0
824 0 return BSON::MinKey->new;
825 }
826  
827 0 ▶ if ( exists $hash->{'$maxKey'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$maxKey"}) 0 0 0
828 0 return BSON::MaxKey->new;
829 }
830  
831 0 ▶ if ( exists $hash->{'$timestamp'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$timestamp"}) 0 0 0
832 return BSON::Timestamp->new(
833 seconds => $hash->{'$timestamp'}{t},
834 increment => $hash->{'$timestamp'}{i},
835 0 );
836 }
837  
838 0 ▶ if ( exists $hash->{'$regex'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$regex"}) 0 0 0
839 return BSON::Regex->new(
840 pattern => $hash->{'$regex'},
841 0 ▶ ( exists $hash->{'$options'} ? ( flags => $hash->{'$options'} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
exists $hash->{'$options'} ? : 0 0 0
842 );
843 }
844  
845 0 ▶ if ( exists $hash->{'$code'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$code"}) 0 0 0
846 return BSON::Code->new(
847 code => $hash->{'$code'},
848 0 ▶ ( exists $hash->{'$scope'} ? ( scope => $hash->{'$scope'} ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
exists $hash->{'$scope'} ? : 0 0 0
849 );
850 }
851  
852 0 ▶ if ( exists $hash->{'$undefined'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$undefined"}) 0 0 0
853 0 return undef; ## no critic
854 }
855  
856 0 ▶ if ( exists $hash->{'$ref'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$ref"}) 0 0 0
857 0 my $id = $hash->{'$id'};
858 0 ▶ $id = BSON->_inflate_hash($id) if ref($id) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $id eq "HASH" 0 0 0
859 0 return BSON::DBRef->new( '$ref' => $hash->{'$ref'}, '$id' => $id );
860 }
861  
862 0 ▶ if ( exists $hash->{'$numberDecimal'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$numberDecimal"}) 0 0 0
863 0 return BSON::Decimal128->new( value => $hash->{'$numberDecimal'} );
864 }
865  
866 # Following extended JSON is non-standard
867  
868 0 ▶ if ( exists $hash->{'$numberDouble'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$numberDouble"}) 0 0 0
869 0 ▶ if ( $hash->{'$numberDouble'} eq '-0' && $] lt '5.014' && ! HAS_LD ) {
Branch: 1 branch
BranchTrueFalseTotal
if () 0 0 0
Condition0%0/5
$hash->{"\$numberDouble"} eq "-0" and $] lt "5.014" and
!ll
00
$hash->{"\$numberDouble"} eq "-0" and $] lt "5.014"
!ll&&!rl&&r
000
MC/DC0%0/2
$hash->{"\$numberDouble"} eq "-0" and $] lt "5.014" and
$hash->{"\$numberDouble"} eq "-0" $] lt "5.014"
Truth table0%0/3
A and B
A= $hash->{"\$numberDouble"} eq "-0"B= $] lt "5.014"
ABresult
0X0
100
111
870 0 $hash->{'$numberDouble'} = '-0.0';
871 }
872 0 return BSON::Double->new( value => $hash->{'$numberDouble'} );
873 }
874  
875 0 ▶ if ( exists $hash->{'$symbol'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"\$symbol"}) 0 0 0
876 0 return $hash->{'$symbol'};
877 }
878  
879 0 return $hash;
880 }
881  
882 sub _inflate_array {
883 0 ▶ my ($class, $array) = @_;
Subroutine _inflate_array: not called CC=5 SCAR=34.0
884 0 ▶ if (@$array) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$array) 0 0 0
885 0 for my $i ( 0 .. $#$array ) {
886 0 my $v = $array->[$i];
887 0 ▶ $array->[$i] =
Branch: 2 branches
BranchTrueFalseTotal
ref $v eq 'HASH' ? : 0 0 0
ref $v eq 'ARRAY' ? : 0 0 0
888 ref($v) eq 'HASH' ? BSON->_inflate_hash($v)
889 : ref($v) eq 'ARRAY' ? _inflate_array($v)
890 : $v;
891 }
892 }
893 0 return $array;
894 }
895  
896 71 my $iso8601_re = qr{
897 (\d{4}) - (\d{2}) - (\d{2}) T # date
898 (\d{2}) : (\d{2}) : ( \d+ (?:\. \d+ )? ) # time
899 (?: Z | ([+-] \d{2} :? (?: \d{2} )? ) )? # maybe TZ
900 }x;
901  
902 sub _iso8601_to_epochms {
903 2 ▶ my ($date) = shift;
Subroutine _iso8601_to_epochms: called CC=7 SCAR=25.3
904 2 require Time::Local;
905  
906 2 my $zone_offset = 0;;
907 2 ▶ if ( substr($date,-1,1) eq 'Z' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($date, -1, 1) eq "Z") 2 0 2
908 2 chop($date);
909 }
910  
911 2 ▶ if ( $date =~ /\A$iso8601_re\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($date =~ /\A$iso8601_re\z/) { } 2 0 2
912 2 my ($Y,$M,$D,$h,$m,$s,$z) = ($1,$2-1,$3,$4,$5,$6,$7);
913 2 ▶ if (defined($z) && length($z)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $z and length $z) 0 2 2
Condition33%1/3
defined $z and length $z
!ll&&!rl&&r
200
MC/DC0%0/2
defined $z and length $z
defined $z length $z
Truth table33%1/3
A and B
A= defined $zB= length $z
ABresult
0X0
100
111
914 0 $z =~ tr[:][];
915 0 ▶ $z .= "00" if length($z) < 5;
Branch: 1 branch
BranchTrueFalseTotal
if length $z < 5 0 0 0
916 0 my $zd = substr($z,0,1);
917 0 my $zh = substr($z,1,2);
918 0 my $zm = substr($z,3,2);
919 0 ▶ $zone_offset = ($zd eq '-' ? -1 : 1 ) * (3600 * $zh + 60 * $zm);
Branch: 1 branch
BranchTrueFalseTotal
$zd eq '-' ? : 0 0 0
920 }
921 2 my $frac = $s - int($s);
922 2 my $epoch = Time::Local::timegm(int($s), $m, $h, $D, $M, $Y) - $zone_offset;
923 2 $epoch = HAS_INT64 ? 1000 * $epoch : Math::BigInt->new($epoch) * 1000;
924 2 $epoch += HAS_INT64 ? $frac * 1000 : Math::BigFloat->new($frac) * 1000;
925 2 return $epoch;
926 }
927 else {
928 0 Carp::croak("Couldn't parse '\$date' field: $date\n");
929 }
930 }
931  
932 71 1;
933  
934 =pod
935  
936 =encoding UTF-8
937  
938 =head1 NAME
939  
940 BSON - BSON serialization and deserialization
941  
942 =head1 VERSION
943  
944 version v1.12.0
945  
946 =head1 SYNOPSIS
947  
948 use BSON;
949 use BSON::Types ':all';
950 use boolean;
951  
952 my $codec = BSON->new;
953  
954 my $document = {
955 _id => bson_oid(),
956 creation_time => bson_time(), # now
957 zip_code => bson_string("08544"),
958 hidden => false,
959 };
960  
961 my $bson = $codec->encode_one( $document );
962 my $doc = $codec->decode_one( $bson );
963  
964 =head1 DESCRIPTION
965  
966 This class implements a BSON encoder/decoder ("codec"). It consumes
967 "documents" (typically hash references) and emits BSON strings and vice
968 versa in accordance with the L<BSON Specification|http://bsonspec.org>.
969  
970 BSON is the primary data representation for L<MongoDB>. While this module
971 has several features that support MongoDB-specific needs and conventions,
972 it can be used as a standalone serialization format.
973  
974 The codec may be customized through attributes on the codec option as well
975 as encode/decode specific options on methods:
976  
977 my $codec = BSON->new( \%global_attributes );
978  
979 my $bson = $codec->encode_one( $document, \%encode_options );
980 my $doc = $codec->decode_one( $bson , \%decode_options );
981  
982 Because BSON is strongly-typed and Perl is not, this module supports
983 a number of "type wrappers" – classes that wrap Perl data to indicate how
984 they should serialize. The L<BSON::Types> module describes these and
985 provides associated helper functions. See L</PERL-BSON TYPE MAPPING>
986 for more details.
987  
988 When decoding, type wrappers are used for any data that has no native Perl
989 representation. Optionally, all data may be wrapped for precise control of
990 round-trip encoding.
991  
992 Please read the configuration attributes carefully to understand more about
993 how to control encoding and decoding.
994  
995 At compile time, this module will select an implementation backend. It
996 will prefer C<BSON::XS> (released separately) if available, or will fall
997 back to L<BSON::PP> (bundled with this module). See L</ENVIRONMENT> for
998 a way to control the selection of the backend.
999  
1000 =head1 ATTRIBUTES
1001  
1002 =head2 error_callback
1003  
1004 This attribute specifies a function reference that will be called with
1005 three positional arguments:
1006  
1007 =over 4
1008  
1009 =item *
1010  
1011 an error string argument describing the error condition
1012  
1013 =item *
1014  
1015 a reference to the problematic document or byte-string
1016  
1017 =item *
1018  
1019 the method in which the error occurred (e.g. C<encode_one> or C<decode_one>)
1020  
1021 =back
1022  
1023 Note: for decoding errors, the byte-string is passed as a reference to avoid
1024 copying possibly large strings.
1025  
1026 If not provided, errors messages will be thrown with C<Carp::croak>.
1027  
1028 =head2 invalid_chars
1029  
1030 A string containing ASCII characters that must not appear in keys. The default
1031 is the empty string, meaning there are no invalid characters.
1032  
1033 =head2 max_length
1034  
1035 This attribute defines the maximum document size. The default is 0, which
1036 disables any maximum.
1037  
1038 If set to a positive number, it applies to both encoding B<and> decoding (the
1039 latter is necessary for prevention of resource consumption attacks).
1040  
1041 =head2 op_char
1042  
1043 This is a single character to use for special MongoDB-specific query
1044 operators. If a key starts with C<op_char>, the C<op_char> character will
1045 be replaced with "$".
1046  
1047 The default is "$", meaning that no replacement is necessary.
1048  
1049 =head2 ordered
1050  
1051 If set to a true value, then decoding will return a reference to a tied
1052 hash that preserves key order. Otherwise, a regular (unordered) hash
1053 reference will be returned.
1054  
1055 B<IMPORTANT CAVEATS>:
1056  
1057 =over 4
1058  
1059 =item *
1060  
1061 When 'ordered' is true, users must not rely on the return value being any particular tied hash implementation. It may change in the future for efficiency.
1062  
1063 =item *
1064  
1065 Turning this option on entails a significant speed penalty as tied hashes are slower than regular Perl hashes.
1066  
1067 =back
1068  
1069 The default is false.
1070  
1071 =head2 prefer_numeric
1072  
1073 When false, scalar values will be encoded as a number if they were
1074 originally a number or were ever used in a numeric context. However, a
1075 string that looks like a number but was never used in a numeric context
1076 (e.g. "42") will be encoded as a string.
1077  
1078 If C<prefer_numeric> is set to true, the encoder will attempt to coerce
1079 strings that look like a number into a numeric value. If the string
1080 doesn't look like a double or integer, it will be encoded as a string.
1081  
1082 B<IMPORTANT CAVEAT>: the heuristics for determining whether something is a
1083 string or number are less accurate on older Perls. See L<BSON::Types>
1084 for wrapper classes that specify exact serialization types.
1085  
1086 The default is false.
1087  
1088 =head2 wrap_dbrefs
1089  
1090 If set to true, during decoding, documents with the fields C<'$id'> and
1091 C<'$ref'> (literal dollar signs, not variables) will be wrapped as
1092 L<BSON::DBRef> objects. If false, they are decoded into ordinary hash
1093 references (or ordered hashes, if C<ordered> is true).
1094  
1095 The default is true.
1096  
1097 =head2 wrap_numbers
1098  
1099 If set to true, during decoding, numeric values will be wrapped into
1100 BSON type-wrappers: L<BSON::Double>, L<BSON::Int64> or L<BSON::Int32>.
1101 While very slow, this can help ensure fields can round-trip if unmodified.
1102  
1103 The default is false.
1104  
1105 =head2 wrap_strings
1106  
1107 If set to true, during decoding, string values will be wrapped into a BSON
1108 type-wrappers, L<BSON::String>. While very slow, this can help ensure
1109 fields can round-trip if unmodified.
1110  
1111 The default is false.
1112  
1113 =head2 dt_type (Discouraged)
1114  
1115 Sets the type of object which is returned for BSON DateTime fields. The
1116 default is C<undef>, which returns objects of type L<BSON::Time>. This is
1117 overloaded to be the integer epoch value when used as a number or string,
1118 so is somewhat backwards compatible with C<dt_type> in the L<MongoDB>
1119 driver.
1120  
1121 Other acceptable values are L<BSON::Time> (explicitly), L<DateTime>,
1122 L<Time::Moment>, L<DateTime::Tiny>, L<Mango::BSON::Time>.
1123  
1124 Because BSON::Time objects have methods to convert to DateTime,
1125 Time::Moment or DateTime::Tiny, use of this field is discouraged. Users
1126 should use these methods on demand. This option is provided for backwards
1127 compatibility only.
1128  
1129 =head1 METHODS
1130  
1131 =head2 encode_one
1132  
1133 $byte_string = $codec->encode_one( $doc );
1134 $byte_string = $codec->encode_one( $doc, \%options );
1135  
1136 Takes a "document", typically a hash reference, an array reference, or a
1137 Tie::IxHash object and returns a byte string with the BSON representation of
1138 the document.
1139  
1140 An optional hash reference of options may be provided. Valid options include:
1141  
1142 =over 4
1143  
1144 =item *
1145  
1146 first_key – if C<first_key> is defined, it and C<first_value> will be encoded first in the output BSON; any matching key found in the document will be ignored.
1147  
1148 =item *
1149  
1150 first_value - value to assign to C<first_key>; will encode as Null if omitted
1151  
1152 =item *
1153  
1154 error_callback – overrides codec default
1155  
1156 =item *
1157  
1158 invalid_chars – overrides codec default
1159  
1160 =item *
1161  
1162 max_length – overrides codec default
1163  
1164 =item *
1165  
1166 op_char – overrides codec default
1167  
1168 =item *
1169  
1170 prefer_numeric – overrides codec default
1171  
1172 =back
1173  
1174 =head2 decode_one
1175  
1176 $doc = $codec->decode_one( $byte_string );
1177 $doc = $codec->decode_one( $byte_string, \%options );
1178  
1179 Takes a byte string with a BSON-encoded document and returns a
1180 hash reference representing the decoded document.
1181  
1182 An optional hash reference of options may be provided. Valid options include:
1183  
1184 =over 4
1185  
1186 =item *
1187  
1188 dt_type – overrides codec default
1189  
1190 =item *
1191  
1192 error_callback – overrides codec default
1193  
1194 =item *
1195  
1196 max_length – overrides codec default
1197  
1198 =item *
1199  
1200 ordered - overrides codec default
1201  
1202 =item *
1203  
1204 wrap_dbrefs - overrides codec default
1205  
1206 =item *
1207  
1208 wrap_numbers - overrides codec default
1209  
1210 =item *
1211  
1212 wrap_strings - overrides codec default
1213  
1214 =back
1215  
1216 =head2 clone
1217  
1218 $copy = $codec->clone( ordered => 1 );
1219  
1220 Constructs a copy of the original codec, but allows changing
1221 attributes in the copy.
1222  
1223 =head2 create_oid
1224  
1225 $oid = BSON->create_oid;
1226  
1227 This class method returns a new L<BSON::OID>. This abstracts OID
1228 generation away from any specific Object ID class and makes it an interface
1229 on a BSON codec. Alternative BSON codecs should define a similar class
1230 method that returns an Object ID of whatever type is appropriate.
1231  
1232 =head2 inflate_extjson (DEPRECATED)
1233  
1234 This legacy method does not follow the L<MongoDB Extended JSON|https://github.com/mongodb/specifications/blob/master/source/extended-json.rst>
1235 specification.
1236  
1237 Use L</extjson_to_perl> instead.
1238  
1239 =head2 perl_to_extjson
1240  
1241 use JSON::MaybeXS;
1242 my $ext = BSON->perl_to_extjson($data, \%options);
1243 my $json = encode_json($ext);
1244  
1245 Takes a perl data structure (i.e. hashref) and turns it into an
1246 L<MongoDB Extended JSON|https://github.com/mongodb/specifications/blob/master/source/extended-json.rst>
1247 structure. Note that the structure will still have to be serialized.
1248  
1249 Possible options are:
1250  
1251 =over 4
1252  
1253 =item *
1254  
1255 C<relaxed> A boolean indicating if "relaxed extended JSON" should
1256  
1257 be generated. If not set, the default value is taken from the
1258 C<BSON_EXTJSON_RELAXED> environment variable.
1259  
1260 =back
1261  
1262 =head2 extjson_to_perl
1263  
1264 use JSON::MaybeXS;
1265 my $ext = decode_json($json);
1266 my $data = $bson->extjson_to_perl($ext);
1267  
1268 Takes an
1269 L<MongoDB Extended JSON|https://github.com/mongodb/specifications/blob/master/source/extended-json.rst>
1270 data structure and inflates it into a Perl data structure. Note that
1271 you have to decode the JSON string manually beforehand.
1272  
1273 Canonically specified numerical values like C<{"$numberInt":"23"}> will
1274 be inflated into their respective C<BSON::*> wrapper types. Plain numeric
1275 values will be left as-is.
1276  
1277 =head1 FUNCTIONS
1278  
1279 =head2 encode
1280  
1281 my $bson = encode({ bar => 'foo' }, \%options);
1282  
1283 This is the legacy, functional interface and is only exported on demand.
1284 It takes a hashref and returns a BSON string.
1285 It uses an internal codec singleton with default attributes.
1286  
1287 =head2 decode
1288  
1289 my $hash = decode( $bson, \%options );
1290  
1291 This is the legacy, functional interface and is only exported on demand.
1292 It takes a BSON string and returns a hashref.
1293 It uses an internal codec singleton with default attributes.
1294  
1295 =for Pod::Coverage BUILD
1296  
1297 =head1 PERL-BSON TYPE MAPPING
1298  
1299 BSON has numerous data types and Perl does not.
1300  
1301 When B<decoding>, each BSON type should result in a single, predictable
1302 Perl type. Where no native Perl type is appropriate, BSON decodes to an
1303 object of a particular class (a "type wrapper").
1304  
1305 When B<encoding>, for historical reasons, there may be many Perl
1306 representations that should encode to a particular BSON type. For example,
1307 all the popular "boolean" type modules on CPAN should encode to the BSON
1308 boolean type. Likewise, as this module is intended to supersede the
1309 type wrappers that have shipped with the L<MongoDB> module, those
1310 type wrapper are supported by this codec.
1311  
1312 The table below describes the BSON/Perl mapping for both encoding and
1313 decoding.
1314  
1315 On the left are all the Perl types or classes this BSON codec
1316 knows how to serialize to BSON. The middle column is the BSON type for
1317 each class. The right-most column is the Perl type or class that the BSON
1318 type deserializes to. Footnotes indicate variations or special behaviors.
1319  
1320 Perl type/class -> BSON type -> Perl type/class
1321 -------------------------------------------------------------------
1322 float[1] 0x01 DOUBLE float[2]
1323 BSON::Double
1324 -------------------------------------------------------------------
1325 string[3] 0x02 UTF8 string[2]
1326 BSON::String
1327 -------------------------------------------------------------------
1328 hashref 0x03 DOCUMENT hashref[4][5]
1329 BSON::Doc
1330 BSON::Raw
1331 MongoDB::BSON::Raw[d]
1332 Tie::IxHash
1333 -------------------------------------------------------------------
1334 arrayref 0x04 ARRAY arrayref
1335 -------------------------------------------------------------------
1336 BSON::Bytes 0x05 BINARY BSON::Bytes
1337 scalarref
1338 BSON::Binary[d]
1339 MongoDB::BSON::Binary[d]
1340 -------------------------------------------------------------------
1341 n/a 0x06 UNDEFINED[d] undef
1342 -------------------------------------------------------------------
1343 BSON::OID 0x07 OID BSON::OID
1344 BSON::ObjectId[d]
1345 MongoDB::OID[d]
1346 -------------------------------------------------------------------
1347 boolean 0x08 BOOL boolean
1348 BSON::Bool[d]
1349 JSON::XS::Boolean
1350 JSON::PP::Boolean
1351 JSON::Tiny::_Bool
1352 Mojo::JSON::_Bool
1353 Cpanel::JSON::XS::Boolean
1354 Types::Serialiser::Boolean
1355 -------------------------------------------------------------------
1356 BSON::Time 0x09 DATE_TIME BSON::Time
1357 DateTime
1358 DateTime::Tiny
1359 Time::Moment
1360 Mango::BSON::Time
1361 -------------------------------------------------------------------
1362 undef 0x0a NULL undef
1363 -------------------------------------------------------------------
1364 BSON::Regex 0x0b REGEX BSON::Regex
1365 qr// reference
1366 MongoDB::BSON::Regexp[d]
1367 -------------------------------------------------------------------
1368 n/a 0x0c DBPOINTER[d] BSON::DBRef
1369 -------------------------------------------------------------------
1370 BSON::Code[6] 0x0d CODE BSON::Code
1371 MongoDB::Code[6]
1372 -------------------------------------------------------------------
1373 n/a 0x0e SYMBOL[d] string
1374 -------------------------------------------------------------------
1375 BSON::Code[6] 0x0f CODEWSCOPE BSON::Code
1376 MongoDB::Code[6]
1377 -------------------------------------------------------------------
1378 integer[7][8] 0x10 INT32 integer[2]
1379 BSON::Int32
1380 -------------------------------------------------------------------
1381 BSON::Timestamp 0x11 TIMESTAMP BSON::Timestamp
1382 MongoDB::Timestamp[d]
1383 -------------------------------------------------------------------
1384 integer[7] 0x12 INT64 integer[2][9]
1385 BSON::Int64
1386 Math::BigInt
1387 Math::Int64
1388 -------------------------------------------------------------------
1389 BSON::MaxKey 0x7F MAXKEY BSON::MaxKey
1390 MongoDB::MaxKey[d]
1391 -------------------------------------------------------------------
1392 BSON::MinKey 0xFF MINKEY BSON::MinKey
1393 MongoDB::MinKey[d]
1394  
1395 [d] Deprecated or soon to be deprecated.
1396 [1] Scalar with "NV" internal representation or a string that looks
1397 like a float if the 'prefer_numeric' option is true.
1398 [2] If the 'wrap_numbers' option is true, numeric types will be wrapped
1399 as BSON::Double, BSON::Int32 or BSON::Int64 as appropriate to ensure
1400 round-tripping. If the 'wrap_strings' option is true, strings will
1401 be wrapped as BSON::String, likewise.
1402 [3] Scalar without "NV" or "IV" representation and not identified as a
1403 number by notes [1] or [7].
1404 [4] If 'ordered' option is set, will return a tied hash that preserves
1405 order (deprecated 'ixhash' option still works).
1406 [5] If the document appears to contain a DBRef and a 'dbref_callback'
1407 exists, that callback is executed with the deserialized document.
1408 [6] Code is serialized as CODE or CODEWSCOPE depending on whether a
1409 scope hashref exists in BSON::Code/MongoDB::Code.
1410 [7] Scalar with "IV" internal representation or a string that looks like
1411 an integer if the 'prefer_numeric' option is true.
1412 [8] Only if the integer fits in 32 bits.
1413 [9] On 32-bit platforms, 64-bit integers are deserialized to
1414 Math::BigInt objects (even if subsequently wrapped into
1415 BSON::Int64 if 'wrap_scalars' is true).
1416  
1417 =head1 THREADS
1418  
1419 Threads are never recommended in Perl, but this module is thread safe.
1420  
1421 =head1 ENVIRONMENT
1422  
1423 =over 4
1424  
1425 =item *
1426  
1427 PERL_BSON_BACKEND – if set at compile time, this will be treated as a module name. The module will be loaded and used as the BSON backend implementation. It must implement the same API as C<BSON::PP>.
1428  
1429 =item *
1430  
1431 BSON_EXTJSON - if set, serializing BSON type wrappers via C<TO_JSON> will produce Extended JSON v2 output.
1432  
1433 =item *
1434  
1435 BSON_EXTJSON_RELAXED - if producing Extended JSON output, if this is true, values will use the "Relaxed" form of Extended JSON, which sacrifices type round-tripping for improved human readability.
1436  
1437 =back
1438  
1439 =head1 SEMANTIC VERSIONING SCHEME
1440  
1441 Starting with BSON C<v0.999.0>, this module is using a "tick-tock"
1442 three-part version-tuple numbering scheme: C<vX.Y.Z>
1443  
1444 =over 4
1445  
1446 =item *
1447  
1448 In stable releases, C<X> will be incremented for incompatible API changes.
1449  
1450 =item *
1451  
1452 Even-value increments of C<Y> indicate stable releases with new functionality. C<Z> will be incremented for bug fixes.
1453  
1454 =item *
1455  
1456 Odd-value increments of C<Y> indicate unstable ("development") releases that should not be used in production. C<Z> increments have no semantic meaning; they indicate only successive development releases. Development releases may have API-breaking changes, usually indicated by C<Y> equal to "999".
1457  
1458 =back
1459  
1460 =head1 HISTORY AND ROADMAP
1461  
1462 This module was originally written by Stefan G. In 2014, he graciously
1463 transferred ongoing maintenance to MongoDB, Inc.
1464  
1465 The C<bson_xxxx> helper functions in L<BSON::Types> were inspired by similar
1466 work in L<Mango::BSON> by Sebastian Riedel.
1467  
1468 =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
1469  
1470 =head1 SUPPORT
1471  
1472 =head2 Bugs / Feature Requests
1473  
1474 Please report any bugs or feature requests through the issue tracker
1475 at L<https://jira.mongodb.org/browse/PERL>.
1476 You will be notified automatically of any progress on your issue.
1477  
1478 =head2 Source Code
1479  
1480 This is open source software. The code repository is available for
1481 public review and contribution under the terms of the license.
1482  
1483 L<https://github.com/mongodb/mongo-perl-bson>
1484  
1485 git clone https://github.com/mongodb/mongo-perl-bson.git
1486  
1487 =head1 AUTHORS
1488  
1489 =over 4
1490  
1491 =item *
1492  
1493 David Golden <david@mongodb.com>
1494  
1495 =item *
1496  
1497 Stefan G. <minimalist@lavabit.com>
1498  
1499 =back
1500  
1501 =head1 CONTRIBUTORS
1502  
1503 =for stopwords Eric Daniels Finn Olivier Duclos Pat Gunn Petr Písař Robert Sedlacek Thomas Bloor Tobias Leich Wallace Reis Yury Zavarin Oleg Kostyuk
1504  
1505 =over 4
1506  
1507 =item *
1508  
1509 Eric Daniels <eric.daniels@mongodb.com>
1510  
1511 =item *
1512  
1513 Finn <toyou1995@gmail.com>
1514  
1515 =item *
1516  
1517 Olivier Duclos <odc@cpan.org>
1518  
1519 =item *
1520  
1521 Pat Gunn <pgunn@mongodb.com>
1522  
1523 =item *
1524  
1525 Petr Písař <ppisar@redhat.com>
1526  
1527 =item *
1528  
1529 Robert Sedlacek <rs@474.at>
1530  
1531 =item *
1532  
1533 Thomas Bloor <tbsliver@shadow.cat>
1534  
1535 =item *
1536  
1537 Tobias Leich <email@froggs.de>
1538  
1539 =item *
1540  
1541 Wallace Reis <wallace@reis.me>
1542  
1543 =item *
1544  
1545 Yury Zavarin <yury.zavarin@gmail.com>
1546  
1547 =item *
1548  
1549 Oleg Kostyuk <cub@cpan.org>
1550  
1551 =back
1552  
1553 =head1 COPYRIGHT AND LICENSE
1554  
1555 This software is Copyright (c) 2019 by Stefan G. and MongoDB, Inc.
1556  
1557 This is free software, licensed under:
1558  
1559 The Apache License, Version 2.0, January 2004
1560  
1561 =cut
1562  
1563 __END__
↑ Summary BSON/PP.pm »