Example/LRU/Array.pm untested

filter: Statementstmt 0.0% 0 / 34 Branchbran 0.0% 0 / 4 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 73 CC 3 SCAR 15.0
CC
3
Cov
0%
put
12.0
new
2.0
_find
2.0
CRAP 4.5
1 ########################################################################
2 # housekeeping
3 ########################################################################
4 package LinkedList::Single::Example::LRU::Array v2.0.0;
5 use v5.40;
6  
7 use Carp qw( croak );
8  
9 ########################################################################
10 # the plain array cache: [ $key, $value ] pairs, newest first.
11 #
12 # there is no index, so a hit is a linear search, a splice out and an
13 # unshift. this is what the problem looks like to a programmer who
14 # reaches for an array first; LinkedList::Single::Example::LRU::Order and
15 # LinkedList::Single::Example::LRU::Lazy are what a programmer who has seen this cost writes.
16 ########################################################################
17  
18 sub new( $class, %arg )
19 {
20 my $limit = $arg{ limit }
21 // croak 'Botched new: missing limit';
22  
23 $limit > 0
24 or croak "Botched new: limit '$limit' is not positive";
25  
26 bless
27 {
28 limit => $limit
29 , on_evict => $arg{ on_evict } // sub {}
30 , item => []
31 }
32 => $class
33 }
34  
35 sub _find( $self, $key )
36 {
37 my $item = $self->{ item };
38  
39 for my $at ( 0 .. $#$item )
40 {
41 $item->[ $at ][ 0 ] eq $key
42 and return $at;
43 }
44  
45 undef
46 }
47  
48 sub get( $self, $key )
49 {
50 my $at = $self->_find( $key )
51 // return undef;
52  
53 my $item = $self->{ item };
54  
55 unshift $item->@*, splice $item->@*, $at, 1;
56  
57 $item->[ 0 ][ 1 ]
58 }
59  
60 sub put( $self, $key, $value )
61 {
62 my $item = $self->{ item };
63 my $at = $self->_find( $key );
64  
65 if( defined $at )
66 {
67 splice $item->@*, $at, 1;
68 }
69  
70 unshift $item->@*, [ $key, $value ];
71  
72 if( @$item > $self->{ limit } )
73 {
74 $self->{ on_evict }->( pop( $item->@* )->@* );
75 }
76  
77 $self
78 }
79  
80 sub exists( $self, $key )
81 {
82 defined $self->_find( $key )
83 }
84  
85 sub size( $self )
86 {
87 scalar $self->{ item }->@*
88 }
89  
90 sub limit( $self )
91 {
92 $self->{ limit }
93 }
94  
95 sub contents( $self )
96 {
97 [ map { [ $_->@* ] } $self->{ item }->@* ]
98 }
99  
100 1
101 __END__