Mojo/Util.pm

filter: Statementstmt 93.9% 385 / 410 Branchbran 86.9% 153 / 176 Conditioncond 79.3% 73 / 92 MC/DCmcdc 59.6% 31 / 52 Subroutinesub 97.5% 78 / 80 Podpod 100% 37 / 37 totaltotal 89.3% 757 / 847 CC 124 SCAR 20.6
CC
124
Cov
90%
random_bytes
41.8
_entity
13.0
punycode_encode
12.0
CRAP 7.8
« Mojolicious/Controller.pm ↑ Summary Mojo/UserAgent.pm »
1 package Mojo::Util;
2 64 ▶use Mojo::Base -strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 64 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 64 ▶use Data::Dumper ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 64 ▶use Digest::MD5 qw(md5 md5_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 64 ▶use Digest::SHA qw(hmac_sha1_hex sha1 sha1_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 64 ▶use Encode qw(find_encoding);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 64 ▶use Errno ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 64 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 64 ▶use File::Basename qw(dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 64 ▶use Getopt::Long qw(GetOptionsFromArray);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 64 ▶use IO::Compress::Gzip;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 64 ▶use IO::Poll qw(POLLIN POLLPRI);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 64 ▶use IO::Uncompress::Gunzip;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 64 ▶use List::Util qw(min);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 64 ▶use MIME::Base64 qw(decode_base64 encode_base64 encode_base64url);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 64 ▶use Mojo::BaseUtil qw(class_to_path monkey_patch);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 64 ▶use Pod::Usage qw(pod2usage);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 64 ▶use Socket qw(inet_pton AF_INET6 AF_INET);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 64 ▶use Symbol qw(delete_package);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 64 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 64 ▶use Unicode::Normalize ();
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 # Encryption support requires CryptX 0.080+
26 64 ▶use constant CRYPTX => $ENV{MOJO_NO_CRYPTX} ? 0 : !!(eval {
Subroutine BEGIN: called CC=2 SCAR=10.3
Branch: 1 branch
BranchTrueFalseTotal
$ENV{'MOJO_NO_CRYPTX'} ? : 0 64 64
27 64 require CryptX;
28 0 require Crypt::AuthEnc::ChaCha20Poly1305;
29 0 require Crypt::KeyDerivation;
30 0 require Crypt::Misc;
31 0 require Crypt::PRNG;
32 0 CryptX->VERSION('0.080');
33 0 1;
34 64 });
35 64 ▶use constant WIN32_API => eval { require Win32::API };
Subroutine BEGIN: called CC=1 SCAR=0.0
36  
37 # Check for monotonic clock support
38 64 ▶use constant MONOTONIC => !!eval { Time::HiRes::clock_gettime(Time::HiRes::CLOCK_MONOTONIC()) };
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 # Punycode bootstring parameters
41 64 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
42 64 PC_BASE => 36,
43 PC_TMIN => 1,
44 PC_TMAX => 26,
45 PC_SKEW => 38,
46 PC_DAMP => 700,
47 PC_INITIAL_BIAS => 72,
48 PC_INITIAL_N => 128
49 64 };
50  
51 # To generate a new HTML entity table run this command
52 # perl examples/entities.pl > lib/Mojo/resources/html_entities.txt
53 64 my %ENTITIES;
54 {
55 # Don't use Mojo::File here due to circular dependencies
56 64 my $path = File::Spec->catfile(dirname(__FILE__), 'resources', 'html_entities.txt');
57  
58 64 ▶ open my $file, '<', $path or croak "Unable to open html entities file ($path): $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $file, "<", $path or croak("Unable to open html entities file ($path): $!") 64 0 64
59 64 my $lines = do { local $/; <$file> };
60  
61 64 for my $line (split /\n/, $lines) {
62 142784 ▶ next unless $line =~ /^(\S+)\s+U\+(\S+)(?:\s+U\+(\S+))?/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /^(\S+)\s+U\+(\S+)(?:\s+U\+(\S+))?/u 0 142784 142784
63 142784 ▶ $ENTITIES{$1} = defined $3 ? (chr(hex $2) . chr(hex $3)) : chr(hex $2);
Branch: 1 branch
BranchTrueFalseTotal
defined $3 ? : 5952 136832 142784
64 }
65 }
66  
67 # Characters that should be escaped in XML
68 64 my %XML = ('&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', '\'' => '&#39;');
69  
70 # Numeric character references to C1 controls are remapped through windows-1252 (WHATWG HTML)
71 64 my %C1 = (
72 0x80 => 0x20AC,
73 0x82 => 0x201A,
74 0x83 => 0x0192,
75 0x84 => 0x201E,
76 0x85 => 0x2026,
77 0x86 => 0x2020,
78 0x87 => 0x2021,
79 0x88 => 0x02C6,
80 0x89 => 0x2030,
81 0x8A => 0x0160,
82 0x8B => 0x2039,
83 0x8C => 0x0152,
84 0x8E => 0x017D,
85 0x91 => 0x2018,
86 0x92 => 0x2019,
87 0x93 => 0x201C,
88 0x94 => 0x201D,
89 0x95 => 0x2022,
90 0x96 => 0x2013,
91 0x97 => 0x2014,
92 0x98 => 0x02DC,
93 0x99 => 0x2122,
94 0x9A => 0x0161,
95 0x9B => 0x203A,
96 0x9C => 0x0153,
97 0x9E => 0x017E,
98 0x9F => 0x0178
99 );
100  
101 # "Sun, 06 Nov 1994 08:49:37 GMT" and "Sunday, 06-Nov-94 08:49:37 GMT"
102 64 my $EXPIRES_RE = qr/(\w+\W+\d+\W+\w+\W+\d+\W+\d+:\d+:\d+\W*\w+)/;
103  
104 # Header key/value pairs
105 64 my $QUOTED_VALUE_RE = qr/\G=\s*("(?:\\\\|\\"|[^"])*")/;
106 64 my $UNQUOTED_VALUE_RE = qr/\G=\s*([^;, ]*)/;
107  
108 # HTML entities
109 64 my $ENTITY_RE = qr/&(?:\#((?:[0-9]{1,7}|x[0-9a-fA-F]{1,6}));|(\w+[;=]?))/;
110  
111 # Encoding, encryption and pattern caches
112 64 my (%ENCODING, %ENCRYPTION, %PATTERN);
113  
114 64 our @EXPORT_OK = (
115 qw(b64_decode b64_encode camelize class_to_file class_to_path decamelize decode decrypt_cookie deprecated dumper),
116 qw(encode encrypt_cookie extract_usage generate_secret getopt gunzip gzip header_params hmac_sha1_sum),
117 qw(html_attr_unescape html_unescape humanize_bytes md5_bytes md5_sum monkey_patch network_contains punycode_decode),
118 qw(punycode_encode quote random_bytes scope_guard secure_compare sha1_bytes sha1_sum slugify split_cookie_header),
119 qw(split_header steady_time tablify term_escape trim unindent unquote url_escape url_unescape xml_escape xor_encode)
120 );
121  
122 # Aliases
123 64 monkey_patch(__PACKAGE__, 'b64_decode', \&decode_base64);
124 64 monkey_patch(__PACKAGE__, 'b64_encode', \&encode_base64);
125 64 monkey_patch(__PACKAGE__, 'hmac_sha1_sum', \&hmac_sha1_hex);
126 64 monkey_patch(__PACKAGE__, 'md5_bytes', \&md5);
127 64 monkey_patch(__PACKAGE__, 'md5_sum', \&md5_hex);
128 64 monkey_patch(__PACKAGE__, 'sha1_bytes', \&sha1);
129 64 monkey_patch(__PACKAGE__, 'sha1_sum', \&sha1_hex);
130  
131 # Use a monotonic clock if possible
132 monkey_patch(__PACKAGE__, 'steady_time',
133 216105 ▶ MONOTONIC ? sub () { Time::HiRes::clock_gettime(Time::HiRes::CLOCK_MONOTONIC()) } : \&Time::HiRes::time);
Subroutine steady_time: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
134  
135 111 ▶sub camelize {
Subroutine camelize: called CC=2 SCAR=6.9
Pod documented
136 111 my $str = shift;
137 111 ▶ return $str if $str =~ /^[A-Z]/;
Branch: 1 branch
BranchTrueFalseTotal
if $str =~ /^[A-Z]/u 18 93 111
138  
139 # CamelCase words
140 return join '::', map {
141 93 join('', map { ucfirst lc } split /_/)
142 } split /-/, $str;
143 }
144  
145 10 ▶sub class_to_file {
Subroutine class_to_file: called CC=1 SCAR=0.0
Pod documented
146 10 my $class = shift;
147 10 $class =~ s/::|'//g;
148 10 $class =~ s/([A-Z])([A-Z]*)/$1 . lc $2/ge;
149 10 return decamelize($class);
150 }
151  
152 48 ▶sub decamelize {
Subroutine decamelize: called CC=2 SCAR=6.9
Pod documented
153 48 my $str = shift;
154 48 ▶ return $str if $str !~ /^[A-Z]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $str =~ /^[A-Z]/u 17 31 48
155  
156 # snake_case words
157 return join '-', map {
158 31 join('_', map {lc} grep {length} split /([A-Z]{1}[^A-Z]*)/)
159 } split /::/, $str;
160 }
161  
162 0 ▶sub decrypt_cookie {
Subroutine decrypt_cookie: not called CC=3 SCAR=24.8
Pod documented
163 0 my ($value, $key, $salt) = @_;
164 0 croak 'CryptX 0.080+ required for encrypted cookie support' unless CRYPTX;
165  
166 0 ▶ return undef unless $value =~ /^([^-]+)-([^-]+)-([^-]+)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $value =~ /^([^-]+)-([^-]+)-([^-]+)$/u 0 0 0
167 0 my ($ct, $iv, $tag) = ($1, $2, $3);
168 0 ($ct, $iv, $tag) = (Crypt::Misc::decode_b64($ct), Crypt::Misc::decode_b64($iv), Crypt::Misc::decode_b64($tag));
169  
170 0 ▶ my $dk = $ENCRYPTION{$key}{$salt} ||= Crypt::KeyDerivation::pbkdf2($key, $salt);
Condition0%0/3
$ENCRYPTION{$key}{$salt} ||= Crypt::KeyDerivation::pbkdf2($key, $salt)
l!l&&r!l&&!r
000
MC/DC0%0/2
$ENCRYPTION{$key}{$salt} ||= Crypt::KeyDerivation::pbkdf2($key, $salt)
$ENCRYPTION{$key}{$salt} Crypt::KeyDerivation::pbkdf2($key, $salt)
Truth table0%0/3
A ||= B
A= $ENCRYPTION{$key}{$salt}B= Crypt::KeyDerivation::pbkdf2($key, $salt)
ABresult
1X1
011
000
171 0 return Crypt::AuthEnc::ChaCha20Poly1305::chacha20poly1305_decrypt_verify($dk, $iv, '', $ct, $tag);
172 }
173  
174 2203 ▶sub decode {
Subroutine decode: called CC=4 SCAR=13.9
Pod documented
175 2203 my ($encoding, $bytes) = @_;
176 2203 ▶ return "$bytes" if $encoding eq 'UTF-8' && $bytes !~ /[^\x00-\x7f]/; # ASCII is valid UTF-8
Branch: 1 branch
BranchTrueFalseTotal
if $encoding eq "UTF-8" and not $bytes =~ /[^\x00-\x7f]/u 2091 112 2203
Condition100%3/3
$encoding eq "UTF-8" and not $bytes =~ /[^\x00-\x7f]/u
!ll&&!rl&&r
111012091
MC/DC100%2/2
$encoding eq "UTF-8" and not $bytes =~ /[^\x00-\x7f]/u
$encoding eq "UTF-8" not $bytes =~ /[^\x00-\x7f]/u
Truth table100%3/3
A and not(B)
A= $encoding eq "UTF-8"B= not $bytes =~ /[^\x00-\x7f]/u
ABresult
0X0
100
111
177 112 ▶ return undef unless eval { $bytes = _encoding($encoding)->decode("$bytes", 1); 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $bytes = _encoding($encoding)->decode("$bytes", 1); 1 } } 41 71 112
178 71 return $bytes;
179 }
180  
181 2 ▶sub deprecated {
Subroutine deprecated: called CC=2 SCAR=6.9
Pod documented
182 2 local $Carp::CarpLevel = 1;
183 2 ▶ $ENV{MOJO_FATAL_DEPRECATIONS} ? croak @_ : carp @_;
Branch: 1 branch
BranchTrueFalseTotal
$ENV{'MOJO_FATAL_DEPRECATIONS'} ? : 1 1 2
184 }
185  
186 100 ▶sub dumper { Data::Dumper->new([@_])->Indent(1)->Sortkeys(1)->Terse(1)->Useqq(1)->Dump }
Subroutine dumper: called CC=1 SCAR=0.0
Pod documented
187  
188 3337 ▶sub encode {
Subroutine encode: called CC=3 SCAR=11.0
Pod documented
189 3337 ▶ return _encoding($_[0])->encode("$_[1]", 0) unless $_[0] eq 'UTF-8' && $_[1] !~ /[^\x00-\x7f]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] eq "UTF-8" and not $_[1] =~ /[^\x00-\x7f]/u 103 3234 3337
Condition100%3/3
$_[0] eq "UTF-8" and not $_[1] =~ /[^\x00-\x7f]/u
!ll&&!rl&&r
14893234
MC/DC100%2/2
$_[0] eq "UTF-8" and not $_[1] =~ /[^\x00-\x7f]/u
$_[0] eq "UTF-8" not $_[1] =~ /[^\x00-\x7f]/u
Truth table100%3/3
A and not(B)
A= $_[0] eq "UTF-8"B= not $_[1] =~ /[^\x00-\x7f]/u
ABresult
0X0
100
111
190 3234 utf8::downgrade(my $bytes = "$_[1]"); # ASCII stays the same in UTF-8
191 3234 return $bytes;
192 }
193  
194 0 ▶sub encrypt_cookie {
Subroutine encrypt_cookie: not called CC=2 SCAR=17.9
Pod documented
195 0 my ($value, $key, $salt) = @_;
196 0 croak 'CryptX 0.080+ required for encrypted cookie support' unless CRYPTX;
197  
198 0 ▶ my $dk = $ENCRYPTION{$key}{$salt} ||= Crypt::KeyDerivation::pbkdf2($key, $salt);
Condition0%0/3
$ENCRYPTION{$key}{$salt} ||= Crypt::KeyDerivation::pbkdf2($key, $salt)
l!l&&r!l&&!r
000
MC/DC0%0/2
$ENCRYPTION{$key}{$salt} ||= Crypt::KeyDerivation::pbkdf2($key, $salt)
$ENCRYPTION{$key}{$salt} Crypt::KeyDerivation::pbkdf2($key, $salt)
Truth table0%0/3
A ||= B
A= $ENCRYPTION{$key}{$salt}B= Crypt::KeyDerivation::pbkdf2($key, $salt)
ABresult
1X1
011
000
199 0 my $iv = Crypt::PRNG::random_bytes(12);
200 0 my ($ct, $tag) = Crypt::AuthEnc::ChaCha20Poly1305::chacha20poly1305_encrypt_authenticate($dk, $iv, '', $value);
201  
202 0 return join '-', Crypt::Misc::encode_b64($ct), Crypt::Misc::encode_b64($iv), Crypt::Misc::encode_b64($tag);
203 }
204  
205 26 ▶sub extract_usage {
Subroutine extract_usage: called CC=2 SCAR=6.9
Pod documented
206 26 ▶ my $file = @_ ? "$_[0]" : (caller)[1];
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 25 1 26
207  
208 26 open my $handle, '>', \my $output;
209 26 pod2usage -exitval => 'noexit', -input => $file, -output => $handle;
210 26 $output =~ s/^.*\n|\n$//;
211 26 $output =~ s/\n$//;
212  
213 26 return unindent($output);
214 }
215  
216 2 ▶sub generate_secret {
Subroutine generate_secret: called CC=1 SCAR=0.0
Pod documented
217 2 return encode_base64url(random_bytes(128));
218 }
219  
220 79 ▶sub getopt {
Subroutine getopt: called CC=2 SCAR=6.9
Pod documented
221 79 ▶ my ($array, $opts) = map { ref $_[0] eq 'ARRAY' ? shift : $_ } \@ARGV, [];
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'ARRAY' ? : 122 36 158
222  
223 79 my $save = Getopt::Long::Configure(qw(default no_auto_abbrev no_ignore_case), @$opts);
224 79 my $result = GetOptionsFromArray $array, @_;
225 79 Getopt::Long::Configure($save);
226  
227 79 return $result;
228 }
229  
230 4 ▶sub gunzip {
Subroutine gunzip: called CC=2 SCAR=7.1
Pod documented
231 4 my $compressed = shift;
232 4 ▶ IO::Uncompress::Gunzip::gunzip \$compressed, \my $uncompressed
Branch: 1 branch
BranchTrueFalseTotal
IO::Uncompress::Gunzip::gunzip(\$compressed, \my $uncompressed) or croak("Couldn't gunzip: $IO::Uncompress::Gunzip::GzipError") 4 0 4
233 or croak "Couldn't gunzip: $IO::Uncompress::Gunzip::GzipError";
234 4 return $uncompressed;
235 }
236  
237 24 ▶sub gzip {
Subroutine gzip: called CC=2 SCAR=7.1
Pod documented
238 24 my $uncompressed = "" . shift;
239 24 ▶ IO::Compress::Gzip::gzip \$uncompressed, \my $compressed or croak "Couldn't gzip: $IO::Compress::Gzip::GzipError";
Branch: 1 branch
BranchTrueFalseTotal
IO::Compress::Gzip::gzip(\$uncompressed, \my $compressed) or croak("Couldn't gzip: $IO::Compress::Gzip::GzipError") 24 0 24
240 24 return $compressed;
241 }
242  
243 16 ▶sub header_params {
Subroutine header_params: called CC=7 SCAR=19.5
Pod documented
244 16 my $value = shift;
245  
246 16 my $params = {};
247 16 ▶ while ($value =~ /\G[;\s]*([^=;, ]+)\s*/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /\G[;\s]*([^=;, ]+)\s*/cgu) 20 16 36
248 20 my $name = $1;
249  
250 # Quoted value
251 20 ▶ if ($value =~ /$QUOTED_VALUE_RE/gco) { $params->{$name} //= unquote($1) }
Branch: 2 branches
BranchTrueFalseTotal
if ($value =~ /$QUOTED_VALUE_RE/cgou) { } 4 16 20
elsif ($value =~ /$UNQUOTED_VALUE_RE/cgou) { } 15 1 16
Condition66%2/3
$params->{$name} //= unquote($1)
l!l&&r!l&&!r
130
MC/DC0%0/2
$params->{$name} //= unquote($1)
$params->{$name} unquote($1)
Truth table66%2/3
A //= B
A= $params->{$name}B= unquote($1)
ABresult
1X1
011
000
252  
253 # Unquoted value
254 15 ▶ elsif ($value =~ /$UNQUOTED_VALUE_RE/gco) { $params->{$name} //= $1 }
Condition66%2/3
$params->{$name} //= $1
l!l&&r!l&&!r
1140
MC/DC0%0/2
$params->{$name} //= $1
$params->{$name} $1
Truth table66%2/3
A //= B
A= $params->{$name}B= $1
ABresult
1X1
011
000
255 }
256  
257 16 ▶ return ($params, substr($value, pos($value) // 0));
Condition100%2/2
pos $value // 0
l!l
133
MC/DC100%1/1
pos $value // 0
pos $value
Truth table100%2/2
A
A= pos $value
Aresult
11
00
258 }
259  
260 33074 ▶sub html_attr_unescape { _html(shift, 1) }
Subroutine html_attr_unescape: called CC=1 SCAR=0.0
Pod documented
261 1479 ▶sub html_unescape { _html(shift, 0) }
Subroutine html_unescape: called CC=1 SCAR=0.0
Pod documented
262  
263 19 ▶sub humanize_bytes {
Subroutine humanize_bytes: called CC=6 SCAR=17.9
Pod documented
264 19 my $size = shift;
265  
266 19 ▶ my $prefix = $size < 0 ? '-' : '';
Branch: 1 branch
BranchTrueFalseTotal
$size < 0 ? : 6 13 19
267  
268 19 ▶ return "$prefix${size}B" if ($size = abs $size) < 1024;
Branch: 1 branch
BranchTrueFalseTotal
if ($size = abs $size) < 1024 3 16 19
269 16 ▶ return $prefix . _round($size) . 'KiB' if ($size /= 1024) < 1024;
Branch: 1 branch
BranchTrueFalseTotal
if ($size /= 1024) < 1024 5 11 16
270 11 ▶ return $prefix . _round($size) . 'MiB' if ($size /= 1024) < 1024;
Branch: 1 branch
BranchTrueFalseTotal
if ($size /= 1024) < 1024 3 8 11
271 8 ▶ return $prefix . _round($size) . 'GiB' if ($size /= 1024) < 1024;
Branch: 1 branch
BranchTrueFalseTotal
if ($size /= 1024) < 1024 6 2 8
272 2 return $prefix . _round($size /= 1024) . 'TiB';
273 }
274  
275 62 ▶sub network_contains {
Subroutine network_contains: called CC=11 SCAR=24.0
Pod documented
276 62 my ($cidr, $addr) = @_;
277 62 ▶ return undef unless length $cidr && length $addr;
Branch: 1 branch
BranchTrueFalseTotal
unless length $cidr and length $addr 2 60 62
Condition100%3/3
length $cidr and length $addr
!ll&&!rl&&r
1160
MC/DC100%2/2
length $cidr and length $addr
length $cidr length $addr
Truth table100%3/3
A and B
A= length $cidrB= length $addr
ABresult
0X0
100
111
278  
279 # Parse inputs
280 60 my ($net, $mask) = split m!/!, $cidr, 2;
281 60 my $v6 = $net =~ /:/;
282 60 ▶ return undef if $v6 xor $addr =~ /:/;
Branch: 1 branch
BranchTrueFalseTotal
if $v6 xor $addr =~ /:/u 2 58 60
Condition100%4/4
$v6 xor $addr =~ /:/u
l&&rl&&!r!l&&r!l&&!r
361122
MC/DC100%2/2
$v6 xor $addr =~ /:/u
$v6 $addr =~ /:/u
Truth table100%4/4
A xor B
A= $v6B= $addr =~ /:/u
ABresult
110
101
011
000
283  
284 # Convert addresses to binary
285 58 ▶ return undef unless $net = inet_pton($v6 ? AF_INET6 : AF_INET, $net);
Branch: 2 branches
BranchTrueFalseTotal
unless $net = inet_pton($v6 ? 10 : 2, $net) 2 56 58
$v6 ? : 36 22 58
286 56 ▶ return undef unless $addr = inet_pton($v6 ? AF_INET6 : AF_INET, $addr);
Branch: 2 branches
BranchTrueFalseTotal
unless $addr = inet_pton($v6 ? 10 : 2, $addr) 2 54 56
$v6 ? : 35 21 56
287 54 ▶ my $length = $v6 ? 128 : 32;
Branch: 1 branch
BranchTrueFalseTotal
$v6 ? : 34 20 54
288  
289 # Apply mask if given
290 54 ▶ $addr &= pack "B$length", '1' x $mask if defined $mask;
Branch: 1 branch
BranchTrueFalseTotal
if defined $mask 48 6 54
291  
292 # Compare
293 54 return 0 == unpack "B$length", ($net ^ $addr);
294 }
295  
296 # Direct translation of RFC 3492
297 25 ▶sub punycode_decode {
Subroutine punycode_decode: called CC=7 SCAR=19.5
Pod documented
298 25 my $input = shift;
299 64 ▶ use integer;
Subroutine BEGIN: called CC=1 SCAR=0.0
300  
301 25 my ($n, $i, $bias, @output) = (PC_INITIAL_N, 0, PC_INITIAL_BIAS);
302  
303 # Consume all code points before the last delimiter
304 25 ▶ push @output, split(//, $1) if $input =~ s/(.*)\x2d//s;
Branch: 1 branch
BranchTrueFalseTotal
if $input =~ s/(.*)\x2d//su 13 12 25
305  
306 25 ▶ while (length $input) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $input) 223 25 248
307 223 my ($oldi, $w) = ($i, 1);
308  
309 # Base to infinity in steps of base
310 223 for (my $k = PC_BASE; 1; $k += PC_BASE) {
311 472 my $digit = ord substr $input, 0, 1, '';
312 472 ▶ $digit = $digit < 0x40 ? $digit + (26 - 0x30) : ($digit & 0x1f) - 1;
Branch: 1 branch
BranchTrueFalseTotal
$digit < 64 ? : 146 326 472
313 472 $i += $digit * $w;
314 472 my $t = $k - $bias;
315 472 ▶ $t = $t < PC_TMIN ? PC_TMIN : $t > PC_TMAX ? PC_TMAX : $t;
Branch: 2 branches
BranchTrueFalseTotal
$t < 1 ? : 91 381 472
$t > 26 ? : 281 100 381
316 472 ▶ last if $digit < $t;
Branch: 1 branch
BranchTrueFalseTotal
if $digit < $t 223 249 472
317 249 $w *= PC_BASE - $t;
318 }
319  
320 223 $bias = _adapt($i - $oldi, @output + 1, $oldi == 0);
321 223 $n += $i / (@output + 1);
322 223 $i = $i % (@output + 1);
323 223 splice @output, $i++, 0, chr $n;
324 }
325  
326 25 return join '', @output;
327 }
328  
329 # Direct translation of RFC 3492
330 66 ▶sub punycode_encode {
Subroutine punycode_encode: called CC=12 SCAR=24.8
Pod documented
331 66 my $output = shift;
332 64 ▶ use integer;
Subroutine BEGIN: called CC=1 SCAR=0.0
333  
334 66 my ($n, $delta, $bias) = (PC_INITIAL_N, 0, PC_INITIAL_BIAS);
335  
336 # Extract basic code points
337 66 my @input = map {ord} split //, $output;
338 66 $output =~ s/[^\x00-\x7f]+//gs;
339 66 my $h = my $basic = length $output;
340 66 ▶ $output .= "\x2d" if $basic > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $basic > 0 42 24 66
341  
342 66 for my $m (sort { $a <=> $b } grep { $_ >= PC_INITIAL_N } @input) {
343 264 ▶ next if $m < $n;
Branch: 1 branch
BranchTrueFalseTotal
if $m < $n 42 222 264
344 222 $delta += ($m - $n) * ($h + 1);
345 222 $n = $m;
346  
347 222 for my $c (@input) {
348  
349 3643 ▶ if ($c < $n) { $delta++ }
Branch: 2 branches
BranchTrueFalseTotal
if ($c < $n) { } 2039 1604 3643
elsif ($c == $n) { } 264 1340 1604
350 elsif ($c == $n) {
351 264 my $q = $delta;
352  
353 # Base to infinity in steps of base
354 264 for (my $k = PC_BASE; 1; $k += PC_BASE) {
355 595 my $t = $k - $bias;
356 595 ▶ $t = $t < PC_TMIN ? PC_TMIN : $t > PC_TMAX ? PC_TMAX : $t;
Branch: 2 branches
BranchTrueFalseTotal
$t < 1 ? : 173 422 595
$t > 26 ? : 322 100 422
357 595 ▶ last if $q < $t;
Branch: 1 branch
BranchTrueFalseTotal
if $q < $t 264 331 595
358 331 my $o = $t + (($q - $t) % (PC_BASE - $t));
359 331 ▶ $output .= chr $o + ($o < 26 ? 0x61 : 0x30 - 26);
Branch: 1 branch
BranchTrueFalseTotal
$o < 26 ? : 173 158 331
360 331 $q = ($q - $t) / (PC_BASE - $t);
361 }
362  
363 264 ▶ $output .= chr $q + ($q < 26 ? 0x61 : 0x30 - 26);
Branch: 1 branch
BranchTrueFalseTotal
$q < 26 ? : 264 0 264
364 264 $bias = _adapt($delta, $h + 1, $h == $basic);
365 264 $delta = 0;
366 264 $h++;
367 }
368 }
369  
370 222 $delta++;
371 222 $n++;
372 }
373  
374 66 return $output;
375 }
376  
377 21 ▶sub quote {
Subroutine quote: called CC=1 SCAR=0.0
Pod documented
378 21 my $str = shift;
379 21 $str =~ s/(["\\])/\\$1/g;
380 21 return qq{"$str"};
381 }
382  
383 5 ▶sub random_bytes {
Subroutine random_bytes: called CC=14 SCAR=37.3
Pod documented
384 5 my ($count) = @_;
385 5 ▶ croak 'Byte count must be a defined, non-negative integer' unless defined $count && $count =~ /\A\d+\z/a;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $count and $count =~ /\A\d+\z/a 0 5 5
Condition33%1/3
defined $count and $count =~ /\A\d+\z/a
!ll&&!rl&&r
005
MC/DC0%0/2
defined $count and $count =~ /\A\d+\z/a
defined $count $count =~ /\A\d+\z/a
Truth table33%1/3
A and B
A= defined $countB= $count =~ /\A\d+\z/a
ABresult
0X0
100
111
386 5 ▶ if (CRYPTX) {
Branch: 2 branches
BranchTrueFalseTotal
if (do { &WIN32_API() }) { } 0 5 5
elsif (-e '/dev/urandom') { } 5 0 5
387 return Crypt::PRNG::random_bytes($count);
388 }
389 elsif (WIN32_API) {
390 0 ▶ state $genrand = Win32::API->new('advapi32', 'INT SystemFunction036(PVOID RandomBuffer, ULONG RandomBufferLength)')
Branch: 1 branch
BranchTrueFalseTotal
state $genrand = "Win32::API"->new("advapi32", "INT SystemFunction036(PVOID RandomBuffer, ULONG RandomBufferLength)") or die "Could not import SystemFunction036: $^E" 0 0 0
391 or die "Could not import SystemFunction036: $^E";
392 0 ▶ return '' if $count == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $count == 0 0 0 0
393 0 my $buffer = chr(0) x $count;
394 0 ▶ $genrand->Call($buffer, $count) or croak("Could not read random bytes");
Branch: 1 branch
BranchTrueFalseTotal
$genrand->Call($buffer, $count) or croak("Could not read random bytes") 0 0 0
395 0 return $buffer;
396 }
397 elsif (-e '/dev/urandom') {
398 5 ▶ open my $fh, '<:raw', '/dev/urandom' or die "Couldn't open /dev/urandom: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", "/dev/urandom" or die "Couldn't open /dev/urandom: $!" 5 0 5
399 5 my ($result, $offset) = ('', 0);
400 5 ▶ while ($offset < $count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset < $count) 5 5 10
401 5 my $read = sysread $fh, $result, $count - $offset, $offset;
402 5 ▶ next if not defined $read and $!{EINTR};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $read and $!{"EINTR"} 0 5 5
Condition33%1/3
not defined $read and $!{"EINTR"}
!ll&&!rl&&r
500
MC/DC0%0/2
not defined $read and $!{"EINTR"}
not defined $read $!{"EINTR"}
Truth table33%1/3
not(A) and B
A= not defined $readB= $!{"EINTR"}
ABresult
0X0
100
111
403 5 ▶ croak("Could not read random bytes") if not defined $read or $read == 0;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $read or $read == 0 0 5 5
Condition33%1/3
not defined $read or $read == 0
l!l&&r!l&&!r
005
MC/DC0%0/2
not defined $read or $read == 0
not defined $read $read == 0
Truth table33%1/3
not(A) or B
A= not defined $readB= $read == 0
ABresult
1X1
011
000
404 5 $offset += $read;
405 }
406 5 return $result;
407 }
408 else {
409 0 die "Can't find source of randomness on your system, consider installing CryptX";
410 }
411 }
412  
413 16 ▶sub scope_guard { Mojo::Util::_Guard->new(cb => shift) }
Subroutine scope_guard: called CC=1 SCAR=0.0
Pod documented
414  
415 21 ▶sub secure_compare {
Subroutine secure_compare: called CC=3 SCAR=11.0
Pod documented
416 21 my ($one, $two) = @_;
417 21 my $r = length $one != length $two;
418 21 ▶ $two = $one if $r;
Branch: 1 branch
BranchTrueFalseTotal
if $r 6 15 21
419 21 $r |= ord(substr $one, $_) ^ ord(substr $two, $_) for 0 .. length($one) - 1;
420 21 return $r == 0;
421 }
422  
423 14 ▶sub slugify {
Subroutine slugify: called CC=2 SCAR=6.9
Pod documented
424 14 my ($value, $allow_unicode) = @_;
425  
426 14 ▶ if ($allow_unicode) {
Branch: 1 branch
BranchTrueFalseTotal
if ($allow_unicode) { } 6 8 14
427  
428 # Force unicode semantics by upgrading string
429 6 utf8::upgrade($value = Unicode::Normalize::NFKC($value));
430 6 $value =~ s/[^\w\s-]+//g;
431 }
432 else {
433 8 $value = Unicode::Normalize::NFKD($value);
434 8 $value =~ s/[^a-zA-Z0-9_\p{PosixSpace}-]+//g;
435 }
436 14 (my $new = lc trim($value)) =~ s/[-\s]+/-/g;
437  
438 14 return $new;
439 }
440  
441 207 ▶sub split_cookie_header { _header(shift, 1) }
Subroutine split_cookie_header: called CC=1 SCAR=0.0
Pod documented
442 71 ▶sub split_header { _header(shift, 0) }
Subroutine split_header: called CC=1 SCAR=0.0
Pod documented
443  
444 18 ▶sub tablify {
Subroutine tablify: called CC=6 SCAR=17.9
Pod documented
445 18 my $rows = shift;
446  
447 18 my @spec;
448 18 for my $row (@$rows) {
449 87 for my $i (0 .. $#$row) {
450 176 ▶ ($row->[$i] //= '') =~ y/\r\n//d;
Condition100%2/2
$row->[$i] //= ""
l!l
1742
MC/DC100%1/1
$row->[$i] //= ""
$row->[$i]
Truth table100%2/2
A
A= $row->[$i]
Aresult
11
00
451 176 my $len = length $row->[$i];
452 176 ▶ $spec[$i] = $len if $len >= ($spec[$i] // 0);
Branch: 1 branch
BranchTrueFalseTotal
if $len >= ($spec[$i] // 0) 83 93 176
Condition100%2/2
$spec[$i] // 0
l!l
13541
MC/DC100%1/1
$spec[$i] // 0
$spec[$i]
Truth table100%2/2
A
A= $spec[$i]
Aresult
11
00
453 }
454 }
455  
456 18 my @fm = (map({"\%-${_}s"} @spec[0 .. $#spec - 1]), '%s');
457 18 return join '', map { sprintf join(' ', @fm[0 .. $#$_]) . "\n", @$_ } @$rows;
458 }
459  
460 4 ▶sub term_escape {
Subroutine term_escape: called CC=1 SCAR=0.0
Pod documented
461 4 my $str = shift;
462 4 $str =~ s/([\x00-\x09\x0b-\x1f\x7f\x80-\x9f])/sprintf '\\x%02x', ord $1/ge;
463 4 return $str;
464 }
465  
466 1322 ▶sub trim {
Subroutine trim: called CC=1 SCAR=0.0
Pod documented
467 1322 my $str = shift;
468 1322 $str =~ s/^\s+//;
469 1322 $str =~ s/\s+$//;
470 1322 return $str;
471 }
472  
473 37 ▶sub unindent {
Subroutine unindent: called CC=3 SCAR=11.0
Pod documented
474 37 my $str = shift;
475 37 ▶ my $min = min map { m/^([ \t]*)/; length $1 || () } split /\n/, $str;
Condition66%2/3
length $1 || ()
l!l&&r!l&&!r
369570
MC/DC0%0/2
length $1 || ()
length $1 ()
Truth table66%2/3
A || B
A= length $1B= ()
ABresult
1X1
011
000
476 37 ▶ $str =~ s/^[ \t]{0,$min}//gm if $min;
Branch: 1 branch
BranchTrueFalseTotal
if $min 36 1 37
477 37 return $str;
478 }
479  
480 50 ▶sub unquote {
Subroutine unquote: called CC=2 SCAR=7.0
Pod documented
481 50 my $str = shift;
482 50 ▶ return $str unless $str =~ s/^"(.*)"$/$1/g;
Branch: 1 branch
BranchTrueFalseTotal
unless $str =~ s/^"(.*)"$/$1/gu 0 50 50
483 50 $str =~ s/\\\\/\\/g;
484 50 $str =~ s/\\"/"/g;
485 50 return $str;
486 }
487  
488 2373 ▶sub url_escape {
Subroutine url_escape: called CC=4 SCAR=13.9
Pod documented
489 2373 my ($str, $pattern) = @_;
490  
491 2373 ▶ if ($pattern) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pattern) { } 2366 7 2373
492 2366 ▶ unless (exists $PATTERN{$pattern}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $PATTERN{$pattern}) 48 2318 2366
493 48 (my $quoted = $pattern) =~ s!([/\$\[])!\\$1!g;
494 48 ▶ $PATTERN{$pattern} = eval "sub { \$_[0] =~ s/([$quoted])/sprintf '%%%02X', ord \$1/ge }" or croak $@;
Branch: 1 branch
BranchTrueFalseTotal
$PATTERN{$pattern} = eval "sub { \$_[0] =~ s/([$quoted])/sprintf '%%%02X', ord \$1/ge }" or croak($@) 48 0 48
495 }
496 2366 $PATTERN{$pattern}->($str);
497 }
498 7 else { $str =~ s/([^A-Za-z0-9\-._~])/sprintf '%%%02X', ord $1/ge }
499  
500 2373 return $str;
501 }
502  
503 2036 ▶sub url_unescape {
Subroutine url_unescape: called CC=1 SCAR=0.0
Pod documented
504 2036 my $str = shift;
505 2036 $str =~ s/%([0-9a-fA-F]{2})/chr hex $1/ge;
506 2036 return $str;
507 }
508  
509 515 ▶sub xml_escape {
Subroutine xml_escape: called CC=4 SCAR=14.0
Pod documented
510 515 ▶ return $_[0] if ref $_[0] && ref $_[0] eq 'Mojo::ByteStream';
Branch: 2 branches
BranchTrueFalseTotal
if ref $_[0] and ref $_[0] eq "Mojo::ByteStream" 1 514 515
if ref $_[0] and ref $_[0] eq "Mojo::ByteStream" 946 4045 4991
Condition83%5/6
ref $_[0] and ref $_[0] eq "Mojo::ByteStream"
!ll&&!rl&&r
51401
ref $_[0] and ref $_[0] eq "Mojo::ByteStream"
!ll&&!rl&&r
3894151946
MC/DC50%1/2
ref $_[0] and ref $_[0] eq "Mojo::ByteStream"
ref $_[0] ref $_[0] eq "Mojo::ByteStream"
MC/DC100%2/2
ref $_[0] and ref $_[0] eq "Mojo::ByteStream"
ref $_[0] ref $_[0] eq "Mojo::ByteStream"
Truth table66%2/3
A and B
A= ref $_[0]B= ref $_[0] eq "Mojo::ByteStream"
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= ref $_[0]B= ref $_[0] eq "Mojo::ByteStream"
ABresult
0X0
100
111
511 514 ▶ my $str = shift // '';
Condition50%2/4
shift() // ""
l!l
5140
shift() // ""
l!l
40450
MC/DC0%0/1
shift() // ""
shift()
MC/DC0%0/1
shift() // ""
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
Truth table50%1/2
A
A= shift()
Aresult
11
00
512 514 $str =~ s/([&<>"'])/$XML{$1}/ge;
513 514 return $str;
514 }
515  
516 20 ▶sub xor_encode {
Subroutine xor_encode: called CC=1 SCAR=0.0
Pod documented
517 20 my ($input, $key) = @_;
518  
519 # Encode with variable key length (repeat key to match input length)
520 20 my $len = length $input;
521 20 return $input ^ substr($key x (int($len / length $key) + 1), 0, $len);
522 }
523  
524 487 ▶sub _adapt {
Subroutine _adapt: called CC=3 SCAR=11.0
525 487 my ($delta, $numpoints, $firsttime) = @_;
526 64 ▶ use integer;
Subroutine BEGIN: called CC=1 SCAR=0.0
527  
528 487 ▶ $delta = $firsttime ? $delta / PC_DAMP : $delta / 2;
Branch: 1 branch
BranchTrueFalseTotal
$firsttime ? : 89 398 487
529 487 $delta += $delta / $numpoints;
530 487 my $k = 0;
531 487 ▶ while ($delta > ((PC_BASE - PC_TMIN) * PC_TMAX) / 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($delta > 455) 116 487 603
532 116 $delta /= PC_BASE - PC_TMIN;
533 116 $k += PC_BASE;
534 }
535  
536 487 return $k + (((PC_BASE - PC_TMIN + 1) * $delta) / ($delta + PC_SKEW));
537 }
538  
539 215 ▶sub _encoding { $ENCODING{$_[0]} //= find_encoding($_[0]) // croak "Unknown encoding '$_[0]'" }
Subroutine _encoding: called CC=3 SCAR=11.0
Condition100%4/4
$ENCODING{$_[0]} //= &find_encoding($_[0]) // croak("Unknown encoding '$_[0]'")
l!l
19025
&find_encoding($_[0]) // croak("Unknown encoding '$_[0]'")
l!l
232
MC/DC100%1/1
$ENCODING{$_[0]} //= &find_encoding($_[0]) // croak("Unknown encoding '$_[0]'")
$ENCODING{$_[0]}
Truth table100%2/2
A
A= $ENCODING{$_[0]}
Aresult
11
00
540  
541 90 ▶sub _entity {
Subroutine _entity: called CC=13 SCAR=25.7
542 90 my ($point, $name, $attr) = @_;
543  
544 # Code point
545 90 ▶ unless (defined $name) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $name) 38 52 90
546 38 ▶ my $cp = $point !~ /^x/ ? $point + 0 : hex $point;
Branch: 1 branch
BranchTrueFalseTotal
!($point =~ /^x/u) ? : 10 28 38
547 38 ▶ return "\N{U+FFFD}" if $cp == 0 || $cp > 0x10FFFF || ($cp >= 0xD800 && $cp <= 0xDFFF);
Branch: 1 branch
BranchTrueFalseTotal
if $cp == 0 or $cp > 1114111 or $cp >= 55296 and $cp <= 57343 11 27 38
Condition100%9/9
$cp == 0 or $cp > 1114111 or $cp >= 55296 and $cp <= 57343
l!l&&r!l&&!r
4727
$cp == 0 or $cp > 1114111
l!l&&r!l&&!r
2234
$cp >= 55296 and $cp <= 57343
!ll&&!rl&&r
2437
MC/DC100%4/4
$cp == 0 or $cp > 1114111 or $cp >= 55296 and $cp <= 57343
$cp == 0 $cp > 1114111 $cp >= 55296 $cp <= 57343
Truth table100%5/5
A or B or C and D
A= $cp == 0B= $cp > 1114111C= $cp >= 55296D= $cp <= 57343
ABCDresult
1XXX1
01XX1
00111
000X0
00100
548 27 ▶ return chr($C1{$cp} // $cp);
Condition66%2/3
$C1{$cp} // $cp
l!l&&r!l&&!r
6210
MC/DC0%0/2
$C1{$cp} // $cp
$C1{$cp} $cp
Truth table66%2/3
A // B
A= $C1{$cp}B= $cp
ABresult
1X1
011
000
549 }
550  
551 # Named character reference
552 52 my $rest = my $last = '';
553 52 ▶ while (length $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $name) 90 10 100
554 return $ENTITIES{$name} . reverse $rest
555 90 ▶ if exists $ENTITIES{$name} && (!$attr || $name =~ /;$/ || $last !~ /[A-Za-z0-9=]/);
Branch: 1 branch
BranchTrueFalseTotal
if exists $ENTITIES{$name} and !$attr || $name =~ /;$/u || !($last =~ /[A-Za-z0-9=]/u) 42 48 90
Condition100%9/9
exists $ENTITIES{$name} and !$attr || $name =~ /;$/u || !($last =~ /[A-Za-z0-9=]/u)
!ll&&!rl&&r
44442
not $attr or $name =~ /;$/u or not $last =~ /[A-Za-z0-9=]/u
l!l&&r!l&&!r
3844
not $attr or $name =~ /;$/u
l!l&&r!l&&!r
3268
MC/DC100%4/4
exists $ENTITIES{$name} and !$attr || $name =~ /;$/u || !($last =~ /[A-Za-z0-9=]/u)
exists $ENTITIES{$name} not $attr $name =~ /;$/u not $last =~ /[A-Za-z0-9=]/u
Truth table100%5/5
A and not(B) or C or not(D)
A= exists $ENTITIES{$name}B= not $attrC= $name =~ /;$/uD= not $last =~ /[A-Za-z0-9=]/u
ABCDresult
0XXX0
10000
11XX1
101X1
10011
556 48 $rest .= $last = chop $name;
557 }
558 10 return '&' . reverse $rest;
559 }
560  
561 278 ▶sub _header {
Subroutine _header: called CC=10 SCAR=23.0
562 278 my ($str, $cookie) = @_;
563  
564 278 my (@tree, @part);
565 278 ▶ while ($str =~ /\G[,;\s]*([^=;, ]+)\s*/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /\G[,;\s]*([^=;, ]+)\s*/cgu) 340 278 618
566 340 push @part, $1, undef;
567 340 ▶ my $expires = $cookie && @part > 2 && lc $1 eq 'expires';
Condition100%6/6
$cookie && @part > 2 && lc $1 eq 'expires'
!ll&&!rl&&r
18012832
$cookie and @part > 2
!ll&&!rl&&r
11268160
MC/DC100%3/3
$cookie && @part > 2 && lc $1 eq 'expires'
$cookie @part > 2 lc $1 eq 'expires'
Truth table100%4/4
A and B && C
A= $cookieB= @part > 2C= lc $1 eq 'expires'
ABCresult
0XX0
10X0
1100
1111
568  
569 # Special "expires" value
570 340 ▶ if ($expires && $str =~ /\G=\s*$EXPIRES_RE/gco) { $part[-1] = $1 }
Branch: 3 branches
BranchTrueFalseTotal
if ($expires and $str =~ /\G=\s*$EXPIRES_RE/cgou) { } 29 311 340
elsif ($str =~ /$QUOTED_VALUE_RE/cgou) { } 44 267 311
elsif ($str =~ /$UNQUOTED_VALUE_RE/cgou) { } 218 49 267
Condition100%3/3
$expires and $str =~ /\G=\s*$EXPIRES_RE/cgou
!ll&&!rl&&r
308329
MC/DC100%2/2
$expires and $str =~ /\G=\s*$EXPIRES_RE/cgou
$expires $str =~ /\G=\s*$EXPIRES_RE/cgou
Truth table100%3/3
A and B
A= $expiresB= $str =~ /\G=\s*$EXPIRES_RE/cgou
ABresult
0X0
100
111
571  
572 # Quoted value
573 44 elsif ($str =~ /$QUOTED_VALUE_RE/gco) { $part[-1] = unquote $1 }
574  
575 # Unquoted value
576 218 elsif ($str =~ /$UNQUOTED_VALUE_RE/gco) { $part[-1] = $1 }
577  
578 # Separator
579 340 ▶ next unless $str =~ /\G[;\s]*,\s*/gc;
Branch: 1 branch
BranchTrueFalseTotal
unless $str =~ /\G[;\s]*,\s*/cgu 310 30 340
580 30 push @tree, [@part];
581 30 @part = ();
582 }
583  
584 # Take care of final part
585 278 ▶ return [@part ? (@tree, \@part) : @tree];
Branch: 1 branch
BranchTrueFalseTotal
@part ? : 92 186 278
586 }
587  
588 34553 ▶sub _html {
Subroutine _html: called CC=1 SCAR=0.0
589 34553 my ($str, $attr) = @_;
590 34553 $str =~ s/$ENTITY_RE/_entity($1, $2, $attr)/geo;
591 34553 return $str;
592 }
593  
594 2397 ▶sub _options {
Subroutine _options: called CC=5 SCAR=16.1
595  
596 # Hash or name (one)
597 2397 ▶ return ref $_[0] eq 'HASH' ? (undef, %{shift()}) : @_ if @_ == 1;
Branch: 2 branches
BranchTrueFalseTotal
if @_ == 1 1907 490 2397
ref $_[0] eq 'HASH' ? : 1176 731 1907
598  
599 # Name and values (odd)
600 490 ▶ return shift, @_ if @_ % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 146 344 490
601  
602 # Name and hash or just values (even)
603 344 ▶ return ref $_[1] eq 'HASH' ? (shift, %{shift()}) : (undef, @_);
Branch: 1 branch
BranchTrueFalseTotal
ref $_[1] eq 'HASH' ? : 1 343 344
604 }
605  
606 # This may break in the future, but is worth it for performance
607 136 ▶sub _readable { !!(IO::Poll::_poll(@_[0, 1], my $m = POLLIN | POLLPRI) > 0) }
Subroutine _readable: called CC=1 SCAR=0.0
608  
609 16 ▶sub _round { $_[0] < 10 ? int($_[0] * 10 + 0.5) / 10 : int($_[0] + 0.5) }
Subroutine _round: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] < 10 ? : 12 4 16
610  
611 3770 ▶sub _stash {
Subroutine _stash: called CC=6 SCAR=17.9
612 3770 my ($name, $object) = (shift, shift);
613  
614 # Hash
615 3770 ▶ return $object->{$name} //= {} unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 3491 279 3770
Condition100%2/2
$object->{$name} //= {}
l!l
345734
MC/DC100%1/1
$object->{$name} //= {}
$object->{$name}
Truth table100%2/2
A
A= $object->{$name}
Aresult
11
00
616  
617 # Get
618 279 ▶ return $object->{$name}{$_[0]} unless @_ > 1 || ref $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless @_ > 1 or ref $_[0] 66 213 279
Condition100%3/3
@_ > 1 or ref $_[0]
l!l&&r!l&&!r
2031066
MC/DC100%2/2
@_ > 1 or ref $_[0]
@_ > 1 ref $_[0]
Truth table100%3/3
A or B
A= @_ > 1B= ref $_[0]
ABresult
1X1
011
000
619  
620 # Set
621 213 ▶ my $values = ref $_[0] ? $_[0] : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 10 203 213
622 213 @{$object->{$name}}{keys %$values} = values %$values;
623  
624 213 return $object;
625 }
626  
627 1367 ▶sub _teardown {
Subroutine _teardown: called CC=2 SCAR=7.0
628 1367 ▶ return unless my $class = shift;
Branch: 1 branch
BranchTrueFalseTotal
unless my $class = shift() 0 1367 1367
629  
630 # @ISA has to be cleared first because of circular references
631 64 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
632 1367 @{"${class}::ISA"} = ();
633 1367 delete_package $class;
634 }
635  
636 package Mojo::Util::_Guard;
637 64 ▶use Mojo::Base -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
638  
639 16 ▶sub DESTROY { shift->{cb}() }
Subroutine DESTROY: called CC=1 SCAR=0.0
640  
641 64 1;
642  
643 =encoding utf8
644  
645 =head1 NAME
646  
647 Mojo::Util - Portable utility functions
648  
649 =head1 SYNOPSIS
650  
651 use Mojo::Util qw(b64_encode url_escape url_unescape);
652  
653 my $str = 'test=23';
654 my $escaped = url_escape $str;
655 say url_unescape $escaped;
656 say b64_encode $escaped, '';
657  
658 =head1 DESCRIPTION
659  
660 L<Mojo::Util> provides portable utility functions for L<Mojo>.
661  
662 =head1 FUNCTIONS
663  
664 L<Mojo::Util> implements the following functions, which can be imported individually.
665  
666 =head2 b64_decode
667  
668 my $bytes = b64_decode $b64;
669  
670 Base64 decode bytes with L<MIME::Base64>.
671  
672 =head2 b64_encode
673  
674 my $b64 = b64_encode $bytes;
675 my $b64 = b64_encode $bytes, "\n";
676  
677 Base64 encode bytes with L<MIME::Base64>, the line ending defaults to a newline.
678  
679 =head2 camelize
680  
681 my $camelcase = camelize $snakecase;
682  
683 Convert C<snake_case> string to C<CamelCase> and replace C<-> with C<::>.
684  
685 # "FooBar"
686 camelize 'foo_bar';
687  
688 # "FooBar::Baz"
689 camelize 'foo_bar-baz';
690  
691 # "FooBar::Baz"
692 camelize 'FooBar::Baz';
693  
694 =head2 class_to_file
695  
696 my $file = class_to_file 'Foo::Bar';
697  
698 Convert a class name to a file.
699  
700 # "foo_bar"
701 class_to_file 'Foo::Bar';
702  
703 # "foobar"
704 class_to_file 'FOO::Bar';
705  
706 # "foo_bar"
707 class_to_file 'FooBar';
708  
709 # "foobar"
710 class_to_file 'FOOBar';
711  
712 =head2 class_to_path
713  
714 my $path = class_to_path 'Foo::Bar';
715  
716 Convert class name to path, as used by C<%INC>.
717  
718 # "Foo/Bar.pm"
719 class_to_path 'Foo::Bar';
720  
721 # "FooBar.pm"
722 class_to_path 'FooBar';
723  
724 =head2 decamelize
725  
726 my $snakecase = decamelize $camelcase;
727  
728 Convert C<CamelCase> string to C<snake_case> and replace C<::> with C<->.
729  
730 # "foo_bar"
731 decamelize 'FooBar';
732  
733 # "foo_bar-baz"
734 decamelize 'FooBar::Baz';
735  
736 # "foo_bar-baz"
737 decamelize 'foo_bar-baz';
738  
739 =head2 decode
740  
741 my $chars = decode 'UTF-8', $bytes;
742  
743 Decode bytes to characters with L<Encode>, or return C<undef> if decoding failed.
744  
745 =head2 decrypt_cookie
746  
747 my $value = decrypt_cookie $encrypted, 'passw0rd', 'salt';
748  
749 Decrypt cookie value encrypted with L</encrypt_cookie>, returns the decrypted value or C<undef>.
750  
751 =head2 deprecated
752  
753 deprecated 'foo is DEPRECATED in favor of bar';
754  
755 Warn about deprecated feature from perspective of caller. You can also set the C<MOJO_FATAL_DEPRECATIONS> environment
756 variable to make them die instead with L<Carp>.
757  
758 =head2 dumper
759  
760 my $perl = dumper {some => 'data'};
761  
762 Dump a Perl data structure with L<Data::Dumper>.
763  
764 =head2 encode
765  
766 my $bytes = encode 'UTF-8', $chars;
767  
768 Encode characters to bytes with L<Encode>.
769  
770 =head2 encrypt_cookie
771  
772 my $encrypted = encrypt_cookie $value, 'passw0rd', 'salt';
773  
774 Encrypt cookie value.
775  
776 =head2 extract_usage
777  
778 my $usage = extract_usage;
779 my $usage = extract_usage '/home/sri/foo.pod';
780  
781 Extract usage message from the SYNOPSIS section of a file containing POD documentation, defaults to using the file this
782 function was called from.
783  
784 # "Usage: APPLICATION test [OPTIONS]\n"
785 extract_usage;
786  
787 =head1 SYNOPSIS
788  
789 Usage: APPLICATION test [OPTIONS]
790  
791 =cut
792  
793 =head2 generate_secret
794  
795 my $secret = generate_secret;
796  
797 Generate a random secret with a cryptographically secure random number generator.
798  
799 =head2 getopt
800  
801 getopt
802 'H|headers=s' => \my @headers,
803 't|timeout=i' => \my $timeout,
804 'v|verbose' => \my $verbose;
805 getopt $array,
806 'H|headers=s' => \my @headers,
807 't|timeout=i' => \my $timeout,
808 'v|verbose' => \my $verbose;
809 getopt $array, ['pass_through'],
810 'H|headers=s' => \my @headers,
811 't|timeout=i' => \my $timeout,
812 'v|verbose' => \my $verbose;
813  
814 Extract options from an array reference with L<Getopt::Long>, but without changing its global configuration, defaults
815 to using C<@ARGV>. The configuration options C<no_auto_abbrev> and C<no_ignore_case> are enabled by default.
816  
817 # Extract "charset" option
818 getopt ['--charset', 'UTF-8'], 'charset=s' => \my $charset;
819 say $charset;
820  
821 =head2 gunzip
822  
823 my $uncompressed = gunzip $compressed;
824  
825 Uncompress bytes with L<IO::Compress::Gunzip>.
826  
827 =head2 gzip
828  
829 my $compressed = gzip $uncompressed;
830  
831 Compress bytes with L<IO::Compress::Gzip>.
832  
833 =head2 header_params
834  
835 my ($params, $remainder) = header_params 'one=foo; two="bar", three=baz';
836  
837 Extract HTTP header field parameters until the first comma according to L<RFC 5987|http://tools.ietf.org/html/rfc5987>.
838  
839 =head2 hmac_sha1_sum
840  
841 my $checksum = hmac_sha1_sum $bytes, 'passw0rd';
842  
843 Generate HMAC-SHA1 checksum for bytes with L<Digest::SHA>.
844  
845 # "11cedfd5ec11adc0ec234466d8a0f2a83736aa68"
846 hmac_sha1_sum 'foo', 'passw0rd';
847  
848 =head2 html_attr_unescape
849  
850 my $str = html_attr_unescape $escaped;
851  
852 Same as L</"html_unescape">, but handles special rules from the L<HTML Living Standard|https://html.spec.whatwg.org>
853 for HTML attributes.
854  
855 # "foo=bar&ltest=baz"
856 html_attr_unescape 'foo=bar&ltest=baz';
857  
858 # "foo=bar<est=baz"
859 html_attr_unescape 'foo=bar&lt;est=baz';
860  
861 =head2 html_unescape
862  
863 my $str = html_unescape $escaped;
864  
865 Unescape all HTML entities in string.
866  
867 # "<div>"
868 html_unescape '&lt;div&gt;';
869  
870 =head2 humanize_bytes
871  
872 my $str = humanize_bytes 1234;
873  
874 Turn number of bytes into a simplified human readable format.
875  
876 # "1B"
877 humanize_bytes 1;
878  
879 # "7.5GiB"
880 humanize_bytes 8007188480;
881  
882 # "13GiB"
883 humanize_bytes 13443399680;
884  
885 # "-685MiB"
886 humanize_bytes -717946880;
887  
888 =head2 md5_bytes
889  
890 my $checksum = md5_bytes $bytes;
891  
892 Generate binary MD5 checksum for bytes with L<Digest::MD5>.
893  
894 =head2 md5_sum
895  
896 my $checksum = md5_sum $bytes;
897  
898 Generate MD5 checksum for bytes with L<Digest::MD5>.
899  
900 # "acbd18db4cc2f85cedef654fccc4a4d8"
901 md5_sum 'foo';
902  
903 =head2 monkey_patch
904  
905 monkey_patch $package, foo => sub {...};
906 monkey_patch $package, foo => sub {...}, bar => sub {...};
907  
908 Monkey patch functions into package.
909  
910 monkey_patch 'MyApp',
911 one => sub { say 'One!' },
912 two => sub { say 'Two!' },
913 three => sub { say 'Three!' };
914  
915 =head2 network_contains
916  
917 my $bool = network_contains $network, $address;
918  
919 Check that a given address is contained within a network in CIDR form. If the network is a single address, the
920 addresses must be equivalent.
921  
922 # True
923 network_contains('10.0.0.0/8', '10.10.10.10');
924 network_contains('10.10.10.10', '10.10.10.10');
925 network_contains('fc00::/7', 'fc::c0:ff:ee');
926  
927 # False
928 network_contains('10.0.0.0/29', '10.10.10.10');
929 network_contains('10.10.10.12', '10.10.10.10');
930 network_contains('fc00::/7', '::1');
931
932 =head2 punycode_decode
933  
934 my $str = punycode_decode $punycode;
935  
936 Punycode decode string as described in L<RFC 3492|https://tools.ietf.org/html/rfc3492>.
937  
938 # "bücher"
939 punycode_decode 'bcher-kva';
940  
941 =head2 punycode_encode
942  
943 my $punycode = punycode_encode $str;
944  
945 Punycode encode string as described in L<RFC 3492|https://tools.ietf.org/html/rfc3492>.
946  
947 # "bcher-kva"
948 punycode_encode 'bücher';
949  
950 =head2 quote
951  
952 my $quoted = quote $str;
953  
954 Quote string.
955  
956 =head2 random_bytes
957  
958 my $random = random_bytes($bytes);
959  
960 Generate C<$bytes> worth of high entropy randomness.
961  
962 =head2 scope_guard
963  
964 my $guard = scope_guard sub {...};
965  
966 Create anonymous scope guard object that will execute the passed callback when the object is destroyed.
967  
968 # Execute closure at end of scope
969 {
970 my $guard = scope_guard sub { say "Mojo!" };
971 say "Hello";
972 }
973  
974 =head2 secure_compare
975  
976 my $bool = secure_compare $str1, $str2;
977  
978 Constant time comparison algorithm to prevent timing attacks. The secret string should be the second argument, to avoid
979 leaking information about the length of the string.
980  
981 =head2 sha1_bytes
982  
983 my $checksum = sha1_bytes $bytes;
984  
985 Generate binary SHA1 checksum for bytes with L<Digest::SHA>.
986  
987 =head2 sha1_sum
988  
989 my $checksum = sha1_sum $bytes;
990  
991 Generate SHA1 checksum for bytes with L<Digest::SHA>.
992  
993 # "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
994 sha1_sum 'foo';
995  
996 =head2 slugify
997  
998 my $slug = slugify $string;
999 my $slug = slugify $string, $bool;
1000  
1001 Returns a URL slug generated from the input string. Non-word characters are removed, the string is trimmed and
1002 lowercased, and whitespace characters are replaced by a dash. By default, non-ASCII characters are normalized to ASCII
1003 word characters or removed, but if a true value is passed as the second parameter, all word characters will be allowed
1004 in the result according to unicode semantics.
1005  
1006 # "joel-is-a-slug"
1007 slugify 'Joel is a slug';
1008  
1009 # "this-is-my-resume"
1010 slugify 'This is: my - résumé! ☃ ';
1011  
1012 # "this-is-my-résumé"
1013 slugify 'This is: my - résumé! ☃ ', 1;
1014  
1015 =head2 split_cookie_header
1016  
1017 my $tree = split_cookie_header 'a=b; expires=Thu, 07 Aug 2008 07:07:59 GMT';
1018  
1019 Same as L</"split_header">, but handles C<expires> values from L<RFC 6265|https://tools.ietf.org/html/rfc6265>.
1020  
1021 =head2 split_header
1022  
1023 my $tree = split_header 'foo="bar baz"; test=123, yada';
1024  
1025 Split HTTP header value into key/value pairs, each comma separated part gets its own array reference, and keys without
1026 a value get C<undef> assigned.
1027  
1028 # "one"
1029 split_header('one; two="three four", five=six')->[0][0];
1030  
1031 # "two"
1032 split_header('one; two="three four", five=six')->[0][2];
1033  
1034 # "three four"
1035 split_header('one; two="three four", five=six')->[0][3];
1036  
1037 # "five"
1038 split_header('one; two="three four", five=six')->[1][0];
1039  
1040 # "six"
1041 split_header('one; two="three four", five=six')->[1][1];
1042  
1043 =head2 steady_time
1044  
1045 my $time = steady_time;
1046  
1047 High resolution time elapsed from an arbitrary fixed point in the past, resilient to time jumps if a monotonic clock is
1048 available through L<Time::HiRes>.
1049  
1050 =head2 tablify
1051  
1052 my $table = tablify [['foo', 'bar'], ['baz', 'yada']];
1053  
1054 Row-oriented generator for text tables.
1055  
1056 # "foo bar\nyada yada\nbaz yada\n"
1057 tablify [['foo', 'bar'], ['yada', 'yada'], ['baz', 'yada']];
1058  
1059 =head2 term_escape
1060  
1061 my $escaped = term_escape $str;
1062  
1063 Escape all POSIX control characters except for C<\n>.
1064  
1065 # "foo\\x09bar\\x0d\n"
1066 term_escape "foo\tbar\r\n";
1067  
1068 =head2 trim
1069  
1070 my $trimmed = trim $str;
1071  
1072 Trim whitespace characters from both ends of string.
1073  
1074 # "foo bar"
1075 trim ' foo bar ';
1076  
1077 =head2 unindent
1078  
1079 my $unindented = unindent $str;
1080  
1081 Unindent multi-line string.
1082  
1083 # "foo\nbar\nbaz\n"
1084 unindent " foo\n bar\n baz\n";
1085  
1086 =head2 unquote
1087  
1088 my $str = unquote $quoted;
1089  
1090 Unquote string.
1091  
1092 =head2 url_escape
1093  
1094 my $escaped = url_escape $str;
1095 my $escaped = url_escape $str, '^A-Za-z0-9\-._~';
1096  
1097 Percent encode unsafe characters in string as described in L<RFC 3986|https://tools.ietf.org/html/rfc3986>, the pattern
1098 used defaults to C<^A-Za-z0-9\-._~>.
1099  
1100 # "foo%3Bbar"
1101 url_escape 'foo;bar';
1102  
1103 =head2 url_unescape
1104  
1105 my $str = url_unescape $escaped;
1106  
1107 Decode percent encoded characters in string as described in L<RFC 3986|https://tools.ietf.org/html/rfc3986>.
1108  
1109 # "foo;bar"
1110 url_unescape 'foo%3Bbar';
1111  
1112 =head2 xml_escape
1113  
1114 my $escaped = xml_escape $str;
1115  
1116 Escape unsafe characters C<&>, C<E<lt>>, C<E<gt>>, C<"> and C<'> in string, but do not escape L<Mojo::ByteStream>
1117 objects.
1118  
1119 # "&lt;div&gt;"
1120 xml_escape '<div>';
1121  
1122 # "<div>"
1123 use Mojo::ByteStream qw(b);
1124 xml_escape b('<div>');
1125  
1126 =head2 xor_encode
1127  
1128 my $encoded = xor_encode $str, $key;
1129  
1130 XOR encode string with variable length key.
1131  
1132 =head1 SEE ALSO
1133  
1134 L<Mojolicious>, L<Mojolicious::Guides>, L<https://mojolicious.org>.
1135  
1136 =cut
« Mojolicious/Controller.pm ↑ Summary Mojo/UserAgent.pm »