blib/lib/PDF/Tiny.pm

filter: Statementstmt 84.2% 528 / 627 Branchbran 63.6% 256 / 402 Conditioncond 61.7% 87 / 141 MC/DCmcdc 32.0% 25 / 78 Subroutinesub 86.6% 39 / 45 Podpod 0.0% 0 / 31 totaltotal 70.6% 935 / 1324 SCAR 74.0
CC
285
Cov
74%
_unfilter
107.4
_flatten_pages
90.0
_interpret_token
70.1
CRAP 1640.6
↑ Summary
1 package PDF::Tiny;
2  
3 1 ▶use 5.01;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 $VERSION = '0.08'; # Update the POD, too!
6  
7 # Fields
8 sub vers () { 0 }
9 sub fh () { 1 }
10 sub trai () { 2 } # trailer
11 sub id () { 3 } # original doc ID
12 sub stxr () { 4 } # startxref, used for /Prev when appending
13 sub file () { 5 } # file name
14 sub size () { 6 } # object count + 1
15 sub free () { 7 } # array of free object ids
16  
17 # Hash fields; must be consecutive
18 sub xrft () { 8 } # xref table
19 sub mods () { 9 } # modified objects
20 sub objs () {10 }
21  
22 sub impo () {12 } # imported objects
23  
24 sub DEBUG () { 0 }
25  
26 sub croak {
27 0 ▶ die "$_[0] at " . join(' line ', (caller(DEBUG ? 0 : 1+$_[1]))[1,2])
Subroutine croak: not called CC=1 SCAR=6.9
Pod undocumented
28 . ".\n";
29 }
30  
31 1 $null = ['null'];
32  
33 1 ▶use warnings; no warnings qw 'numeric uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 # REGEXPS FOR PARSING
36  
37 1 $S = '[\0\t\cj\cl\cm ]'; # PDF whitespace chars
38 1 $_S = '[\0\t\cl ]'; #PDF whitespace chars except line breaks
39 1 $N = '(?:\cm\cj?|\cj)'; # PDF line break chars
40 1 $D = '[\(\)<>\[\]\{\}\/]'; # PDF delimiter characters (except %);
41 1 $R = '[^\0\t\cj\cl\cm \(\)<>\[\]\{\}\/%]'; # PDF regular characters
42  
43  
44 # CONSTRUCTOR
45  
46 sub new {
47 17 ▶ my $class = shift;
Subroutine new: called CC=10 SCAR=23.2
Pod undocumented
48 17 my ($file, %opts);
49 17 ▶ if (@_ == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1) { } 15 2 17
50 15 $file = shift;
51 }
52 else {
53 2 %opts = @_;
54 2 $file = $opts{filename};
55 }
56 17 my $self = [];
57 17 $self->[file] = $file;
58 17 $self->[$_] = {} for xrft..objs; # This is why they must be consecutive.
59 17 $self->[free] = [];
60 17 bless $self, $class;
61 17 ▶ if (defined $file) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file) { } 15 2 17
62 15 ▶ open my $fh, "<", $file or croak "Cannot open $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or croak("Cannot open ${file}: $!") 0 15 15
63 15 binmode $self->[fh] = $fh;
64 15 ▶ defined read $fh, my $read, 1024 or croak "Cannot read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
defined read($fh, my $read, 1024) or croak("Cannot read ${file}: $!") 0 15 15
65 15 ▶ if ($read !~ /%PDF-([0-9.]+)/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($read =~ /%PDF-([0-9.]+)/) 0 15 15
66 0 croak "The file $file is not a PDF";
67 }
68 15 $self->[vers] = $1;
69 15 _parse_xref($self);
70 15 $self->[size] = $self->[trai][1]{Size}[1];
71 15 ▶ if ($self->[trai][1]{ID}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->[2][1]{"ID"}) 11 4 15
72 11 $self->[id] = $self->[trai][1]{ID}[1][0][1];
73 }
74 }
75 else {
76 2 ▶ $self->[vers] = $opts{version} || 1.4;
Condition100%2/2
$opts{'version'} || 1.4
l!l
11
MC/DC100%1/1
$opts{'version'} || 1.4
$opts{'version'}
Truth table100%2/2
A
A= $opts{'version'}
Aresult
11
00
77 2 $self->[trai] = make_dict(my $trailer_hash = {});
78 2 ▶ if (!$opts{empty}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $opts{'empty'}) { } 2 0 2
79 2 $$trailer_hash{Root} = make_ref("1 0");
80 2 @{$self->[objs]}{"1 0","2 0"} =
81 ( make_dict({
82 Type => make_name("Catalog"), Pages => make_ref("2 0")
83 }),
84 make_dict({
85 Type => make_name("Pages"),
86 Kids => make_array([]),
87 Count => make_num(0)
88 })
89 );
90 2 $self->[size] = 3;
91 }
92 0 else { $self->[size] = 1; }
93 }
94 17 $self;
95 }
96  
97 sub _parse_xref {
98 15 ▶ my($self) = shift;
Subroutine _parse_xref: called CC=27 SCAR=34.4
99 15 my $fh = $self->[fh];
100 15 ▶ seek $fh, -1024,2 or seek $fh, 0,0;
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, -1024, 2 or seek $fh, 0, 0 2 13 15
101 15 ▶ read $fh, my $read, 1024
Branch: 1 branch
BranchTrueFalseTotal
read $fh, my $read, 1024 or croak("Cannot read $self->[5]: $!", 1) 0 15 15
102 or croak "Cannot read $self->[file]: $!", 1;
103 15 $read =~ /startxref$N(\d+)$N%%EOF$N?$/o;
104  
105 15 $self->[stxr] = my $startxref = $1;
106 15 my $xref = $self->[xrft];
107
108 15 my $trailer;
109 15 ▶ while(defined $startxref){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $startxref) 16 15 31
110 # read from the position indicated by $startxref, up to the word
111 # "startxref"
112
113 16 ▶ seek $fh, $startxref, 0
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $startxref, 0 or croak("Cannot seek in $self->[5]: $!", 1) 0 16 16
114 or croak "Cannot seek in $self->[file]: $!",1;
115 16 ▶ read $fh, my $read, 1024, length $read
Branch: 1 branch
BranchTrueFalseTotal
read $fh, my $read, 1024, length $read or croak("Cannot read $self->[5]: $!", 1) 0 16 16
116 or croak "Cannot read $self->[file]: $!", 1;
117 16 ▶ if ($read =~ /^$S*[0-9]/o) { # cross-reference stream
Branch: 1 branch
BranchTrueFalseTotal
if ($read =~ /^$S*[0-9]/o) { } 3 13 16
118 3 my $obj = _read_obj($self, $startxref);
119 3 my $stream = $self->decode_stream($obj);
120 3 $trailer = $$obj[1];
121 3 my $hash = $$trailer[1];
122 3 my @widths = map $$_[1], @{$$hash{W}[1]};
123 3 my $width = $widths[0] + $widths[1] + $widths[2];
124 3 my $unpack = join '', map "H".$_*2, @widths;
125 my @indices = $$hash{Index}
126 1 ? map $$_[1], @{$$hash{Index}[1]}
127 3 ▶ : (0, $$hash{Size}[1]);
Branch: 1 branch
BranchTrueFalseTotal
$hash->{'Index'} ? : 1 2 3
128 3 my ($ix, $last) = splice @indices, 0, 2;
129 3 $last += $ix - 1;
130 3 ▶ while (length $stream) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $stream) 33 3 36
131 33 my($type,$where,$gen)
132 = map hex,
133 unpack $unpack,
134 substr $stream, 0,
135 $width, '';
136 33 ▶ $widths[0] or $type = 1;
Branch: 1 branch
BranchTrueFalseTotal
$widths[0] or $type = 1 0 33 33
137  
138 33 ▶ if ($type == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type == 1) { } 17 16 33
elsif ($type == 2) { } 14 2 16
139 17 my $obj_ref = "$ix $gen";
140 !exists $$xref{$obj_ref}
141 17 ▶ and $$xref{$obj_ref} = $where;
Branch: 1 branch
BranchTrueFalseTotal
exists $xref->{$obj_ref} or $xref->{$obj_ref} = $where 17 0 17
142 }
143 elsif ($type == 2) {
144 14 my $obj_ref = "$ix 0";
145 !exists $$xref{$obj_ref}
146 14 ▶ and $$xref{$obj_ref} =
Branch: 1 branch
BranchTrueFalseTotal
exists $xref->{$obj_ref} or $xref->{$obj_ref} = ["$where 0", $gen] 14 0 14
147 ["$where 0", $gen];
148 }
149 else { # free
150 2 ▶ push @{$self->[free]}, "$ix $gen"
Branch: 1 branch
BranchTrueFalseTotal
if $ix and $gen != 65535 0 2 2
Condition33%1/3
$ix and $gen != 65535
!ll&&!rl&&r
200
MC/DC0%0/2
$ix and $gen != 65535
$ix $gen != 65535
Truth table33%1/3
A and B
A= $ixB= $gen != 65535
ABresult
0X0
100
111
151 if $ix && $gen != 65535
152 }
153 33 ▶ if ($ix++ > $last) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ix++ > $last) 0 33 33
154 0 ($ix, $last) = splice @indices,0,2;
155 0 $last += $ix - 1;
156 }
157 }
158 }
159 else {
160 13 ▶ while($read !~ /startxref/){
Branch: 1 branch
BranchTrueFalseTotal
unless ($read =~ /startxref/) 0 13 13
161 0 ▶ read $fh, $read, 1024, length $read
Branch: 1 branch
BranchTrueFalseTotal
read $fh, $read, 1024, length $read or croak("Cannot read $self->[5]: $!", 1) 0 0 0
162 or croak "Cannot read $self->[file]: $!", 1;
163 }
164 13 $read =~ /xref(.*?)trailer(.*)/s;
165 13 my $xreftext =$1;
166  
167 13 $trailer = parse_string("$2",qr/^startxref\z/);
168  
169 # remove initial line, and read the numbers,
170 # repeating as necessary
171  
172 13 ▶ while ($xreftext=~ s/^$N?(\d+) (\d+).*?$N//o) {
Branch: 1 branch
BranchTrueFalseTotal
if ($xreftext =~ s/^$N?(\d+) (\d+).*?$N//o) 13 13 26
173 13 for ($1..$1+$2-1) {
174 #$xreftext =~ s/(.{20})//s; # get 20 bytes
175 248 my $_1 = substr($xreftext,0,20,'');
176 248 my $obj_ref = "$_ " . substr($_1,11,5)*1;
177 248 ▶ if (substr ($_1, 17,1) eq 'n') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($_1, 17, 1) eq 'n') { } 218 30 248
178 !exists $$xref{$obj_ref}
179 218 ▶ and $$xref{$obj_ref} =
Branch: 1 branch
BranchTrueFalseTotal
exists $xref->{$obj_ref} or $xref->{$obj_ref} = substr($_1, 0, 10) 218 0 218
180 substr($_1,0,10);
181 # (See PDF Reference [5th ed.], p. 70.)
182 }
183 else { # free
184 30 ▶ push @{$self->[free]}, $obj_ref
Branch: 1 branch
BranchTrueFalseTotal
unless substr($_1, 11, 5) == 65535 17 13 30
185 unless substr($_1,11,5) == 65535
186 }
187 }
188 }
189 }
190 16 ▶ unless ($self->[trai]) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->[2]) 15 1 16
191 15 $self->[trai] = $trailer;
192 exists $$trailer[1]{Encrypt}
193 15 ▶ and croak "$self->[file] is encrypted", 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $trailer->[1]{"Encrypt"} and croak("$self->[5] is encrypted", 1) 0 15 15
194 }
195  
196 16 $trailer = $$trailer[1];
197 16 ▶ $startxref = defined $$trailer{Prev} ? $$trailer{Prev}[1] : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $trailer->{'Prev'} ? : 1 15 16
198 }
199  
200 }
201  
202 # HIGH-LEVEL METHODS
203  
204 sub page_count {
205 1 ▶ $_[0]->get_obj("/Root", "/Pages", "/Count")->[1]
Subroutine page_count: called CC=1 SCAR=0.0
Pod undocumented
206 }
207  
208 sub _walk_pages {
209 11 ▶ my $self = shift;
Subroutine _walk_pages: called CC=7 SCAR=28.0
210 11 ▶ my $pages = shift || $self->get_obj("/Root", "/Pages")
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
Condition40%2/5
shift() || $self->get_obj('/Root', '/Pages') || (return wantarray ? () : 0)
l!l
110
shift() or $self->get_obj("/Root", "/Pages")
l!l&&r!l&&!r
0110
MC/DC0%0/2
shift() || $self->get_obj('/Root', '/Pages') || (return wantarray ? () : 0)
shift() $self->get_obj("/Root", "/Pages")
Truth table33%1/3
A or B
A= shift()B= $self->get_obj("/Root", "/Pages")
ABresult
1X1
011
000
211 || return wantarray ? () : 0;
212 11 my @pages; # output
213 11 my $kids = $self->get_obj($pages, "/Kids");
214 11 ▶ if ($self->get_obj($pages, "/Count")->[1] == @{$$kids[1]}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->get_obj($pages, "/Count")->[1] == @{$kids->[1];}) 11 0 11
215 11 return @{$$kids[1]}
216 }
217 0 my $kid;
218 0 for (0 .. $#{$$kids[1]}){
219 0 $kid = $$kids[1][$_];
220 0 ▶ push @pages, ${$self->get_obj($kid, '/Type')}[1] eq 'Pages'
Branch: 1 branch
BranchTrueFalseTotal
do { $self->get_obj($kid, '/Type') }->[1] eq 'Pages' ? : 0 0 0
221 ? _walk_pages($self, $kid)
222 : $kid;
223 }
224 0 return @pages;
225 }
226  
227 sub delete_page {
228 0 ▶ my ($self, $num,) = @'_;
Subroutine delete_page: not called CC=2 SCAR=17.9
Pod undocumented
229 0 my $root = $self->get_obj("/Root");
230 0 my $pages_id = $$root[1]{Pages}[1];
231 0 my $pages = $self->get_obj($pages_id);
232 0 my $pages_array = $self->get_obj($pages, '/Kids');
233 0 my $count = $self->get_obj($pages, "/Count");
234 0 ▶ if (@{$pages_array->[1]} != $count->[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$pages_array->[1];} != $count->[1]) 0 0 0
235 # Flatten the pages array. Other structures just require too much code.
236 0 _flatten_pages($self, $pages_id, $pages, $pages_array);
237 }
238 0 splice @{$pages_array->[1]}, $num, 1;
239 0 $count->[1]--;
240 _:
241 }
242  
243 sub import_page {
244 4 ▶ my ($self, $source_pdf, $num, $whither) = @'_;
Subroutine import_page: called CC=11 SCAR=24.9
Pod undocumented
245 4 my @pages = _walk_pages($source_pdf);
246 4 ▶ my $page_to_import =
Condition33%1/3
$pages[$num] || croak("No such page: $num")
l!l&&r!l&&!r
400
MC/DC0%0/2
$pages[$num] || croak("No such page: $num")
$pages[$num] croak("No such page: $num")
Truth table33%1/3
A || B
A= $pages[$num]B= croak("No such page: $num")
ABresult
1X1
011
000
247 $source_pdf->get_obj(($pages[$num] || croak "No such page: $num")->[1]);
248  
249 # We cannot simply use import_obj. import_obj will follow the /Parent
250 # link and import the entire page tree from the source PDF.
251 # Furthermore, if the values of /Resources, /MediaBox and /CropBox are
252 # inherited from the parent node that we are not importing, they need to
253 # be transferred to the page object itself.
254 4 my $temp_copy = [@$page_to_import];
255 4 $temp_copy->[1] = {%{ $temp_copy->[1] }};
256 4 my $node = $temp_copy;
257 4 ▶ while (!$temp_copy->[1]{Resources} || !$temp_copy->[1]{MediaBox}
Branch: 1 branch
BranchTrueFalseTotal
if (not $temp_copy->[1]{"Resources"} && $temp_copy->[1]{"MediaBox"} && $temp_copy->[1]{"CropBox"} and $node->[1]{"Parent"}) 4 4 8
Condition66%6/9
not $temp_copy->[1]{"Resources"} && $temp_copy->[1]{"MediaBox"} && $temp_copy->[1]{"CropBox"} and $node->[1]{"Parent"}
!ll&&!rl&&r
044
$temp_copy->[1]{'Resources'} && $temp_copy->[1]{'MediaBox'} && $temp_copy->[1]{'CropBox'}
!ll&&!rl&&r
260
$temp_copy->[1]{"Resources"} and $temp_copy->[1]{"MediaBox"}
!ll&&!rl&&r
206
MC/DC25%1/4
not $temp_copy->[1]{"Resources"} && $temp_copy->[1]{"MediaBox"} && $temp_copy->[1]{"CropBox"} and $node->[1]{"Parent"}
$temp_copy->[1]{"Resources"} $temp_copy->[1]{"MediaBox"} $temp_copy->[1]{'CropBox'} $node->[1]{"Parent"}
Truth table57%4/7
not(A and B && C) and D
A= $temp_copy->[1]{"Resources"}B= $temp_copy->[1]{"MediaBox"}C= $temp_copy->[1]{'CropBox'}D= $node->[1]{"Parent"}
ABCDresult
111X0
0XX00
10X00
11000
0XX11
10X11
11011
258 || !$temp_copy->[1]{CropBox} and $node->[1]{Parent}) {
259 4 $node = $source_pdf->get_obj($node, '/Parent');
260 $node->[1]{$_} and !$temp_copy->[1]{$_}
261 and $temp_copy->[1]{$_} = $node->[1]{$_}
262 4 ▶ for qw< Resources MediaBox CropBox >;
Branch: 1 branch
BranchTrueFalseTotal
$node->[1]{$_} and not $temp_copy->[1]{$_} and $temp_copy->[1]{$_} = $node->[1]{$_} 0 12 12
Condition66%2/3
$node->[1]{$_} and not $temp_copy->[1]{$_}
!ll&&!rl&&r
840
MC/DC0%0/2
$node->[1]{$_} and not $temp_copy->[1]{$_}
$node->[1]{$_} not $temp_copy->[1]{$_}
Truth table66%2/3
A and not(B)
A= $node->[1]{$_}B= not $temp_copy->[1]{$_}
ABresult
0X0
100
111
263 }
264 4 delete $temp_copy->[1]{Parent};
265 4 my $page_id =
266 $self->add_obj(my $real_copy=$self->import_obj($source_pdf, $temp_copy));
267
268 4 my $root = $self->get_obj("/Root");
269 4 my $pages_id = $$root[1]{Pages}[1];
270 4 $real_copy->[1]{Parent} = ['ref',$pages_id];
271 4 my $pages = $self->get_obj($pages_id);
272 4 my $pages_array = $self->get_obj($pages, '/Kids');
273 4 my $count = $self->get_obj($pages, "/Count");
274 4 ▶ if (@{$pages_array->[1]} != $count->[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$pages_array->[1];} != $count->[1]) 0 4 4
275 # Flatten the pages array. Other structures just require too much code.
276 0 _flatten_pages($self, $pages_id, $pages, $pages_array);
277 }
278 4 ▶ splice @{$pages_array->[1]}, $whither//@{$pages_array->[1]}, 0,
Condition66%2/3
$whither // @{$pages_array->[1];}
l!l&&r!l&&!r
022
MC/DC50%1/2
$whither // @{$pages_array->[1];}
$whither @{$pages_array->[1];}
Truth table66%2/3
A // B
A= $whitherB= @{$pages_array->[1];}
ABresult
1X1
011
000
279 ['ref',$page_id];
280 4 $count->[1]++;
281 _:
282 }
283 sub _flatten_pages {
284 0 ▶ my ($self, $pages_id, $pages, $pages_array) = @ '_;
Subroutine _flatten_pages: not called CC=9 SCAR=45.0
285 0 my @pages = _walk_pages($self, $pages);
286 0 for (@pages) {
287 0 my $page = $self->get_obj($_);
288 0 ▶ next if $page->[1]{Parent}[1] eq $pages_id;
Branch: 1 branch
BranchTrueFalseTotal
if $page->[1]{"Parent"}[1] eq $pages_id 0 0 0
289 0 my $node = $page;
290 0 ▶ while (!$page->[1]{Resources} || !$page->[1]{MediaBox}
Branch: 1 branch
BranchTrueFalseTotal
if (not $page->[1]{"Resources"} && $page->[1]{"MediaBox"} && $page->[1]{"CropBox"} and $node->[1]{"Parent"}[1] ne $pages_id) 0 0 0
Condition0%0/9
not $page->[1]{"Resources"} && $page->[1]{"MediaBox"} && $page->[1]{"CropBox"} and $node->[1]{"Parent"}[1] ne $pages_id
!ll&&!rl&&r
000
$page->[1]{'Resources'} && $page->[1]{'MediaBox'} && $page->[1]{'CropBox'}
!ll&&!rl&&r
000
$page->[1]{"Resources"} and $page->[1]{"MediaBox"}
!ll&&!rl&&r
000
MC/DC0%0/4
not $page->[1]{"Resources"} && $page->[1]{"MediaBox"} && $page->[1]{"CropBox"} and $node->[1]{"Parent"}[1] ne $pages_id
$page->[1]{"Resources"} $page->[1]{"MediaBox"} $page->[1]{'CropBox'} $node->[1]{"Parent"}[1] ne $pages_id
Truth table0%0/7
not(A and B && C) and D
A= $page->[1]{"Resources"}B= $page->[1]{"MediaBox"}C= $page->[1]{'CropBox'}D= $node->[1]{"Parent"}[1] ne $pages_id
ABCDresult
111X0
0XX00
10X00
11000
0XX11
10X11
11011
291 || !$page->[1]{CropBox} and $node->[1]{Parent}[1] ne $pages_id) {
292 0 $node = $self->get_obj($node, '/Parent');
293 $node->[1]{$_} and $page->[1]{$_} = $node->[1]{$_}
294 0 ▶ for qw< Resources MediaBox CropBox >;
Branch: 1 branch
BranchTrueFalseTotal
$node->[1]{$_} and $page->[1]{$_} = $node->[1]{$_} 0 0 0
295 }
296 0 $page->[1]{Parent}[1] = $pages_id;
297 }
298 0 $pages_array->[1] = \@pages;
299 }
300  
301 sub append {
302 3 ▶ my $self = shift;
Subroutine append: called CC=17 SCAR=29.7
Pod undocumented
303 3 ▶ if (!defined $self->[file]) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->[5]) 0 3 3
304 0 croak "No file to write to!"
305 }
306 3 ▶ if (!%{$self->[mods]}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (%{$self->[9];}) 0 3 3
307 0 return;
308 }
309 3 ▶ if ($self->[trai][1]{Type}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->[2][1]{"Type"}) 0 3 3
310 0 croak "Cannot append to files with cross-reference streams";
311 }
312 3 ▶ open my $fh, ">>", $self->[file]
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">>", $self->[5] or croak("Cannot open $self->[5] for writing: $!") 0 3 3
313 or croak "Cannot open $self->[file] for writing: $!";
314 3 binmode $fh;
315 3 local ($\,$,);
316 3 print $fh "\n"; # The existing %%EOF might not have \n after it
317  
318 # Update the doc ID now. If it already exists, it might be an indirect
319 # object, in which case changes to it must included in the objects that we
320 # append to the file before we reach the trailer.
321 3 my $id_array = $self->vivify_obj('array',"/ID");
322 3 ▶ if (@{$$id_array[1]} == 2
Branch: 1 branch
BranchTrueFalseTotal
if (@{$id_array->[1];} == 2 and $self->vivify_obj('str', $id_array, 0)->[1] ne $self->[3] || $self->vivify_obj('str', $id_array, 1)->[1] ne $self->[3]) { } 0 3 3
Condition33%2/6
@{$id_array->[1];} == 2 and $self->vivify_obj("str", $id_array, 0)->[1] ne $self->[3] || $self->vivify_obj("str", $id_array, 1)->[1] ne $self->[3]
!ll&&!rl&&r
030
$self->vivify_obj("str", $id_array, 0)->[1] ne $self->[3] or $self->vivify_obj("str", $id_array, 1)->[1] ne $self->[3]
l!l&&r!l&&!r
003
MC/DC0%0/3
@{$id_array->[1];} == 2 and $self->vivify_obj("str", $id_array, 0)->[1] ne $self->[3] || $self->vivify_obj("str", $id_array, 1)->[1] ne $self->[3]
@{$id_array->[1];} == 2 $self->vivify_obj("str", $id_array, 0)->[1] ne $self->[3] $self->vivify_obj("str", $id_array, 1)->[1] ne $self->[3]
Truth table25%1/4
A and B or C
A= @{$id_array->[1];} == 2B= $self->vivify_obj("str", $id_array, 0)->[1] ne $self->[3]C= $self->vivify_obj("str", $id_array, 1)->[1] ne $self->[3]
ABCresult
0XX0
1000
11X1
1011
323 and $self->vivify_obj('str', $id_array, 0)->[1] ne $self->[id]
324 || $self->vivify_obj('str', $id_array, 1)->[1] ne $self->[id]) {
325 # User has assigned his own id. Leave it alone.
326 }
327 else {
328 3 ▶ $self->vivify_obj('str', $id_array, 0)->[1]
Condition33%1/3
$self->vivify_obj("str", $id_array, 0)->[1] ||= time . '' ^ '' . (rand) ^ '' . (0 + $self)
l!l&&r!l&&!r
300
MC/DC0%0/2
$self->vivify_obj("str", $id_array, 0)->[1] ||= time . '' ^ '' . (rand) ^ '' . (0 + $self)
$self->vivify_obj("str", $id_array, 0)->[1] time . '' ^ '' . (rand) ^ '' . (0 + $self)
Truth table33%1/3
A ||= B
A= $self->vivify_obj("str", $id_array, 0)->[1]B= time . '' ^ '' . (rand) ^ '' . (0 + $self)
ABresult
1X1
011
000
329 ||= time."" ^ "".rand ^ "".(0+$self);
330 3 $self->vivify_obj('str', $id_array, 1)->[1]
331 ^= time."" ^ "".rand ^ "".(0+$self);
332 3 @{$$id_array[1]} = @{$$id_array[1]}[0,1];
333 }
334  
335 3 my %offsets;
336 3 my @ids = grep $self->[objs]{$_}, sort {$a<=>$b} keys %{$self->[mods]};
337 3 for (@ids) {
338 4 my $obj = $self->[objs]{$_};
339 4 $offsets{$_} = tell $fh;
340
341 4 ▶ if ($$obj[0] eq 'stream') {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->[0] eq 'stream') { } 1 3 4
342 1 print $fh join_tokens(
343 $_,'obj',
344 _serialize($obj)
345 ), $$obj[2], "\nendstream endobj\n"
346 }
347 else {
348 3 print $fh join_tokens(
349 $_,'obj',
350 _serialize($obj),
351 "endobj"
352 ), "\n";
353 }
354 }
355 3 my $startxref = tell $fh;
356 3 print $fh "xref\n";
357 # Divide the ids into chunks of consecutive numbers
358 3 my @chunks = ['0 65535'];
359 3 $offsets{'0 65535'} = $self->[free][0];
360 3 for (@ids) {
361 4 ▶ if ($chunks[-1][-1] + 1 != $_) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunks[-1][-1] + 1 != $_) 3 1 4
362 3 push @chunks, [];
363 }
364 4 push @{$chunks[-1]}, $_
365 }
366 3 for (@chunks) {
367 6 printf $fh "%d %s\n", $$_[0], scalar @$_;
368 printf $fh "%010d %05d %s \n",
369 $offsets{$_}, /\ (\d+)/, $_ == 0 ? "f" : "n"
370 6 ▶ for @$_;
Branch: 1 branch
BranchTrueFalseTotal
$_ == 0 ? : 3 4 7
371 }
372 3 my $trailerhash = $self->[trai]->[1];
373 3 $trailerhash->{Prev} = ['num', $self->[stxr]];
374 3 $trailerhash->{Size} = ['num', $self->[size]];
375 3 print $fh join_tokens(trailer=>serialize($self->[trai])),
376 "\nstartxref\n$startxref\n%%EOF\n";
377 3 ▶ close $fh or croak "Cannot close $self->[file]: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("Cannot close $self->[5]: $!") 0 3 3
378 }
379  
380 sub print {
381 4 ▶ my $self = shift;
Subroutine print: called CC=27 SCAR=33.2
Pod undocumented
382 4 my %args = @_;
383 4 ▶ $args{fh} // $args{filename} // croak "No file to write to!";
Condition60%3/5
($args{"fh"} // $args{"filename"}) // croak("No file to write to!")
l!l
40
$args{"fh"} // $args{"filename"}
l!l&&r!l&&!r
220
MC/DC0%0/3
($args{"fh"} // $args{"filename"}) // croak("No file to write to!")
$args{"fh"} $args{"filename"} croak("No file to write to!")
Truth table50%2/4
A // B // C
A= $args{"fh"}B= $args{"filename"}C= croak("No file to write to!")
ABCresult
1XX1
01X1
0011
0000
384 4 my $fh;
385 4 ▶ if ($args{filename}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'filename'}) { } 2 2 4
386 open $fh, ">", $args{filename}
387 2 ▶ or croak "Cannot open $args{filename} for writing: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $fh, ">", $args{"filename"} or croak(qq[Cannot open $args{"filename"} for writing: $!]) 0 2 2
388 }
389 2 else { $fh = $args{fh} }
390 4 binmode $fh;
391 4 local ($\,$,);
392 4 my $pos = length(my $buf = "%PDF-$self->[vers]\n%\xff\xff\xff\xff\n");
393 4 print $fh $buf;
394  
395 # Generate the doc ID now. If it already exists, it might be an indirect
396 # object, in which case changes to it must included in the objects that we
397 # append to the file before we reach the trailer.
398 4 my $id_array = $self->vivify_obj('array',"/ID");
399 4 ▶ if (@{$$id_array[1]} == 2
Branch: 1 branch
BranchTrueFalseTotal
if (@{$id_array->[1];} == 2 and $self->vivify_obj('str', $id_array, 0)->[1] ne $self->[3]) { } 3 1 4
Condition66%2/3
@{$id_array->[1];} == 2 and $self->vivify_obj("str", $id_array, 0)->[1] ne $self->[3]
!ll&&!rl&&r
103
MC/DC50%1/2
@{$id_array->[1];} == 2 and $self->vivify_obj("str", $id_array, 0)->[1] ne $self->[3]
@{$id_array->[1];} == 2 $self->vivify_obj("str", $id_array, 0)->[1] ne $self->[3]
Truth table66%2/3
A and B
A= @{$id_array->[1];} == 2B= $self->vivify_obj("str", $id_array, 0)->[1] ne $self->[3]
ABresult
0X0
100
111
400 and $self->vivify_obj('str', $id_array, 0)->[1] ne $self->[id]) {
401 # User has assigned his own id. Leave it alone.
402 }
403 else {
404 1 @{$$id_array[1]} = (['str', time."" ^ "".rand ^ "".(0+$self)])x2;
405 }
406  
407 # We assume that if this points to a cross-reference stream’s dictionary
408 # then we will not be emitting that cross-reference stream.
409 4 delete @{ $self->[trai][1] }{qw< XRefStm Length Filter DecodeParms F
410 FFilter FDecodeParms DL Type Size Index
411 Prev W >};
412  
413 4 my @trailer = _serialize($self->[trai]);
414 4 my %seen;
415 my @ids;
416 4 for (2..$#trailer) {
417 48 ▶ next unless $trailer[$_] eq 'R';
Branch: 1 branch
BranchTrueFalseTotal
unless $trailer[$_] eq "R" 41 7 48
418 7 my $id = sprintf '%d %d',@trailer[$_-2,$_-1];
419 7 ▶ next if $seen{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$id}++ 0 7 7
420 7 push @ids, $id;
421 }
422 4 my %offsets;
423 4 ▶ while (@ids) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ids) 50 4 54
424 50 my $id = shift @ids;
425 50 my $del = !$self->[objs]{$id};
426 50 ▶ my $obj = $self->get_obj($id) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $obj = $self->get_obj($id) or next 0 50 50
427 my @tokens = (my $flat = $obj->[0] eq 'flat')
428 ? tokenize($obj->[1],qr/^(?:endobj|stream)\z/)
429 50 ▶ : $obj->[0] eq 'tokens' ? @{$obj->[1]} : _serialize($obj);
Branch: 2 branches
BranchTrueFalseTotal
(my $flat = $obj->[0] eq 'flat') ? : 0 50 50
$obj->[0] eq 'tokens' ? : 0 50 50
430 50 for (2..$#tokens) {
431 501 ▶ next unless $tokens[$_] eq 'R';
Branch: 1 branch
BranchTrueFalseTotal
unless $tokens[$_] eq "R" 447 54 501
432 54 my $id = sprintf '%d %d',@tokens[$_-2,$_-1];
433 54 ▶ next if $seen{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$id}++ 11 43 54
434 43 push @ids, $id;
435 }
436 50 $offsets{$id} = $pos;
437 50 ▶ if ($$obj[0] eq 'stream') {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->[0] eq 'stream') { } 8 42 50
438 8 $pos += length($buf = join_tokens(
439 $id,'obj',
440 @tokens
441 ) . $$obj[2] . "\nendstream endobj\n"
442 );
443 8 print $fh $buf;
444 }
445 else {
446 42 $pos += length ($buf = join_tokens(
447 $id,'obj',
448 @tokens,
449 "endobj"
450 ) . "\n"
451 );
452 42 print $fh $buf;
453 }
454 50 ▶ delete $self->[objs]{$id} if $del; # Avoid reading the whole file into
Branch: 1 branch
BranchTrueFalseTotal
if $del 22 28 50
455 } # memory at once.
456 4 for (sort {$a<=>$b} keys %offsets) {
457 50 $ids[$_] = $_;
458 }
459 4 my @free = $ids[0] = '0 65535';
460 4 for (1..$#ids-1) {
461 58 ▶ next if $ids[$_];
Branch: 1 branch
BranchTrueFalseTotal
if $ids[$_] 46 12 58
462 12 push @free, $ids[$_] = "$_ 0";
463 }
464 4 my %next_free;
465 4 for (0..$#free) {
466 16 $next_free{$free[$_]} = 0+$free[$_+1];
467 }
468 4 my $startxref = $pos;
469 4 printf $fh "xref\n0 %d\n", scalar @ids;
470 4 for (@ids) {
471 printf $fh "%010d %05d %s \n",
472 exists $next_free{$_}
473 ? ($next_free{$_}, /\ (\d+)/, "f")
474 66 ▶ : ($offsets {$_}, /\ (\d+)/, "n")
Branch: 1 branch
BranchTrueFalseTotal
exists $next_free{$_} ? : 16 50 66
475 }
476 4 my $trailerhash = $self->[trai]->[1];
477 4 delete $trailerhash->{Prev};
478 4 $trailerhash->{Size} = ['flat', 1+$ids[-1]];
479 4 print $fh join_tokens(trailer=>serialize($self->[trai])),
480 "\nstartxref\n$startxref\n%%EOF\n";
481 4 ▶ if ($args{filename}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"filename"}) 2 2 4
482 2 ▶ close $fh or croak "Cannot close $args{filename}: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak(qq[Cannot close $args{"filename"}: $!]) 0 2 2
483 }
484 }
485  
486 # LOW-LEVEL METHODS
487  
488 1 ▶sub version :lvalue { $_[0][vers] }
Subroutine version: called CC=1 SCAR=0.0
Pod undocumented
489 0 ▶sub xref { $_[0][xrft] }
Subroutine xref: not called CC=1 SCAR=6.9
Pod undocumented
490  
491 sub modified {
492 3 ▶ my $self = shift;
Subroutine modified: called CC=6 SCAR=18.4
Pod undocumented
493 3 ▶ @_ or return $self->[mods];
Branch: 1 branch
BranchTrueFalseTotal
@_ or return $self->[9] 0 3 3
494 3 ▶ if (@_ == 1 && $_[0] !~ m.^/.) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and not $_[0] =~ m[^/]) 1 2 3
Condition66%2/3
@_ == 1 and not $_[0] =~ m[^/]
!ll&&!rl&&r
021
MC/DC50%1/2
@_ == 1 and not $_[0] =~ m[^/]
@_ == 1 not $_[0] =~ m[^/]
Truth table66%2/3
A and not(B)
A= @_ == 1B= not $_[0] =~ m[^/]
ABresult
0X0
100
111
495 1 ▶ croak "$_[0] is not an object id" unless $_[0] =~ /^[0-9]+ [0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] =~ /^[0-9]+ [0-9]+\z/ 0 1 1
496 1 $self->[mods]{$_[0]}++;
497 return
498 1 }
499 2 my (undef, $last_ref) = _get_obj($self, 0, @_);
500 2 ▶ $last_ref and $self->[mods]{$last_ref}++;
Branch: 1 branch
BranchTrueFalseTotal
$last_ref and ++$self->[9]{$last_ref} 2 0 2
501 2 $self->[mods];
502 }
503  
504 0 ▶sub objects { $_[0][objs] }
Subroutine objects: not called CC=1 SCAR=6.9
Pod undocumented
505 1 ▶sub trailer { $_[0][trai] }
Subroutine trailer: called CC=1 SCAR=0.0
Pod undocumented
506  
507 sub read_obj {
508 71 ▶ my $self = shift;
Subroutine read_obj: called CC=9 SCAR=32.6
Pod undocumented
509 71 my $id = shift;
510 71 ▶ { return $self->[objs]{$id} || next }
Condition100%2/2
$self->[10]{$id} || (next)
l!l
566
MC/DC100%1/1
$self->[10]{$id} || (next)
$self->[10]{$id}
Truth table100%2/2
A
A= $self->[10]{$id}
Aresult
11
00
511 66 ▶ croak "$id is not a valid id" unless $id =~ /^[0-9]+ [0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /^[0-9]+ [0-9]+\z/ 0 66 66
512 66 ▶ if (!$self->[fh]) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->[1]) 0 66 66
513 0 croak "No file open";
514 }
515 66 ▶ my $loc = $self->[xrft]{$id} || return $null;
Condition50%1/2
$self->[8]{$id} || (return $null)
l!l
660
MC/DC0%0/1
$self->[8]{$id} || (return $null)
$self->[8]{$id}
Truth table50%1/2
A
A= $self->[8]{$id}
Aresult
11
00
516 66 ▶ if (ref $loc) { # handle object streams here
Branch: 1 branch
BranchTrueFalseTotal
if (ref $loc) 0 66 66
517 0 my ($strmid, $ix) = @$loc;
518 # Since we have to decompress the stream and calculate the offsets, let’s
519 # go ahead and extract all the objects into the objects hash, in flat
520 # format. We may have reached this code because somebody manually
521 # deleted an objects entry in order to re-read it, so only extract
522 # objects that are not already in the hash.
523 0 my $obj = $self->get_obj($strmid);
524 0 my $stream = \$self->decode_stream($obj);
525 0 my $count = $self->get_obj($$obj[1], "/N")->[1];
526 0 my $first = $self->get_obj($$obj[1], "/First")->[1];
527 0 my @numbers =
528 split /(?:$S++|%[^\cm\cj]*[\cm\cj])+/, substr $$stream, 0, $first, '';
529 0 ▶ while (@numbers) {
Branch: 1 branch
BranchTrueFalseTotal
if (@numbers) 0 0 0
530 0 my ($id, $off) = splice @numbers, 0, 2;
531 0 $id .= " 0";
532 0 ▶ $self->[objs]{$id} ||=
Branch: 1 branch
BranchTrueFalseTotal
@numbers ? : 0 0 0
Condition0%0/2
$self->[10]{$id} ||= ["flat", substr($$stream, $off, @numbers ? $numbers[1] - $off : length $$stream)]
l!l
00
MC/DC0%0/1
$self->[10]{$id} ||= ["flat", substr($$stream, $off, @numbers ? $numbers[1] - $off : length $$stream)]
$self->[10]{$id}
Truth table0%0/2
A
A= $self->[10]{$id}
Aresult
11
00
533 ['flat',
534 substr $$stream, $off, @numbers ? $numbers[1]-$off : length $$stream]
535 }
536 0 return $self->[objs]{$id}
537 }
538 # otherwise use the seek-and-read approach
539 66 _read_obj($self, $loc, $id);
540 }
541 sub _read_obj {
542 69 ▶ my ($self, $loc, $id) = @_;
Subroutine _read_obj: called CC=7 SCAR=19.7
543 69 seek $self->[fh], $loc, 0;
544 69 ▶ read $self->[fh], my $buf, 1024 or croak "Cannot read $self->[file]: $!";
Branch: 1 branch
BranchTrueFalseTotal
read $self->[1], my $buf, 1024 or croak("Cannot read $self->[5]: $!") 0 69 69
545  
546 my @tokens = tokenize($buf, qr/^(?:endobj|stream)\z/,
547 sub {
548 177 ▶ defined read $self->[fh], $buf, 1024, length $buf
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
defined read($self->[1], $buf, 1024, length $buf) or croak("Cannot read $self->[5]: $!") 0 177 177
549 or croak "Cannot read $self->[file]: $!"
550 69 });
551 69 my $read_id = 0+shift(@tokens) . ' ' . (0+shift@tokens);
552 69 ▶ if ($id and $read_id ne $id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id and $read_id ne $id) 0 69 69
Condition66%2/3
$id and $read_id ne $id
!ll&&!rl&&r
3660
MC/DC0%0/2
$id and $read_id ne $id
$id $read_id ne $id
Truth table66%2/3
A and B
A= $idB= $read_id ne $id
ABresult
0X0
100
111
553 0 croak "$self->[file]: Found $read_id at offset $loc instead of $id";
554 }
555 69 shift @tokens; # remove “obj”
556 69 my $obj;
557 69 ▶ if ($tokens[-1] eq 'stream') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tokens[-1] eq 'stream') { } 11 58 69
558 11 my $pos = tell $self->[fh];
559 11 $obj = _interpret_token(\@tokens);
560 11 $buf =~ s/^\cm?\cj//;
561 # Create the new obj now, to avoid having to copy a huge buffer on pre-
562 # COW perls.
563 11 my $new_obj = ['stream', $obj, $buf];
564 # Have to use get_obj here, not $obj[1]{Length}[1], as /Length could be
565 # an indirect reference.
566 11 my $stream_length = $self->get_obj($obj, '/Length')->[1];
567 11 ▶ if (length $buf < $stream_length) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $buf < $stream_length) { } 4 7 11
568 4 seek $self->[fh], $pos, 0;
569 4 ▶ read $self->[fh], $new_obj->[2], $stream_length-length $buf, length $buf
Branch: 1 branch
BranchTrueFalseTotal
read $self->[1], $new_obj->[2], $stream_length - length($buf), length $buf or croak("Cannot read $self->[5]: $!") 0 4 4
570 or croak "Cannot read $self->[file]: $!";
571 }
572 else {
573 7 substr $new_obj->[2], $stream_length, = '';
574 }
575 11 $obj = $new_obj;
576 }
577 else {
578 58 pop @tokens; # remove ‘endobj’
579 58 $obj = ['tokens', \@tokens];
580 }
581 69 $self->[objs]{$read_id} = $obj
582 }
583  
584 sub get_obj {
585 152 ▶ splice @_, 1, 0, 0;
Subroutine get_obj: called CC=1 SCAR=0.0
Pod undocumented
586 152 (&_get_obj)[0]
587 }
588 sub _get_obj {
589 179 ▶ my $self = shift;
Subroutine _get_obj: called CC=20 SCAR=30.4
590 179 my $vivify = shift;
591 179 my $obj = shift;
592 # $obj may be any of:
593 # • "4 0"
594 # • "/Root"
595 # • ['dict', { ... }]
596 # • ['array', { ... }]
597 # • ['ref', "4 0 R"]
598 # • ['anything else', ...]
599 179 my $lastref;
600 {
601 179 ▶ if (ref $obj) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $obj) { } 121 132 253
elsif ($obj =~ m[^/]) { } 38 94 132
602 121 ▶ if ($$obj[0] eq 'ref') {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->[0] eq "ref") 36 85 121
603 36 $obj = $$obj[1]; redo
604 36 }
605 }
606 elsif ($obj =~ m.^/.) {
607 38 my $subobj = $self->[trai][1]{substr $obj, 1};
608 38 ▶ if (!$subobj) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $subobj) { } 2 36 38
609 2 ▶ if ($vivify) {
Branch: 1 branch
BranchTrueFalseTotal
if ($vivify) { } 2 0 2
610 2 ▶ $obj = $self->[trai][1]{substr $obj, 1} =_viv($vivify, @_ ? $_[0]: ())
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 2 2
611 }
612 else {
613 return
614 0 }
615 }
616 36 else { $obj = $subobj }
617 38 redo; # $obj may be ['ref', '1894 0']
618 }
619 else {
620 94 $lastref = $obj;
621 94 ▶ $obj = $self->[objs]{$obj} || $self->read_obj($obj);
Condition66%2/3
$self->[10]{$obj} || $self->read_obj($obj)
l!l&&r!l&&!r
54400
MC/DC0%0/2
$self->[10]{$obj} || $self->read_obj($obj)
$self->[10]{$obj} $self->read_obj($obj)
Truth table66%2/3
A || B
A= $self->[10]{$obj}B= $self->read_obj($obj)
ABresult
1X1
011
000
622 }
623 }
624 179 ▶ $obj or return;
Branch: 1 branch
BranchTrueFalseTotal
$obj or return 0 179 179
625 179 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 103 176 279
626 103 ▶ if ($$obj[0] eq 'stream') { $obj = $$obj[1] } # for get_obj($stream,$key)
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->[0] eq "stream") 7 96 103
627 103 _unflatten($obj);
628 103 my $key = shift;
629 103 ▶ my $subobj = $key =~ m.^/. ? $$obj[1]{substr $key, 1} : $$obj[1][$key];
Branch: 1 branch
BranchTrueFalseTotal
$key =~ m[^/] ? : 86 17 103
630 103 ▶ if (!$subobj) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $subobj) { } 4 99 103
631 4 ▶ if ($vivify) {
Branch: 1 branch
BranchTrueFalseTotal
if ($vivify) { } 1 3 4
632 1 ▶ $obj = $key =~ m.^/. ? $$obj[1]{substr $key, 1} : $$obj[1][$key] =
Branch: 2 branches
BranchTrueFalseTotal
@_ ? : 0 1 1
$key =~ m[^/] ? : 1 0 1
633 _viv($vivify, @_ ? $_[0]: ())
634 }
635 else {
636 return
637 3 }
638 }
639 99 else { $obj = $subobj }
640 100 ▶ if ($obj && $$obj[0] eq 'ref') {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj and $obj->[0] eq "ref") 31 69 100
Condition66%2/3
$obj and $obj->[0] eq "ref"
!ll&&!rl&&r
06931
MC/DC50%1/2
$obj and $obj->[0] eq "ref"
$obj $obj->[0] eq "ref"
Truth table66%2/3
A and B
A= $objB= $obj->[0] eq "ref"
ABresult
0X0
100
111
641 31 $lastref = $$obj[1];
642 31 ▶ $obj = $self->[objs]{$$obj[1]} || $self->read_obj($$obj[1]);
Condition66%2/3
$self->[10]{$obj->[1]} || $self->read_obj($obj->[1])
l!l&&r!l&&!r
16150
MC/DC0%0/2
$self->[10]{$obj->[1]} || $self->read_obj($obj->[1])
$self->[10]{$obj->[1]} $self->read_obj($obj->[1])
Truth table66%2/3
A || B
A= $self->[10]{$obj->[1]}B= $self->read_obj($obj->[1])
ABresult
1X1
011
000
643 }
644 }
645 176 _unflatten($obj);
646 176 ▶ $obj->[0] eq 'null' and return;
Branch: 1 branch
BranchTrueFalseTotal
$obj->[0] eq "null" and return 0 176 176
647 176 $obj, $lastref;
648 }
649 sub _unflatten {
650 283 ▶ my $obj = shift;
Subroutine _unflatten: called CC=3 SCAR=11.8
651 283 ▶ if ($$obj[0] eq 'flat') {
Branch: 2 branches
BranchTrueFalseTotal
if ($obj->[0] eq 'flat') { } 0 283 283
elsif ($obj->[0] eq 'tokens') { } 67 216 283
652 0 @$obj = @{ _interpret_token([tokenize($$obj[1])]) };
653 }
654 elsif($$obj[0] eq 'tokens') {
655 67 @$obj = @{ _interpret_token($$obj[1]) };
656 }
657 }
658 sub _viv {
659 3 ▶ my ($type, $key) = @_;
Subroutine _viv: called CC=8 SCAR=25.9
660 3 ▶ [defined $key
Branch: 7 branches
BranchTrueFalseTotal
defined $key ? : 0 3 3
$key =~ m[^/] ? : 0 0 0
$type eq 'dict' ? : 0 3 3
$type =~ /^(?:array|tokens)\z/ ? : 2 1 3
$type eq 'num' ? : 0 1 1
$type eq 'null' ? : 0 1 1
$type eq 'stream' ? : 0 1 1
661 ? $key =~ m.^/. ? ('dict',{}) : ('array',[])
662 : ($type, $type eq 'dict' ? {}
663 : $type =~ /^(?:array|tokens)\z/ ? []
664 : $type eq 'num' ? 0
665 : $type eq 'null' ? ()
666 : $type eq 'stream' ? (['dict',{}], '') : '')
667 ];
668 }
669  
670 sub vivify_obj {
671 25 ▶ my $self = $_[0];
Subroutine vivify_obj: called CC=3 SCAR=11.2
Pod undocumented
672 25 ▶ if ($_[1] !~ /^[a-z]+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_[1] =~ /^[a-z]+\z/) 0 25 25
673 0 croak "First arg to vivify_obj must be a type";
674 }
675 25 my($obj, $lastref) = &_get_obj;
676 25 ▶ $lastref and $$self[mods]{$lastref}++;
Branch: 1 branch
BranchTrueFalseTotal
$lastref and ++$self->[9]{$lastref} 2 23 25
677 25 $obj;
678 }
679  
680 sub get_page {
681 7 ▶ my $self = shift;
Subroutine get_page: called CC=1 SCAR=0.0
Pod undocumented
682 7 my @pages = _walk_pages($self);
683 7 $self->get_obj($pages[$_[0]])
684 }
685  
686 # The import cache looks like this:
687 # # src dest src dest
688 # { $other_pdf => { '2 0' => '1 0', '12 0' => '13 0', ... },
689 # $another_pdf => { '1 0' => '3 0', '12 0' => '13 0', ... },
690 # ...
691 # }
692 # where src is the PDF imported from and dest is the PDF that owns the
693 # cache.
694 sub import_obj {
695 4 ▶ my ($self, $spdf, $obj) = @'_;
Subroutine import_obj: called CC=19 SCAR=31.0
Pod undocumented
696 my $cach =
697 ($self->[impo] ||=
698 2 do { require Hash'Util'FieldHash; &Hash'Util'FieldHash'fieldhash({}) })
699 4 ▶ ->{$spdf} ||= {};
Condition80%4/5
+($self->[12] ||= do { require Hash::Util::FieldHash; &Hash::Util::FieldHash::fieldhash(scalar {}) })->{$spdf} ||= {}
l!l
22
$self->[12] ||= do { require Hash::Util::FieldHash; &Hash::Util::FieldHash::fieldhash(scalar {}) }
l!l&&r!l&&!r
220
MC/DC100%1/1
+($self->[12] ||= do { require Hash::Util::FieldHash; &Hash::Util::FieldHash::fieldhash(scalar {}) })->{$spdf} ||= {}
+($self->[12] ||= do { require Hash::Util::FieldHash; &Hash::Util::FieldHash::fieldhash(scalar {}) })->{$spdf}
MC/DC0%0/2
$self->[12] ||= do { require Hash::Util::FieldHash; &Hash::Util::FieldHash::fieldhash(scalar {}) }
$self->[12] do { require Hash::Util::FieldHash; &Hash::Util::FieldHash::fieldhash(scalar {}) }
Truth table100%2/2
A
A= +($self->[12] ||= do { require Hash::Util::FieldHash; &Hash::Util::FieldHash::fieldhash(scalar {}) })->{$spdf}
Aresult
11
00
Truth table66%2/3
A ||= B
A= $self->[12]B= do { require Hash::Util::FieldHash; &Hash::Util::FieldHash::fieldhash(scalar {}) }
ABresult
1X1
011
000
700 4 my $ret;
701 4 ▶ if (!ref $obj) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $obj) 0 4 4
702 0 ▶ croak "$obj is not an object id" unless $obj =~ /^[0-9]+ [0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $obj =~ /^[0-9]+ [0-9]+\z/ 0 0 0
703 0 ▶ if ($cach->{$obj}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cach->{$obj}) 0 0 0
704 0 return $cach->{$obj}
705 }
706 # Assign a new number now. In the loop below, we assume that all
707 # objects have had new numbers assigned already, and that the objects
708 # just need cloning.
709 # Temporarily assign an empty array.
710 0 $ret = $cach->{$obj} = $self->add_obj([]);
711 }
712 4 my $return_id = !ref $obj;
713 4 my @objs = $obj;
714 4 ▶ while (@objs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@objs) 20 4 24
715 20 my $obj = shift @objs;
716 20 my $id;
717 20 ▶ if (!ref $obj) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $obj) 16 4 20
718 16 $id = $obj;
719 16 $obj = $spdf->read_obj($obj);
720 }
721 my @tokens = ($obj->[0] eq 'flat')
722 ? tokenize($obj->[1],qr/^stream\z/)
723 20 ▶ : $obj->[0] eq 'tokens' ? @{$obj->[1]} : _serialize($obj);
Branch: 2 branches
BranchTrueFalseTotal
$obj->[0] eq 'flat' ? : 0 20 20
$obj->[0] eq 'tokens' ? : 6 14 20
724 20 for (2..$#tokens) {
725 222 ▶ next unless $tokens[$_] eq 'R';
Branch: 1 branch
BranchTrueFalseTotal
unless $tokens[$_] eq "R" 202 20 222
726 20 my $id = sprintf '%d %d',@tokens[$_-2,$_-1];
727 20 ▶ if (!$cach->{$id}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cach->{$id}) 16 4 20
728 # Temporarily assign an empty array.
729 16 $cach->{$id} = $self->add_obj([]);
730 # Add to the list of ids to process.
731 16 push @objs, $id;
732 }
733 20 @tokens[$_-2,$_-1] = split / /, $cach->{$id};
734 }
735 # Clone the object.
736 # If an object id is in @objs at this point, it can only be because it
737 # has had a new id assigned already.
738 my $clone =
739 $id && ($cach->{$id} || die "Internal error: $obj got uncached")
740 20 ▶ ? $self->[objs]{$cach->{$id}} # cached empty array
Branch: 1 branch
BranchTrueFalseTotal
$id && ($cach->{$id} || die("Internal error: $obj got uncached")) ? : 16 4 20
Condition60%3/5
$id and $cach->{$id} || die("Internal error: $obj got uncached")
!ll&&!rl&&r
4016
$cach->{$id} or die "Internal error: $obj got uncached"
l!l
160
MC/DC50%1/2
$id and $cach->{$id} || die("Internal error: $obj got uncached")
$id $cach->{$id}
Truth table66%2/3
A and B
A= $idB= $cach->{$id}
ABresult
0X0
100
111
741 : []; # cloning the top-level object with no cache
742 20 ▶ $ret ||= $clone;
Condition66%2/3
$ret ||= $clone
l!l&&r!l&&!r
1640
MC/DC0%0/2
$ret ||= $clone
$ret $clone
Truth table66%2/3
A ||= B
A= $retB= $clone
ABresult
1X1
011
000
743  
744 ## We are not supporting flat streams yet (if ever).
745 #if ($$obj[0] eq 'flat' && $tokens[-1] eq "stream\n") {
746 # pop @tokens;
747 # @$clone = ('stream', ['tokens', \@tokens, ...???
748 #}
749  
750 20 ▶ if ($$obj[0] eq 'stream') {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->[0] eq 'stream') { } 5 15 20
751 # tokenize() above will have ended up putting a "stream\n" token on the
752 # end, which we do not want in the dictionary.
753 5 pop @tokens;
754 5 @$clone = ('stream', ['tokens', \@tokens], $$obj[2]);
755 }
756 else {
757 15 @$clone = ('tokens', \@tokens);
758 }
759 }
760 4 ▶ _unflatten($ret) if ref $ret;
Branch: 1 branch
BranchTrueFalseTotal
if ref $ret 4 0 4
761 4 $ret;
762 }
763  
764 sub add_obj {
765 23 ▶ my $self = shift;
Subroutine add_obj: called CC=2 SCAR=7.0
Pod undocumented
766 23 ▶ my $id = shift @{$self->[free]} || $self->[size]++ . ' 0';
Condition50%1/2
shift @{$$self[7];} || $self->[6]++ . ' 0'
l!l
023
MC/DC0%0/1
shift @{$$self[7];} || $self->[6]++ . ' 0'
shift @{$$self[7];}
Truth table50%1/2
A
A= shift @{$$self[7];}
Aresult
11
00
767 23 $self->[objs]{$id} = shift;
768 23 $self->[mods]{$id}++;
769 23 $id;
770 }
771  
772 sub decode_stream :lvalue{
773 3 ▶ my $self = shift;
Subroutine decode_stream: called CC=7 SCAR=20.5
Pod undocumented
774 3 my $stream = $self->get_obj(@_);
775 3 my @filters = $self->get_obj($stream, "/Filter");
776 3 ▶ if (@filters) {
Branch: 1 branch
BranchTrueFalseTotal
if (@filters) 2 1 3
777 2 ▶ if ($filters[0][0] eq 'array') {
Branch: 1 branch
BranchTrueFalseTotal
if ($filters[0][0] eq 'array') { } 0 2 2
778 0 @filters = map $self->get_obj($filters[0],$_)->[1],0..$#{$filters[0][1]};
779 }
780 2 else { @filters = $filters[0][1] }
781 }
782 3 ▶ my @params = $self->get_obj($stream, "/DecodeParms")
Condition66%2/3
$self->get_obj($stream, '/DecodeParms') || $self->get_obj($stream, '/DP')
l!l&&r!l&&!r
201
MC/DC50%1/2
$self->get_obj($stream, '/DecodeParms') || $self->get_obj($stream, '/DP')
$self->get_obj($stream, '/DecodeParms') $self->get_obj($stream, '/DP')
Truth table66%2/3
A || B
A= $self->get_obj($stream, '/DecodeParms')B= $self->get_obj($stream, '/DP')
ABresult
1X1
011
000
783 || $self->get_obj($stream, "/DP"); # unofficial but Acrobat sup-
784 3 ▶ if (@params) { # ports it
Branch: 1 branch
BranchTrueFalseTotal
if (@params) 2 1 3
785 2 ▶ if ($params[0][0] eq 'array') {
Branch: 1 branch
BranchTrueFalseTotal
if ($params[0][0] eq "array") 0 2 2
786 @params = map scalar $self->get_obj($params[0], $_),
787 0 0..$#{$params[0][1]};
788 }
789 }
790 3 $stream = \$stream->[2];
791 3 for (@filters) {
792 2 $stream = _unfilter($self, $stream, $_, shift @params);
793 }
794 3 $$stream
795 }
796  
797 sub _unfilter {
798 2 ▶ my ($self, $stream, $filter, $params) = @_;
Subroutine _unfilter: called CC=26 SCAR=46.8
799 2 ▶ $filter eq 'FlateDecode'
Branch: 1 branch
BranchTrueFalseTotal
$filter eq "FlateDecode" or croak("The $filter filter is not supported", 1) 0 2 2
800 or croak "The $filter filter is not supported", 1;
801 2 my ($predictor, $bpc, $cols, $colours) = (1, 8, 1, 1);
802 2 ▶ if ($params) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params) 2 0 2
803 $params->[1]{Predictor}
804 2 ▶ and $predictor = $self->get_obj($params, "/Predictor")->[1];
Branch: 1 branch
BranchTrueFalseTotal
$params->[1]{"Predictor"} and $predictor = $self->get_obj($params, "/Predictor")->[1] 2 0 2
805 2 ▶ $predictor == 1 || $predictor >= 10
Branch: 1 branch
BranchTrueFalseTotal
$predictor == 1 or $predictor >= 10 or croak("Predictor functions other than PNG are not supported", 1) 0 2 2
Condition33%1/3
$predictor == 1 or $predictor >= 10
l!l&&r!l&&!r
020
MC/DC0%0/2
$predictor == 1 or $predictor >= 10
$predictor == 1 $predictor >= 10
Truth table33%1/3
A or B
A= $predictor == 1B= $predictor >= 10
ABresult
1X1
011
000
806 || croak "Predictor functions other than PNG are not supported", 1;
807 $params->[1]{BitsPerComponent}
808 2 ▶ and $bpc = $self->get_obj($params, "/BitsPerComponent")->[1];
Branch: 1 branch
BranchTrueFalseTotal
$params->[1]{"BitsPerComponent"} and $bpc = $self->get_obj($params, "/BitsPerComponent")->[1] 0 2 2
809 2 ▶ $$params[1]{Columns} and $cols=$self->get_obj($params, "/Columns")->[1];
Branch: 1 branch
BranchTrueFalseTotal
$params->[1]{"Columns"} and $cols = $self->get_obj($params, "/Columns")->[1] 2 0 2
810 2 ▶ $$params[1]{Colours} and $colours=$self->get_obj($params,"/Colors")->[1];
Branch: 1 branch
BranchTrueFalseTotal
$params->[1]{"Colours"} and $colours = $self->get_obj($params, "/Colors")->[1] 0 2 2
811 2 ▶ $bpc % 8 and croak "BitsPerComponent values that are not multiples of"
Branch: 1 branch
BranchTrueFalseTotal
$bpc % 8 and croak("BitsPerComponent values that are not multiples of 8 are not supported", 1) 0 2 2
812 . " 8 are not supported", 1;
813 2 $bpc >>= 3; # bytes per component
814 2 $bpc *= $colours;
815 }
816 2 require Compress::Zlib;
817 2 ▶ my $x = Compress'Zlib'inflateInit()
Branch: 1 branch
BranchTrueFalseTotal
my $x = &Compress::Zlib::inflateInit() or croak("Could not create an inflation stream (whatever that is)", 1) 0 2 2
818 or croak "Could not create an inflation stream (whatever that is)", 1;
819 2 my ($flate_output, $flate_stat) = inflate $x my $copy = $$stream;
820 2 ▶ croak "Inflation failed for some reason", 1
Branch: 1 branch
BranchTrueFalseTotal
unless $flate_stat == &Compress::Zlib::Z_STREAM_END 0 2 2
821 unless $flate_stat == &Compress'Zlib'Z_STREAM_END;
822 2 ▶ if ($predictor >= 10) { # rats
Branch: 1 branch
BranchTrueFalseTotal
if ($predictor >= 10) { } 2 0 2
823 2 my $output = '';
824 2 my $rowsize = 1 + $bpc * $cols;
825 2 my $prev = "\0"x($rowsize-1);
826 2 for my $row (1..length($flate_output) / $rowsize) {
827 20 my $filter = vec $flate_output, ($row-1) * $rowsize, 8;
828 20 my $samples = substr $flate_output, ($row-1) * $rowsize + 1, $rowsize-1;
829 20 ▶ if ($filter == 2) { # Up (first ’cos it’s the most common)
Branch: 5 branches
BranchTrueFalseTotal
if ($filter == 2) { } 20 0 20
elsif (not $filter) { } 0 0 0
elsif ($filter == 1) { } 0 0 0
elsif ($filter == 3) { } 0 0 0
elsif ($filter == 4) { } 0 0 0
830 20 for (0..$rowsize-2) {
831 80 vec ($samples, $_, 8) += vec $prev, $_, 8;
832 }
833 }
834 elsif (!$filter) { # Nothing
835 }
836 elsif ($filter == 1) { # Sub (left)
837 0 for (0..$rowsize-2) {
838 0 vec ($samples, $_, 8) += vec $samples, $_ - $bpc, 8;
839 }
840 }
841 elsif ($filter == 3) { # Avg
842 0 for (0..$rowsize-2) {
843 0 vec ($samples, $_, 8) +=
844 (vec($prev, $_, 8) + vec $samples, $_ - $bpc, 8) / 2;
845 }
846 }
847 elsif ($filter == 4) { # Paeth
848 0 for (0..$rowsize-2) {
849 0 my ($a,$b,$c) = (vec($samples, $_ - $bpc, 8),
850 vec($prev , $_ , 8),
851 vec $prev , $_ - $bpc, 8 );
852 0 my $p = $a + $b - $c;
853 0 my ($pa, $pb, $pc) = (abs($p - $a), abs($p - $b), abs($p - $c));
854 0 ▶ vec $samples, $_, 8 =>=
Branch: 2 branches
BranchTrueFalseTotal
$pa <= $pb && $pa <= $pc ? : 0 0 0
$pb <= $pc ? : 0 0 0
Condition0%0/3
$pa <= $pb and $pa <= $pc
!ll&&!rl&&r
000
MC/DC0%0/2
$pa <= $pb and $pa <= $pc
$pa <= $pb $pa <= $pc
Truth table0%0/3
A and B
A= $pa <= $pbB= $pa <= $pc
ABresult
0X0
100
111
855 $pa <= $pb && $pa <= $pc ? $a : $pb <= $pc ? $b : $c
856 }
857 }
858 0 else { croak "Invalid PNG filter value: $filter", 1 }
859 20 $output .= $prev = $samples;
860 }
861 2 \$output;
862 }
863 else {
864 0 \$flate_output;
865 }
866 }
867  
868  
869 # FUNCTIONS
870  
871 1 *tokenise = *tokenize;
872 sub tokenize { # This function tokenizes.
873 # accepts three arguments: the text to parse, the token to stop
874 # on (such as 'endobj') and a function to supply more text
875 # the 2nd and 3rd args are optional
876  
877 83 ▶ for (shift) {
Subroutine tokenize: called CC=14 SCAR=26.5
Pod undocumented
878 83 my $endtoken=shift;
879 83 my $more = shift;
880 83 my @tokens;
881 my $prev_length;
882 83 TOKEN: while (1) {
883 1471 ▶ if ($more and length() < 500) {
Branch: 2 branches
BranchTrueFalseTotal
if ($more and length $_ < 500) { } 168 1303 1471
elsif (not length $_ or length $_ == $prev_length) { } 0 1303 1303
Condition100%3/3
$more and length $_ < 500
!ll&&!rl&&r
1911112168
MC/DC100%2/2
$more and length $_ < 500
$more length $_ < 500
Truth table100%3/3
A and B
A= $moreB= length $_ < 500
ABresult
0X0
100
111
884 168 &$more();
885 }
886 ▶ elsif(!length or length == $prev_length) {
Condition33%1/3
not length $_ or length $_ == $prev_length
l!l&&r!l&&!r
001303
MC/DC0%0/2
not length $_ or length $_ == $prev_length
not length $_ length $_ == $prev_length
Truth table33%1/3
not(A) or B
A= not length $_B= length $_ == $prev_length
ABresult
1X1
011
000
887 0 last TOKEN;
888 }
889 1471 $prev_length = length;
890 1471 s/^(?:$S++|%[^\cm\cj]*$N)+//o;
891 1471 ▶ if (s _^(($R+)|<<|>>|[\[\]\{\}]|/$R*)__o) {
Branch: 1 branch
BranchTrueFalseTotal
if (s(^(($R+)|<<|>>|[\[\]\{\}]|/$R*))[]o) 1424 47 1471
892 1424 push @tokens, $1;
893 1424 ▶ last TOKEN if defined $endtoken && length $2
Branch: 1 branch
BranchTrueFalseTotal
if defined $endtoken and length $2 and $1 =~ /$endtoken/ 82 1342 1424
Condition83%5/6
defined $endtoken and length $2 and $1 =~ /$endtoken/
!ll&&!rl&&r
60573782
defined $endtoken and length $2
!ll&&!rl&&r
0605819
MC/DC66%2/3
defined $endtoken and length $2 and $1 =~ /$endtoken/
defined $endtoken length $2 $1 =~ /$endtoken/
Truth table75%3/4
A and B and C
A= defined $endtokenB= length $2C= $1 =~ /$endtoken/
ABCresult
0XX0
10X0
1100
1111
894 && $1 =~ $endtoken;
895 next TOKEN
896 1342 }
897 47 ▶ if (s.^\(..) { # remove paren.
Branch: 1 branch
BranchTrueFalseTotal
if (s/^\(//) 15 32 47
898 15 ▶ &$more()
Branch: 1 branch
BranchTrueFalseTotal
s/( (?:\\.|[^()\\])++# escaped char or non-\() | \((?1)\) # parenthesized stuff )*\) # final closing paren //sx or do { &$more() } 9 14 23
899 until s/(
900 (?:\\.|[^()\\])++# escaped char or non-\()
901 |
902 \((?1)\) # parenthesized stuff
903 )*\) # final closing paren
904 //xs;
905 14 push @tokens, "($1)";
906 next
907 14 }
908 32 ▶ s.^(<[^>]*>).. and push @tokens, $1;
Branch: 1 branch
BranchTrueFalseTotal
s/^(<[^>]*>)// and push @tokens, $1 19 13 32
909 32 ▶ &$more() while /^<[^>]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
/^<[^>]*\z/ and do { &$more() } 1 32 33
910 }
911 82 return @tokens;
912 }
913 }
914  
915 sub join_tokens {
916 # PDF lines are not supposed to be longer than 255 (outside of content
917 # streams). I don’t know whether that includes the line ending. I assume
918 # it does.
919 80 ▶ my $ret = '';
Subroutine join_tokens: called CC=13 SCAR=25.7
Pod undocumented
920 80 my $line = '';
921 80 for (@_) {
922 # We assume that only strings can get too long to fit on a line. After
923 # all, they are the only token that can be split between lines.
924 1030 ▶ if (length() + length $line > 254 && /^$S*([(<])/o) {
Branch: 1 branch
BranchTrueFalseTotal
if (length($_) + length($line) > 254 and /^$S*([(<])/o) { } 3 1027 1030
Condition100%3/3
length($_) + length($line) > 254 and /^$S*([(<])/o
!ll&&!rl&&r
102613
MC/DC100%2/2
length($_) + length($line) > 254 and /^$S*([(<])/o
length($_) + length($line) > 254 /^$S*([(<])/o
Truth table100%3/3
A and B
A= length($_) + length($line) > 254B= /^$S*([(<])/o
ABresult
0X0
100
111
925 3 my $hex = $1 eq '<';
926 # Put a line break before the string.
927 3 $ret .= "$line\n";
928 3 $line = '';
929 # To keep this code simple, just ignore the fact that strings can have
930 # embedded line breaks. Just split it up into pieces that are small
931 # enough to fit on a line.
932 3 ▶ while (length > 254) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $_ > 254) 65 3 68
933 # Don’t split it between an escaper and an escapee.
934 65 my $piecepiece = substr $_, 0, 253;
935 65 ▶ chop $piecepiece unless $piecepiece =~ /^[^\\]*(?:\\.[^\\]*)*\z/s;
Branch: 1 branch
BranchTrueFalseTotal
unless $piecepiece =~ /^[^\\]*(?:\\.[^\\]*)*\z/s 0 65 65
936 65 ▶ $ret .= $hex ? "$piecepiece\n" : "$piecepiece\\\n";
Branch: 1 branch
BranchTrueFalseTotal
$hex ? : 1 64 65
937 65 substr $_, 0, length $piecepiece, = '';
938 }
939 3 $ret .= "$_\n";
940 }
941 else {
942 # Wherever whitespace is mandatory, use a line break, to avoid that more
943 # complicated string-splitting logic above. (Speeeeeeeed!) (I hope.)
944 # PDF::Extract won’t be able to read it. That’s the least of
945 # its problems.
946 1027 ▶ for (ref eq 'SCALAR' ? $$_ : $_) {
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'SCALAR' ? : 7 1020 1027
947 1027 ▶ if (length($line) and $line !~ /$D\z/o && !/^$D/o
Branch: 1 branch
BranchTrueFalseTotal
if (length $line and !($line =~ /$D\z/o || /^$D/o) || length($line) + length($_) > 254) 425 602 1027
Condition100%9/9
length $line and !($line =~ /$D\z/o || /^$D/o) || length($line) + length($_) > 254
!ll&&!rl&&r
799462
not $line =~ /$D\z/o || /^$D/o or length($line) + length($_) > 254
l!l&&r!l&&!r
4232523
$line =~ /$D\z/o || /^$D/o
l!l&&r!l&&!r
192333423
MC/DC50%2/4
length $line and !($line =~ /$D\z/o || /^$D/o) || length($line) + length($_) > 254
length $line $line =~ /$D\z/o /^$D/o length($line) + length($_) > 254
Truth table83%5/6
A and not(B || C) or D
A= length $lineB= $line =~ /$D\z/oC= /^$D/oD= length($line) + length($_) > 254
ABCDresult
0XXX0
11X00
10100
100X1
11X11
10111
948 ||length($line) + length > 254) {
949 425 $ret .= "$line\n";
950 425 $line = '';
951 }
952 1027 $line .= $_;
953 }
954 }
955 }
956 80 "$ret$line";
957 }
958  
959 sub parse_string {
960 14 ▶ parse_tokens( tokenize @_[0,1] )
Subroutine parse_string: called CC=1 SCAR=0.0
Pod undocumented
961 }
962  
963 sub parse_tokens {
964 13 ▶ my @newtokens;
Subroutine parse_tokens: called CC=3 SCAR=17.3
Pod undocumented
965 13 ▶ wantarray or return _interpret_token(\@_);
Branch: 1 branch
BranchTrueFalseTotal
wantarray or return _interpret_token(\@_) 13 0 13
966 0 ▶ while (scalar ( @_)){
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_) 0 0 0
967 0 push @newtokens, _interpret_token(\@_);
968 }
969 0 return @newtokens;
970 }
971  
972 sub _interpret_token { # pass an array ref
973 # interpret_token removes the first token or set of tokens from an
974 # array and returns the token in 'parsed object' format.
975  
976 549 ▶ my $tokens = shift;
Subroutine _interpret_token: called CC=34 SCAR=42.5
977 549 for (shift @$tokens) {
978  
979 # references:
980  
981 549 ▶ if ($_ =~ /^\d+$/ and
Branch: 10 branches
BranchTrueFalseTotal
if ($_ =~ /^\d+$/ and (@$tokens >= 2 and $tokens->[0] =~ /^\d+$/ and $tokens->[1] eq 'R')) { } 130 419 549
elsif (s[^/][]) { } 72 347 419
elsif ($_ eq '<<') { } 81 266 347
elsif ($_ eq '[') { } 54 212 266
elsif (s/^\(//) { } 14 198 212
elsif (/^[+\-]?\d+$/ or /^[+\-]?[\d\.]+$/ and tr/.// == 1) { } 179 19 198
elsif (s/^<//) { } 19 0 19
elsif ($_ eq 'true') { } 0 0 0
elsif ($_ eq 'false') { } 0 0 0
elsif ($_ eq 'null') { } 0 0 0
Condition100%9/9
$_ =~ /^\d+$/ and (@$tokens >= 2 and $tokens->[0] =~ /^\d+$/ and $tokens->[1] eq "R")
!ll&&!rl&&r
254165130
@$tokens >= 2 and $tokens->[0] =~ /^\d+$/ and $tokens->[1] eq "R"
!ll&&!rl&&r
9867130
@$tokens >= 2 and $tokens->[0] =~ /^\d+$/
!ll&&!rl&&r
1682197
MC/DC100%4/4
$_ =~ /^\d+$/ and (@$tokens >= 2 and $tokens->[0] =~ /^\d+$/ and $tokens->[1] eq "R")
$_ =~ /^\d+$/ @$tokens >= 2 $tokens->[0] =~ /^\d+$/ $tokens->[1] eq "R"
Truth table100%5/5
A and B and C and D
A= $_ =~ /^\d+$/B= @$tokens >= 2C= $tokens->[0] =~ /^\d+$/D= $tokens->[1] eq "R"
ABCDresult
0XXX0
10XX0
110X0
11100
11111
982 @$tokens >= 2 && $$tokens[0] =~ /^\d+$/
983 && $$tokens[1] eq 'R') {
984 130 my $to_return = ['ref',
985 "$_ " . (shift @$tokens)];
986 130 shift @$tokens; # shift off the 'R'
987 130 return $to_return;
988 }
989  
990 # names
991  
992 elsif (s.^/..) { # if it begins with "/"
993 # replace #XX sequences with real chars:
994 72 s/#([a-f\d]{2})/chr hex $1/gie;
995 72 return ['name', $_];
996 }
997  
998 # dictionaries:
999  
1000 elsif ($_ eq '<<') {
1001 81 my %tmp_hash;
1002 81 ▶ while(scalar @$tokens){
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @$tokens) 380 0 380
1003 380 my $name = shift @$tokens;
1004 380 ▶ if ($name eq '>>') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq '>>') { } 81 299 380
1005 81 return ['dict', \%tmp_hash];
1006 }else {
1007 299 $name =~ s.^/..;
1008 # replace #XX sequences with real chars:
1009 299 $name =~ s/#([a-f\d]{2})/chr hex $1/gie;
1010 299 $tmp_hash{$name} =
1011 _interpret_token($tokens);
1012 delete $tmp_hash{$name}
1013 299 ▶ if $tmp_hash{$name}[0] eq 'null'
Branch: 1 branch
BranchTrueFalseTotal
if $tmp_hash{$name}[0] eq "null" 0 299 299
1014 }
1015 }
1016 }
1017  
1018 # arrays:
1019  
1020 elsif ($_ eq '[') {
1021 54 my @tmp_array;
1022 54 ▶ while(scalar @$tokens){
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @$tokens) 213 0 213
1023 213 ▶ if ($$tokens[0] eq ']') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tokens->[0] eq ']') { } 54 159 213
1024 54 shift @$tokens; #shift off the "]"
1025 54 return ['array', \@tmp_array];
1026 }else {
1027 159 push @tmp_array, _interpret_token($tokens);
1028 }
1029 }
1030 }
1031  
1032 # strings
1033  
1034 elsif (s/^\(//){ #if it begins with a '('
1035 #i.e., if it's a string
1036 14 s/\)$//; # remove final ")"
1037 # and remove wack escapes:
1038 14 s,($N)|\\($N|\d{1\,3}|.), my $match = $2;
1039 38 my $unescaped = $1;
1040 38 ▶ $unescaped ? "\cj" : # EOL
Branch: 12 branches
BranchTrueFalseTotal
$unescaped ? : 2 36 38
$match =~ /$N/o ? : 32 4 36
$match =~ /\d/ ? : 0 4 4
$match eq 'n' ? : 0 4 4
$match eq 'r' ? : 4 0 4
$match eq 't' ? : 0 0 0
$match eq 'b' ? : 0 0 0
$match eq 'f' ? : 0 0 0
$match eq '(' ? : 0 0 0
$match eq ')' ? : 0 0 0
$match eq '\\' ? : 0 0 0
length $match ? : 0 0 0
1041 $match =~ /$N/o ? '' : # \EOL
1042 $match=~/\d/?chr oct$match : # octal
1043 $match eq 'n' ? "\cj" : # CR
1044 $match eq 'r' ? "\cm" : # LF
1045 $match eq 't' ? "\t" : # tab
1046 $match eq 'b' ? "\010" : # backspace
1047 $match eq 'f' ? "\x0c" : # form feed
1048 $match eq '(' ? "(" : # (
1049 $match eq ')' ? ')' : # )
1050 $match eq '\\' ? '\\' : # |
1051 length $match ? $match : # ignore backslash as per Adobe's instructions
1052 $fullmatch # anything else
1053 ,goes;
1054 14 return ['str', $_];
1055 }
1056  
1057 # numbers:
1058  
1059 ▶ elsif (/^[+\-]?\d+$/ or
Condition83%5/6
/^[+\-]?\d+$/ or /^[+\-]?[\d\.]+$/ and tr/.// == 1
l!l&&r!l&&!r
171819
/^[+\-]?[\d\.]+$/ and tr/.// == 1
!ll&&!rl&&r
1908
MC/DC66%2/3
/^[+\-]?\d+$/ or /^[+\-]?[\d\.]+$/ and tr/.// == 1
/^[+\-]?\d+$/ /^[+\-]?[\d\.]+$/ tr/.// == 1
Truth table75%3/4
A or B and C
A= /^[+\-]?\d+$/B= /^[+\-]?[\d\.]+$/C= tr/.// == 1
ABCresult
1XX1
0111
00X0
0100
1060 /^[+\-]?[\d\.]+$/ && y/.// == 1) {
1061 179 return ['num',$_];
1062 }
1063  
1064 # hex strings
1065  
1066 elsif (s/^<//){ #if it begins with a '<'
1067 19 s/>$//; # remove final ">"
1068 19 s/$S//g; #remove whitespace
1069 19 return ['str', pack "H*", $_];
1070 }
1071  
1072 # booleans:
1073  
1074 elsif ($_ eq 'true') {
1075 0 return ['bool', 1];
1076 }
1077 elsif($_ eq 'false'){
1078 0 return ['bool',''];
1079 }
1080  
1081 # null:
1082  
1083 elsif ($_ eq 'null') {
1084 0 return ['null', ];
1085 }
1086  
1087  
1088 # in case something went wrong:
1089  
1090 0 else { return ['?',$_]; }
1091 }
1092 }
1093  
1094 1 *serialise = *serialize;
1095 sub serialize {
1096 19 ▶ join_tokens(&_serialize)
Subroutine serialize: called CC=1 SCAR=0.0
Pod undocumented
1097 }
1098 sub _serialize;
1099 sub _serialize {
1100 462 ▶ for (shift) {
Subroutine _serialize: called CC=23 SCAR=33.7
1101 # numbers
1102 462 ▶ if($$_[0]eq'num'){ for ($$_[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->[0] eq "num") 135 327 462
1103 135 ▶ !$_||$_==-0 and return 0;
Branch: 1 branch
BranchTrueFalseTotal
!$_ || $_ == 0 and return 0 36 99 135
Condition66%2/3
not $_ or $_ == 0
l!l&&r!l&&!r
36099
MC/DC50%1/2
not $_ or $_ == 0
not $_ $_ == 0
Truth table66%2/3
not(A) or B
A= not $_B= $_ == 0
ABresult
1X1
011
000
1104 99 ▶ /^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]*)\z/ and return $_;
Branch: 1 branch
BranchTrueFalseTotal
/^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]*)\z/ and return $_ 99 0 99
1105 0 my $ret = 0+$_;
1106 0 ▶ return $ret unless $ret =~ /e([+-][0-9]+)/;
Branch: 1 branch
BranchTrueFalseTotal
unless $ret =~ /e([+-][0-9]+)/ 0 0 0
1107 0 $ret = sprintf"%.$1f",$ret;
1108 0 $ret =~ s/\.?0+\z//;
1109 0 return $ret;
1110 }}
1111
1112 # names
1113 327 ▶ if($$_[0]eq'name'){
Branch: 1 branch
BranchTrueFalseTotal
if ($_->[0] eq "name") 60 267 327
1114 60 for (my $copy = $$_[1]) {
1115 60 s/($D|$S|#)/sprintf'#%02x',ord$1/ego;
1116 60 return "/$_";
1117 }
1118 }
1119
1120 # dictionaries
1121 267 ▶ if ($$_[0] eq 'dict') {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->[0] eq "dict") 64 203 267
1122 64 my (@ret,$key,$key_copy);
1123 64 for $key (sort keys %{$$_[1]}) {
1124 233 ($key_copy=$key)
1125 0 =~s/($D|$S|#)/sprintf'#%02x',ord$1/ego;
1126 233 push @ret,"/$key_copy", _serialize $$_[1]{$key};
1127 }
1128 64 return"<<",@ret,">>";
1129 }
1130
1131 # indirect references
1132 203 ▶ $$_[0] eq 'ref' and return split(/ /,$$_[1]), "R";
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] eq "ref" and return split(/ /, $_->[1], 0), "R" 101 102 203
1133  
1134 # arrays
1135 102 ▶ if ($$_[0]eq'array'){
Branch: 1 branch
BranchTrueFalseTotal
if ($_->[0] eq "array") 43 59 102
1136 43 my (@ret);
1137 43 for(@{$$_[1]}){
1138 124 push @ret, _serialize$_;
1139 }
1140 43 return "[",@ret,"]";
1141 }
1142
1143 # screams
1144 59 ▶ if ($$_[0]eq'stream'){
Branch: 1 branch
BranchTrueFalseTotal
if ($_->[0] eq "stream") 14 45 59
1145 14 return _serialize($$_[1]), "stream\n"
1146 }
1147
1148 # strings
1149 45 ▶ if($$_[0]eq 'str'){
Branch: 1 branch
BranchTrueFalseTotal
if ($_->[0] eq "str") 32 13 45
1150 # copy it so we don't modify the object being flattened
1151 32 for (my $ret = $$_[1]) {
1152 32 ▶ s/([\\()\r])/$1 eq "\r" ? '\r' : "\\$1"/ge;
Branch: 1 branch
BranchTrueFalseTotal
$1 eq "\r" ? : 11 0 11
1153 32 return"($_)";
1154 }
1155 }
1156
1157 13 ▶ $$_[0]eq'tokens'&&return@{$$_[1]};
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] eq "tokens" and return @{$_->[1];} 6 7 13
1158
1159 # booleans
1160 7 ▶ $$_[0]eq'bool'&&return+(false=>'true')[$$_[1]];
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] eq "bool" and return ("false", "true")[$_->[1]] 0 7 7
1161
1162 7 ▶ $$_[0]eq'flat'&&return\$$_[1];
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] eq "flat" and return \$_->[1] 7 0 7
1163
1164 0 ▶ $$_[0]eq'null'&&return'null';
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] eq "null" and return "null" 0 0 0
1165
1166 # If we get this far, then there's probably an empty array element or hash value which is not supposed to be there, so we shouldn't return anything.
1167 }
1168 }
1169  
1170 1 for (qw< bool num str name array dict ref>) {
1171 2 ▶ eval "sub make_$_ { ['$_', \$_[0] ] }"
Subroutine make_array: called CC=1 SCAR=0.0
Subroutine make_bool: not called CC=1 SCAR=0.0
Subroutine make_dict: called CC=1 SCAR=0.0
Subroutine make_name: called CC=1 SCAR=0.0
Subroutine make_num: called CC=1 SCAR=0.0
Subroutine make_ref: called CC=1 SCAR=0.0
Subroutine make_str: called CC=1 SCAR=0.0
Pod undocumented
Pod undocumented
Pod undocumented
Pod undocumented
Pod undocumented
Pod undocumented
Pod undocumented
1172 }
1173  
1174  
1175  
1176  
1177 1 !()__END__()!
1178  
↑ Summary