| 1 | package DTL::Fast::Cache::File; | ||
| 2 | use strict; use warnings FATAL => 'all'; | ||
| 3 | use parent 'DTL::Fast::Cache::Compressed'; | ||
| 4 | |||
| 5 | #@Override | ||
| 6 | sub new | ||
| 7 | { | ||
| 8 | my( $proto, $dir, %kwargs ) = @_; | ||
| 9 | |||
| 10 | die "You should pass a cache directory to the constructor of ".__PACKAGE__ | ||
| 11 | if not $dir; | ||
| 12 | |||
| 13 | $dir =~ s{[\/]+$}{}gs; | ||
| 14 | |||
| 15 | if( | ||
| 16 | -d $dir | ||
| 17 | and -w $dir | ||
| 18 | ) | ||
| 19 | { | ||
| 20 | $kwargs{'dir'} = $dir; | ||
| 21 | } | ||
| 22 | else | ||
| 23 | { | ||
| 24 | die "$dir is not a directory or it's not writable for me"; | ||
| 25 | } | ||
| 26 | |||
| 27 | return $proto->SUPER::new(%kwargs); | ||
| 28 | } | ||
| 29 | |||
| 30 | #@Override | ||
| 31 | sub read_compressed_data | ||
| 32 | { | ||
| 33 | my( $self, $key ) = @_; | ||
| 34 | my $result; | ||
| 35 | |||
| 36 | my $filename = sprintf '%s/%s.dtc', $self->{'dir'}, $key; | ||
| 37 | |||
| 38 | if( -e $filename ) | ||
| 39 | { | ||
| 40 | if( open my $IF, '<', $filename ) | ||
| 41 | { | ||
| 42 | binmode $IF; | ||
| 43 | local $/ = undef; | ||
| 44 | $result = <$IF>; | ||
| 45 | close $IF; | ||
| 46 | } | ||
| 47 | else | ||
| 48 | { | ||
| 49 | die "Error opening cache file $filename for reading: $!"; | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | return $result; | ||
| 54 | } | ||
| 55 | |||
| 56 | #@Override | ||
| 57 | sub write_compressed_data | ||
| 58 | { | ||
| 59 | my( $self, $key, $data ) = @_; | ||
| 60 | my $filename = sprintf '%s/%s.dtc', $self->{'dir'}, $key; | ||
| 61 | |||
| 62 | if( open my $OF, '>', $filename ) | ||
| 63 | { | ||
| 64 | binmode $OF; | ||
| 65 | print $OF $data; | ||
| 66 | close $OF; | ||
| 67 | } | ||
| 68 | else | ||
| 69 | { | ||
| 70 | die "Error opening cache file $filename for writing: $!"; | ||
| 71 | } | ||
| 72 | return $self | ||
| 73 | } | ||
| 74 | |||
| 75 | |||
| 76 | 1; |