]> Dogcows Code - chaz/p5-File-KDBX/blob - lib/File/KDBX/Util.pm
Add key file saving and refactor some stuff
[chaz/p5-File-KDBX] / lib / File / KDBX / Util.pm
1 package File::KDBX::Util;
2 # ABSTRACT: Utility functions for working with KDBX files
3
4 use warnings;
5 use strict;
6
7 use Crypt::PRNG qw(random_bytes random_string);
8 use Encode qw(decode encode);
9 use Exporter qw(import);
10 use File::KDBX::Error;
11 use List::Util 1.33 qw(any all);
12 use Module::Load;
13 use Ref::Util qw(is_arrayref is_coderef is_hashref is_ref is_refref is_scalarref is_ref);
14 use Scalar::Util qw(blessed isdual looks_like_number readonly refaddr);
15 use namespace::clean -except => 'import';
16
17 our $VERSION = '999.999'; # VERSION
18
19 our %EXPORT_TAGS = (
20 assert => [qw(assert_64bit)],
21 clone => [qw(clone clone_nomagic)],
22 crypt => [qw(pad_pkcs7)],
23 debug => [qw(dumper)],
24 fork => [qw(can_fork)],
25 function => [qw(memoize recurse_limit)],
26 empty => [qw(empty nonempty)],
27 erase => [qw(erase erase_scoped)],
28 gzip => [qw(gzip gunzip)],
29 io => [qw(read_all)],
30 load => [qw(load_optional load_xs try_load_optional)],
31 search => [qw(query search simple_expression_query)],
32 text => [qw(snakify trim)],
33 uuid => [qw(format_uuid generate_uuid is_uuid uuid)],
34 uri => [qw(split_url uri_escape_utf8 uri_unescape_utf8)],
35 );
36
37 $EXPORT_TAGS{all} = [map { @$_ } values %EXPORT_TAGS];
38 our @EXPORT_OK = @{$EXPORT_TAGS{all}};
39
40 my %OPS = (
41 'eq' => 2, # binary
42 'ne' => 2,
43 'lt' => 2,
44 'gt' => 2,
45 'le' => 2,
46 'ge' => 2,
47 '==' => 2,
48 '!=' => 2,
49 '<' => 2,
50 '>' => 2,
51 '<=' => 2,
52 '>=' => 2,
53 '=~' => 2,
54 '!~' => 2,
55 '!' => 1, # unary
56 '!!' => 1,
57 '-not' => 1, # special
58 '-false' => 1,
59 '-true' => 1,
60 '-defined' => 1,
61 '-undef' => 1,
62 '-empty' => 1,
63 '-nonempty' => 1,
64 '-or' => -1,
65 '-and' => -1,
66 );
67 my %OP_NEG = (
68 'eq' => 'ne',
69 'ne' => 'eq',
70 'lt' => 'ge',
71 'gt' => 'le',
72 'le' => 'gt',
73 'ge' => 'lt',
74 '==' => '!=',
75 '!=' => '==',
76 '<' => '>=',
77 '>' => '<=',
78 '<=' => '>',
79 '>=' => '<',
80 '=~' => '!~',
81 '!~' => '=~',
82 );
83
84 =func assert_64bit
85
86 assert_64bit();
87
88 Throw if perl doesn't support 64-bit IVs.
89
90 =cut
91
92 sub assert_64bit() {
93 require Config;
94 $Config::Config{ivsize} < 8
95 and throw "64-bit perl is required to use this feature.\n", ivsize => $Config::Config{ivsize};
96 }
97
98 =func can_fork
99
100 $bool = can_fork;
101
102 Determine if perl can fork, with logic lifted from L<Test2::Util/CAN_FORK>.
103
104 =cut
105
106 sub can_fork {
107 require Config;
108 return 1 if $Config::Config{d_fork};
109 return 0 if $^O ne 'MSWin32' && $^O ne 'NetWare';
110 return 0 if !$Config::Config{useithreads};
111 return 0 if $Config::Config{ccflags} !~ /-DPERL_IMPLICIT_SYS/;
112 return 0 if $] < 5.008001;
113 if ($] == 5.010000 && $Config::Config{ccname} eq 'gcc' && $Config::Config{gccversion}) {
114 return 0 if $Config::Config{gccversion} !~ m/^(\d+)\.(\d+)/;
115 my @parts = split(/[\.\s]+/, $Config::Config{gccversion});
116 return 0 if $parts[0] > 4 || ($parts[0] == 4 && $parts[1] >= 8);
117 }
118 return 0 if $INC{'Devel/Cover.pm'};
119 return 1;
120 }
121
122 =func clone
123
124 $clone = clone($thing);
125
126 Clone deeply. This is an unadorned alias to L<Storable> C<dclone>.
127
128 =cut
129
130 sub clone {
131 require Storable;
132 goto &Storable::dclone;
133 }
134
135 =func clone_nomagic
136
137 $clone = clone_nomagic($thing);
138
139 Clone deeply without keeping [most of] the magic.
140
141 B<WARNING:> At the moment the implementation is naïve and won't respond well to nontrivial data or recursive
142 structures.
143
144 =cut
145
146 sub clone_nomagic {
147 my $thing = shift;
148 if (is_arrayref($thing)) {
149 my @arr = map { clone_nomagic($_) } @$thing;
150 return \@arr;
151 }
152 elsif (is_hashref($thing)) {
153 my %hash;
154 $hash{$_} = clone_nomagic($thing->{$_}) for keys %$thing;
155 return \%hash;
156 }
157 elsif (is_ref($thing)) {
158 return clone($thing);
159 }
160 return $thing;
161 }
162
163 =func dumper
164
165 $str = dumper $thing;
166 dumper $thing; # in void context, prints to STDERR
167
168 Like L<Data::Dumper> but slightly terser in some cases relevent to L<File::KDBX>.
169
170 =cut
171
172 sub dumper {
173 require Data::Dumper;
174 # avoid "once" warnings
175 local $Data::Dumper::Deepcopy = $Data::Dumper::Deepcopy = 1;
176 local $Data::Dumper::Deparse = $Data::Dumper::Deparse = 1;
177 local $Data::Dumper::Indent = 1;
178 local $Data::Dumper::Quotekeys = 0;
179 local $Data::Dumper::Sortkeys = 1;
180 local $Data::Dumper::Terse = 1;
181 local $Data::Dumper::Trailingcomma = 1;
182 local $Data::Dumper::Useqq = 1;
183
184 my @dumps;
185 for my $struct (@_) {
186 my $str = Data::Dumper::Dumper($struct);
187
188 # boolean
189 $str =~ s/bless\( do\{\\\(my \$o = ([01])\)\}, 'boolean' \)/boolean($1)/gs;
190 # Time::Piece
191 $str =~ s/bless\([^\)]+?(\d+)'?,\s+\d+,?\s+\], 'Time::Piece' \)/Time::Piece->new($1)/gs;
192
193 print STDERR $str if !defined wantarray;
194 push @dumps, $str;
195 return $str;
196 }
197 return join("\n", @dumps);
198 }
199
200 =func empty
201
202 =func nonempty
203
204 $bool = empty $thing;
205
206 $bool = nonempty $thing;
207
208 Test whether a thing is empty (or nonempty). An empty thing is one of these:
209
210 =for :list
211 * nonexistent
212 * C<undef>
213 * zero-length string
214 * zero-length array
215 * hash with zero keys
216 * reference to an empty thing (recursive)
217
218 Note in particular that zero C<0> is not considered empty because it is an actual value.
219
220 =cut
221
222 sub empty { _empty(@_) }
223 sub nonempty { !_empty(@_) }
224
225 sub _empty {
226 return 1 if @_ == 0;
227 local $_ = shift;
228 return !defined $_
229 || $_ eq ''
230 || (is_arrayref($_) && @$_ == 0)
231 || (is_hashref($_) && keys %$_ == 0)
232 || (is_scalarref($_) && (!defined $$_ || $$_ eq ''))
233 || (is_refref($_) && _empty($$_));
234 }
235
236 =func erase
237
238 erase($string, ...);
239 erase(\$string, ...);
240
241 Overwrite the memory used by one or more string.
242
243 =cut
244
245 # use File::KDBX::XS;
246
247 sub erase {
248 # Only bother zeroing out memory if we have the last SvPV COW reference, otherwise we'll end up just
249 # creating a copy and erasing the copy.
250 # TODO - Is this worth doing? Need some benchmarking.
251 for (@_) {
252 if (!is_ref($_)) {
253 next if !defined $_ || readonly $_;
254 if (_USE_COWREFCNT()) {
255 my $cowrefcnt = B::COW::cowrefcnt($_);
256 goto FREE_NONREF if defined $cowrefcnt && 1 < $cowrefcnt;
257 }
258 # if (__PACKAGE__->can('erase_xs')) {
259 # erase_xs($_);
260 # }
261 # else {
262 substr($_, 0, length($_), "\0" x length($_));
263 # }
264 FREE_NONREF: {
265 no warnings 'uninitialized';
266 undef $_;
267 }
268 }
269 elsif (is_scalarref($_)) {
270 next if !defined $$_ || readonly $$_;
271 if (_USE_COWREFCNT()) {
272 my $cowrefcnt = B::COW::cowrefcnt($$_);
273 goto FREE_REF if defined $cowrefcnt && 1 < $cowrefcnt;
274 }
275 # if (__PACKAGE__->can('erase_xs')) {
276 # erase_xs($$_);
277 # }
278 # else {
279 substr($$_, 0, length($$_), "\0" x length($$_));
280 # }
281 FREE_REF: {
282 no warnings 'uninitialized';
283 undef $$_;
284 }
285 }
286 elsif (is_arrayref($_)) {
287 erase(@$_);
288 @$_ = ();
289 }
290 elsif (is_hashref($_)) {
291 erase(values %$_);
292 %$_ = ();
293 }
294 else {
295 throw 'Cannot erase this type of scalar', type => ref $_, what => $_;
296 }
297 }
298 }
299
300 =func erase_scoped
301
302 $scope_guard = erase_scoped($string, ...);
303 $scope_guard = erase_scoped(\$string, ...);
304 undef $scope_guard; # erase happens here
305
306 Get a scope guard that will cause scalars to be erased later (i.e. when the scope ends). This is useful if you
307 want to make sure a string gets erased after you're done with it, even if the scope ends abnormally.
308
309 See L</erase>.
310
311 =cut
312
313 sub erase_scoped {
314 my @args;
315 for (@_) {
316 !is_ref($_) || is_arrayref($_) || is_hashref($_) || is_scalarref($_)
317 or throw 'Cannot erase this type of scalar', type => ref $_, what => $_;
318 push @args, is_ref($_) ? $_ : \$_;
319 }
320 require Scope::Guard;
321 return Scope::Guard->new(sub { erase(@args) });
322 }
323
324 =func format_uuid
325
326 $string_uuid = format_uuid($raw_uuid);
327 $string_uuid = format_uuid($raw_uuid, $delimiter);
328
329 Format a 128-bit UUID (given as a string of 16 octets) into a hexidecimal string, optionally with a delimiter
330 to break up the UUID visually into five parts. Examples:
331
332 my $uuid = uuid('01234567-89AB-CDEF-0123-456789ABCDEF');
333 say format_uuid($uuid); # -> 0123456789ABCDEF0123456789ABCDEF
334 say format_uuid($uuid, '-'); # -> 01234567-89AB-CDEF-0123-456789ABCDEF
335
336 This is the inverse of L</uuid>.
337
338 =cut
339
340 sub format_uuid {
341 local $_ = shift // "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
342 my $delim = shift // '';
343 length($_) == 16 or throw 'Must provide a 16-bytes UUID', size => length($_), str => $_;
344 return uc(join($delim, unpack('H8 H4 H4 H4 H12', $_)));
345 }
346
347 =func generate_uuid
348
349 $uuid = generate_uuid;
350 $uuid = generate_uuid(\%set);
351 $uuid = generate_uuid(\&test_uuid);
352
353 Generate a new random UUID. It's pretty unlikely that this will generate a repeat, but if you're worried about
354 that you can provide either a set of existing UUIDs (as a hashref where the keys are the elements of a set) or
355 a function to check for existing UUIDs, and this will be sure to not return a UUID already in provided set.
356 Perhaps an example will make it clear:
357
358 my %uuid_set = (
359 uuid('12345678-9ABC-DEFG-1234-56789ABCDEFG') => 'whatever',
360 );
361 $uuid = generate_uuid(\%uuid_set);
362 # OR
363 $uuid = generate_uuid(sub { !$uuid_set{$_} });
364
365 Here, C<$uuid> can't be "12345678-9ABC-DEFG-1234-56789ABCDEFG". This example uses L</uuid> to easily pack
366 a 16-byte UUID from a literal, but it otherwise is not a consequential part of the example.
367
368 =cut
369
370 sub generate_uuid {
371 my $set = @_ % 2 == 1 ? shift : undef;
372 my %args = @_;
373 my $test = $set //= $args{test};
374 $test = sub { !$set->{$_} } if is_hashref($test);
375 $test //= sub { 1 };
376 my $printable = $args{printable} // $args{print};
377 local $_ = '';
378 do {
379 $_ = $printable ? random_string(16) : random_bytes(16);
380 } while (!$test->($_));
381 return $_;
382 }
383
384 =func gunzip
385
386 $unzipped = gunzip($string);
387
388 Decompress an octet stream.
389
390 =cut
391
392 sub gunzip {
393 load_optional('Compress::Raw::Zlib');
394 local $_ = shift;
395 my ($i, $status) = Compress::Raw::Zlib::Inflate->new(-WindowBits => 31);
396 $status == Compress::Raw::Zlib::Z_OK()
397 or throw 'Failed to initialize compression library', status => $status;
398 $status = $i->inflate($_, my $out);
399 $status == Compress::Raw::Zlib::Z_STREAM_END()
400 or throw 'Failed to decompress data', status => $status;
401 return $out;
402 }
403
404 =func gzip
405
406 $zipped = gzip($string);
407
408 Compress an octet stream.
409
410 =cut
411
412 sub gzip {
413 load_optional('Compress::Raw::Zlib');
414 local $_ = shift;
415 my ($d, $status) = Compress::Raw::Zlib::Deflate->new(-WindowBits => 31, -AppendOutput => 1);
416 $status == Compress::Raw::Zlib::Z_OK()
417 or throw 'Failed to initialize compression library', status => $status;
418 $status = $d->deflate($_, my $out);
419 $status == Compress::Raw::Zlib::Z_OK()
420 or throw 'Failed to compress data', status => $status;
421 $status = $d->flush($out);
422 $status == Compress::Raw::Zlib::Z_OK()
423 or throw 'Failed to compress data', status => $status;
424 return $out;
425 }
426
427 =func is_uuid
428
429 $bool = is_uuid($thing);
430
431 Check if a thing is a UUID (i.e. scalar string of length 16).
432
433 =cut
434
435 sub is_uuid { defined $_[0] && !is_ref($_[0]) && length($_[0]) == 16 }
436
437 =func load_optional
438
439 $package = load_optional($package);
440
441 Load a module that isn't required but can provide extra functionality. Throw if the module is not available.
442
443 =cut
444
445 sub load_optional {
446 for my $module (@_) {
447 eval { load $module };
448 if (my $err = $@) {
449 warn $err if $ENV{DEBUG};
450 throw "Missing dependency: Please install $module to use this feature.\n", module => $module;
451 }
452 }
453 return wantarray ? @_ : $_[0];
454 }
455
456 =func load_xs
457
458 $bool = load_xs();
459 $bool = load_xs($version);
460
461 Attempt to load L<File::KDBX::XS>. Return truthy if C<XS> is loaded. If C<$version> is given, it will check
462 that at least the given version is loaded.
463
464 =cut
465
466 sub load_xs {
467 my $version = shift;
468
469 require File::KDBX;
470
471 my $has_xs = File::KDBX->can('XS_LOADED');
472 return $has_xs->() && ($version ? eval { File::KDBX::XS->VERSION($version); 1 } : 1) if $has_xs;
473
474 my $try_xs = 1;
475 $try_xs = 0 if $ENV{PERL_ONLY} || (exists $ENV{PERL_FILE_KDBX_XS} && !$ENV{PERL_FILE_KDBX_XS});
476
477 my $use_xs = 0;
478 $use_xs = try_load_optional('File::KDBX::XS') if $try_xs;
479
480 *File::KDBX::XS_LOADED = *File::KDBX::XS_LOADED = $use_xs ? sub() { 1 } : sub() { 0 };
481 return $version ? eval { File::KDBX::XS->VERSION($version); 1 } : 1;
482 }
483
484 =func memoize
485
486 \&memoized_code = memoize(\&code, ...);
487
488 Memoize a function. Extra arguments are passed through to C<&code> when it is called.
489
490 =cut
491
492 sub memoize {
493 my $func = shift;
494 my @args = @_;
495 my %cache;
496 return sub { $cache{join("\0", grep { defined } @_)} //= $func->(@args, @_) };
497 }
498
499 =func pad_pkcs7
500
501 $padded_string = pad_pkcs7($string, $block_size),
502
503 Pad a block using the PKCS#7 method.
504
505 =cut
506
507 sub pad_pkcs7 {
508 my $data = shift // throw 'Must provide a string to pad';
509 my $size = shift or throw 'Must provide block size';
510
511 0 <= $size && $size < 256
512 or throw 'Cannot add PKCS7 padding to a large block size', size => $size;
513
514 my $pad_len = $size - length($data) % $size;
515 $data .= chr($pad_len) x $pad_len;
516 }
517
518 =func query
519
520 $query = query(@where);
521 $query->(\%data);
522
523 Generate a function that will run a series of tests on a passed hashref and return true or false depending on
524 if the data record in the hash matched the specified logic.
525
526 The logic can be specified in a manner similar to L<SQL::Abstract/"WHERE CLAUSES"> which was the inspiration
527 for this function, but this code is distinct, supporting an overlapping but not identical feature set and
528 having its own bugs.
529
530 See L<File::KDBX/QUERY> for examples.
531
532 =cut
533
534 sub query { _query(undef, '-or', \@_) }
535
536 =func read_all
537
538 $size = read_all($fh, my $buffer, $size);
539 $size = read_all($fh, my $buffer, $size, $offset);
540
541 Like L<functions/read> but returns C<undef> if not all C<$size> bytes are read. This is considered an error,
542 distinguishable from other errors by C<$!> not being set.
543
544 =cut
545
546 sub read_all($$$;$) { ## no critic (ProhibitSubroutinePrototypes)
547 my $result = @_ == 3 ? read($_[0], $_[1], $_[2])
548 : read($_[0], $_[1], $_[2], $_[3]);
549 return if !defined $result;
550 return if $result != $_[2];
551 return $result;
552 }
553
554 =func recurse_limit
555
556 \&limited_code = recurse_limit(\&code);
557 \&limited_code = recurse_limit(\&code, $max_depth);
558 \&limited_code = recurse_limit(\&code, $max_depth, \&error_handler);
559
560 Wrap a function with a guard to prevent deep recursion.
561
562 =cut
563
564 sub recurse_limit {
565 my $func = shift;
566 my $max_depth = shift // 200;
567 my $error = shift // sub {};
568 my $depth = 0;
569 return sub { return $error->(@_) if $max_depth < ++$depth; $func->(@_) };
570 };
571
572 =func search
573
574 # Generate a query on-the-fly:
575 \@matches = search(\@records, @where);
576
577 # Use a pre-compiled query:
578 $query = query(@where);
579 \@matches = search(\@records, $query);
580
581 # Use a simple expression:
582 \@matches = search(\@records, \'query terms', @fields);
583 \@matches = search(\@records, \'query terms', $operator, @fields);
584
585 # Use your own subroutine:
586 \@matches = search(\@records, \&query);
587 \@matches = search(\@records, sub { $record = shift; ... });
588
589 Execute a linear search over an array of records using a L</query>. A "record" is usually a hash.
590
591 This is the search engine described with many examples at L<File::KDBX/QUERY>.
592
593 =cut
594
595 sub search {
596 my $list = shift;
597 my $query = shift;
598 # my %args = @_;
599
600 if (is_coderef($query) && !@_) {
601 # already a query
602 }
603 elsif (is_scalarref($query)) {
604 $query = simple_expression_query($$query, @_);
605 }
606 else {
607 $query = query($query, @_);
608 }
609
610 # my $limit = $args{limit};
611
612 my @match;
613 for my $item (@$list) {
614 push @match, $item if $query->($item);
615 # last if defined $limit && $limit <= @match;
616 }
617 return \@match;
618 }
619
620 =func simple_expression_query
621
622 $query = simple_expression_query($expression, @fields);
623
624 Generate a query, like L</query>, to be used with L</search> but built from a "simple expression" as
625 L<described here|https://keepass.info/help/base/search.html#mode_se>.
626
627 An expression is a string with one or more space-separated terms. Terms with spaces can be enclosed in double
628 quotes. Terms are negated if they are prefixed with a minus sign. A record must match every term on at least
629 one of the given fields.
630
631 =cut
632
633 sub simple_expression_query {
634 my $expr = shift;
635 my $op = @_ && ($OPS{$_[0] || ''} || 0) == 2 ? shift : '=~';
636
637 my $neg_op = $OP_NEG{$op};
638 my $is_re = $op eq '=~' || $op eq '!~';
639
640 require Text::ParseWords;
641 my @terms = Text::ParseWords::shellwords($expr);
642
643 my @query = qw(-and);
644
645 for my $term (@terms) {
646 my @subquery = qw(-or);
647
648 my $neg = $term =~ s/^-//;
649 my $condition = [($neg ? $neg_op : $op) => ($is_re ? qr/\Q$term\E/i : $term)];
650
651 for my $field (@_) {
652 push @subquery, $field => $condition;
653 }
654
655 push @query, \@subquery;
656 }
657
658 return query(\@query);
659 }
660
661 =func snakify
662
663 $string = snakify($string);
664
665 Turn a CamelCase string into snake_case.
666
667 =cut
668
669 sub snakify {
670 local $_ = shift;
671 s/UserName/Username/g;
672 s/([a-z])([A-Z0-9])/${1}_${2}/g;
673 s/([A-Z0-9]+)([A-Z0-9])(?![A-Z0-9]|$)/${1}_${2}/g;
674 return lc($_);
675 }
676
677 =func split_url
678
679 ($scheme, $auth, $host, $port, $path, $query, $hash, $usename, $password) = split_url($url);
680
681 Split a URL into its parts.
682
683 For example, C<http://user:pass@localhost:4000/path?query#hash> gets split like:
684
685 =for :list
686 * C<http>
687 * C<user:pass>
688 * C<host>
689 * C<4000>
690 * C</path>
691 * C<?query>
692 * C<#hash>
693 * C<user>
694 * C<pass>
695
696 =cut
697
698 sub split_url {
699 local $_ = shift;
700 my ($scheme, $auth, $host, $port, $path, $query, $hash) =~ m!
701 ^([^:/\?\#]+) ://
702 (?:([^\@]+)\@)
703 ([^:/\?\#]*)
704 (?::(\d+))?
705 ([^\?\#]*)
706 (\?[^\#]*)?
707 (\#(.*))?
708 !x;
709
710 $scheme = lc($scheme);
711
712 $host ||= 'localhost';
713 $host = lc($host);
714
715 $path = "/$path" if $path !~ m!^/!;
716
717 $port ||= $scheme eq 'http' ? 80 : $scheme eq 'https' ? 433 : undef;
718
719 my ($username, $password) = split($auth, ':', 2);
720
721 return ($scheme, $auth, $host, $port, $path, $query, $hash, $username, $password);
722 }
723
724 =func trim
725
726 $string = trim($string);
727
728 The ubiquitous C<trim> function. Removes all whitespace from both ends of a string.
729
730 =cut
731
732 sub trim($) { ## no critic (ProhibitSubroutinePrototypes)
733 local $_ = shift // return;
734 s/^\s*//;
735 s/\s*$//;
736 return $_;
737 }
738
739 =func try_load_optional
740
741 $package = try_load_optional($package);
742
743 Try to load a module that isn't required but can provide extra functionality, and return true if successful.
744
745 =cut
746
747 sub try_load_optional {
748 for my $module (@_) {
749 eval { load $module };
750 if (my $err = $@) {
751 warn $err if $ENV{DEBUG};
752 return;
753 }
754 }
755 return @_;
756 }
757
758 =func uri_escape_utf8
759
760 $string = uri_escape_utf8($string);
761
762 Percent-encode arbitrary text strings, like for a URI.
763
764 =cut
765
766 my %ESC = map { chr($_) => sprintf('%%%02X', $_) } 0..255;
767 sub uri_escape_utf8 {
768 local $_ = shift // return;
769 $_ = encode('UTF-8', $_);
770 # RFC 3986 section 2.3 unreserved characters
771 s/([^A-Za-z0-9\-\._~])/$ESC{$1}/ge;
772 return $_;
773 }
774
775 =func uri_unescape_utf8
776
777 $string = uri_unescape_utf8($string);
778
779 Inverse of L</uri_escape_utf8>.
780
781 =cut
782
783 sub uri_unescape_utf8 {
784 local $_ = shift // return;
785 s/\%([A-Fa-f0-9]{2})/chr(hex($1))/;
786 return decode('UTF-8', $_);
787 }
788
789 =func uuid
790
791 $raw_uuid = uuid($string_uuid);
792
793 Pack a 128-bit UUID (given as a hexidecimal string with optional C<->'s, like
794 C<12345678-9ABC-DEFG-1234-56789ABCDEFG>) into a string of exactly 16 octets.
795
796 This is the inverse of L</format_uuid>.
797
798 =cut
799
800 sub uuid {
801 local $_ = shift // return "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
802 s/-//g;
803 /^[A-Fa-f0-9]{32}$/ or throw 'Must provide a formatted 128-bit UUID';
804 return pack('H32', $_);
805
806 }
807
808 BEGIN {
809 my $use_cowrefcnt = eval { require B::COW; 1 };
810 *_USE_COWREFCNT = $use_cowrefcnt ? sub() { 1 } : sub() { 0 };
811 }
812
813 ### --------------------------------------------------------------------------
814
815 # Determine if an array looks like keypairs from a hash.
816 sub _looks_like_keypairs {
817 my $arr = shift;
818 return 0 if @$arr % 2 == 1;
819 for (my $i = 0; $i < @$arr; $i += 2) {
820 return 0 if is_ref($arr->[$i]);
821 }
822 return 1;
823 }
824
825 sub _is_operand_plain {
826 local $_ = shift;
827 return !(is_hashref($_) || is_arrayref($_));
828 }
829
830 sub _query {
831 # dumper \@_;
832 my $subject = shift;
833 my $op = shift // throw 'Must specify a query operator';
834 my $operand = shift;
835
836 return _query_simple($op, $subject) if defined $subject && !is_ref($op) && ($OPS{$subject} || 2) < 2;
837 return _query_simple($subject, $op, $operand) if _is_operand_plain($operand);
838 return _query_inverse(_query($subject, '-or', $operand)) if $op eq '-not' || $op eq '-false';
839 return _query($subject, '-and', [%$operand]) if is_hashref($operand);
840
841 my @queries;
842
843 my @atoms = @$operand;
844 while (@atoms) {
845 if (_looks_like_keypairs(\@atoms)) {
846 my ($atom, $operand) = splice @atoms, 0, 2;
847 if (my $op_type = $OPS{$atom}) {
848 if ($op_type == 1 && _is_operand_plain($operand)) { # unary
849 push @queries, _query_simple($operand, $atom);
850 }
851 else {
852 push @queries, _query($subject, $atom, $operand);
853 }
854 }
855 elsif (!is_ref($atom)) {
856 push @queries, _query($atom, 'eq', $operand);
857 }
858 }
859 else {
860 my $atom = shift @atoms;
861 if ($OPS{$atom}) { # apply new operator over the rest
862 push @queries, _query($subject, $atom, \@atoms);
863 last;
864 }
865 else { # apply original operator over this one
866 push @queries, _query($subject, $op, $atom);
867 }
868 }
869 }
870
871 if (@queries == 1) {
872 return $queries[0];
873 }
874 elsif ($op eq '-and') {
875 return _query_all(@queries);
876 }
877 elsif ($op eq '-or') {
878 return _query_any(@queries);
879 }
880 throw 'Malformed query';
881 }
882
883 sub _query_simple {
884 my $subject = shift;
885 my $op = shift // 'eq';
886 my $operand = shift;
887
888 # these special operators can also act as simple operators
889 $op = '!!' if $op eq '-true';
890 $op = '!' if $op eq '-false';
891 $op = '!' if $op eq '-not';
892
893 defined $subject or throw 'Subject is not set in query';
894 $OPS{$op} >= 0 or throw 'Cannot use a non-simple operator in a simple query';
895 if (empty($operand)) {
896 if ($OPS{$op} < 2) {
897 # no operand needed
898 }
899 # Allow field => undef and field => {'ne' => undef} to do the (arguably) right thing.
900 elsif ($op eq 'eq' || $op eq '==') {
901 $op = '-empty';
902 }
903 elsif ($op eq 'ne' || $op eq '!=') {
904 $op = '-nonempty';
905 }
906 else {
907 throw 'Operand is required';
908 }
909 }
910
911 my $field = sub { blessed $_[0] && $_[0]->can($subject) ? $_[0]->$subject : $_[0]->{$subject} };
912
913 my %map = (
914 'eq' => sub { local $_ = $field->(@_); defined && $_ eq $operand },
915 'ne' => sub { local $_ = $field->(@_); defined && $_ ne $operand },
916 'lt' => sub { local $_ = $field->(@_); defined && $_ lt $operand },
917 'gt' => sub { local $_ = $field->(@_); defined && $_ gt $operand },
918 'le' => sub { local $_ = $field->(@_); defined && $_ le $operand },
919 'ge' => sub { local $_ = $field->(@_); defined && $_ ge $operand },
920 '==' => sub { local $_ = $field->(@_); defined && $_ == $operand },
921 '!=' => sub { local $_ = $field->(@_); defined && $_ != $operand },
922 '<' => sub { local $_ = $field->(@_); defined && $_ < $operand },
923 '>' => sub { local $_ = $field->(@_); defined && $_ > $operand },
924 '<=' => sub { local $_ = $field->(@_); defined && $_ <= $operand },
925 '>=' => sub { local $_ = $field->(@_); defined && $_ >= $operand },
926 '=~' => sub { local $_ = $field->(@_); defined && $_ =~ $operand },
927 '!~' => sub { local $_ = $field->(@_); defined && $_ !~ $operand },
928 '!' => sub { local $_ = $field->(@_); ! $_ },
929 '!!' => sub { local $_ = $field->(@_); !!$_ },
930 '-defined' => sub { local $_ = $field->(@_); defined $_ },
931 '-undef' => sub { local $_ = $field->(@_); !defined $_ },
932 '-nonempty' => sub { local $_ = $field->(@_); nonempty $_ },
933 '-empty' => sub { local $_ = $field->(@_); empty $_ },
934 );
935
936 return $map{$op} // throw "Unexpected operator in query: $op",
937 subject => $subject,
938 operator => $op,
939 operand => $operand;
940 }
941
942 sub _query_inverse {
943 my $query = shift;
944 return sub { !$query->(@_) };
945 }
946
947 sub _query_all {
948 my @queries = @_;
949 return sub {
950 my $val = shift;
951 all { $_->($val) } @queries;
952 };
953 }
954
955 sub _query_any {
956 my @queries = @_;
957 return sub {
958 my $val = shift;
959 any { $_->($val) } @queries;
960 };
961 }
962
963 1;
This page took 0.095517 seconds and 4 git commands to generate.