Example/LRU/Order.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
_touch
2.0
CRAP 4.5
1 ########################################################################
2 # housekeeping
3 ########################################################################
4 package LinkedList::Single::Example::LRU::Order v2.0.0;
5 use v5.40;
6  
7 use Carp qw( croak );
8  
9 ########################################################################
10 # a hash finds the value, an array of keys keeps the order (newest
11 # first). a miss costs nothing but the hash lookup; a hit still has to
12 # find the key in the order array, and splice it to the front.
13 ########################################################################
14  
15 sub new( $class, %arg )
16 {
17 my $limit = $arg{ limit }
18 // croak 'Botched new: missing limit';
19  
20 $limit > 0
21 or croak "Botched new: limit '$limit' is not positive";
22  
23 bless
24 {
25 limit => $limit
26 , on_evict => $arg{ on_evict } // sub {}
27 , value => {}
28 , order => []
29 }
30 => $class
31 }
32  
33 # move a key already present to the front.
34  
35 sub _touch( $self, $key )
36 {
37 my $order = $self->{ order };
38  
39 $order->[ 0 ] eq $key
40 and return;
41  
42 my $at = 0;
43  
44 ++$at while $order->[ $at ] ne $key;
45  
46 splice $order->@*, $at, 1;
47  
48 unshift $order->@*, $key;
49 }
50  
51 sub get( $self, $key )
52 {
53 exists $self->{ value }{ $key }
54 or return undef;
55  
56 $self->_touch( $key );
57  
58 $self->{ value }{ $key }
59 }
60  
61 sub put( $self, $key, $value )
62 {
63 if( exists $self->{ value }{ $key } )
64 {
65 $self->_touch( $key );
66 }
67 else
68 {
69 unshift $self->{ order }->@*, $key;
70 }
71  
72 $self->{ value }{ $key } = $value;
73  
74 if( $self->{ order }->@* > $self->{ limit } )
75 {
76 my $old = pop $self->{ order }->@*;
77  
78 $self->{ on_evict }->( $old, delete $self->{ value }{ $old } );
79 }
80  
81 $self
82 }
83  
84 sub exists( $self, $key )
85 {
86 exists $self->{ value }{ $key }
87 }
88  
89 sub size( $self )
90 {
91 scalar $self->{ order }->@*
92 }
93  
94 sub limit( $self )
95 {
96 $self->{ limit }
97 }
98  
99 sub contents( $self )
100 {
101 [ map { [ $_, $self->{ value }{ $_ } ] } $self->{ order }->@* ]
102 }
103  
104 1
105 __END__