File Coverage

blib/lib/Perinci/Sub/Property/memoize.pm
Criterion Covered Total %
statement 24 24 100.0
branch 1 2 50.0
condition 3 5 60.0
subroutine 5 5 100.0
pod n/a
total 33 36 91.6


line stmt bran cond sub pod time code
1             package Perinci::Sub::Property::memoize;
2              
3 1     1   5502 use 5.010001;
  1         3  
  1         86  
4 1     1   5 use strict;
  1         2  
  1         28  
5 1     1   5 use warnings;
  1         2  
  1         32  
6              
7 1     1   904 use Perinci::Sub::PropertyUtil qw(declare_property);
  1         781  
  1         298  
8              
9             our $VERSION = '0.01'; # VERSION
10              
11             declare_property(
12             name => 'memoize',
13             type => 'function',
14             schema => ['any' => {default=>0, of=>[
15             ['bool*'],
16             ['hash*' => {keys=>{
17             }}],
18             ]}],
19             wrapper => {
20             meta => {
21             v => 2,
22             # high, we want to return memoized result early right after we get
23             # %args
24             prio => 0,
25             convert => 1,
26             },
27             handler => sub {
28 6     6   63604 my ($self, %args) = @_;
29              
30 6   33     33 my $v = $args{new} // $args{value};
31 6 50       19 return unless $v;
32              
33 6         20 $self->select_section('declare_vars');
34 6         81 $self->_add_var('_w_cache_key');
35 6   100     14899 my @fargs_names = sort keys %{ $self->{_meta}{args} // {} };
  6         54  
36 6         28 my $qsub_name = Perinci::Sub::Wrapper::__squote($self->{_args}{sub_name});
37 4         114 $self->push_lines(
38             '{',
39             ' no warnings;',
40             ' $_w_cache_key = join("\0", map {$args{$_}} ('.
41 6         394 join(",",map {Perinci::Sub::Wrapper::__squote($_)}
42             @fargs_names).'));',
43             ' return $Perinci::Sub::Wrapped::memoize_cache{'.$qsub_name.'}{$_w_cache_key} '.
44             'if exists $Perinci::Sub::Wrapped::memoize_cache{'.$qsub_name.'}{$_w_cache_key};',
45             '}',
46             );
47              
48 6         305 $self->select_section('after_call_after_res_validation');
49 6         78 $self->push_lines(
50             '$Perinci::Sub::Wrapped::memoize_cache{'.$qsub_name.'}{$_w_cache_key} = $_w_res;',
51             );
52             },
53             },
54             );
55              
56             1;
57             # ABSTRACT: Memoize function
58              
59             __END__