| 1 | # Copyright 2017-2026, Paul Johnson (paul@pjcj.net) | ||
| 2 | |||
| 3 | # This software is free. It is licensed under the same terms as Perl itself. | ||
| 4 | |||
| 5 | # The latest version of this software should be available from my homepage: | ||
| 6 | # https://pjcj.net | ||
| 7 | |||
| 8 | package Devel::Cover::DB::IO::Base; | ||
| 9 | |||
| 10 | use strict; | ||
| 11 | use warnings; | ||
| 12 | |||
| 13 | use Fcntl ":flock"; | ||
| 14 | |||
| 15 | our $VERSION = '1.52'; # VERSION | ||
| 16 | |||
| 17 | sub new { | ||
| 18 | my $class = shift; | ||
| 19 | bless {@_}, $class | ||
| 20 | } | ||
| 21 | |||
| 22 | sub _lock { | ||
| 23 | my $self = shift; | ||
| 24 | my ($file, $type) = @_; | ||
| 25 | my $lock = "$file.lock"; | ||
| 26 | open my $fh, "+>>", $lock or die "Can't open $lock: $!\n"; | ||
| 27 | flock $fh, $type or die "Can't lock $lock: $!\n"; | ||
| 28 | $fh | ||
| 29 | } | ||
| 30 | |||
| 31 | sub _read { | ||
| 32 | my $self = shift; | ||
| 33 | my ($file, $reader) = @_; | ||
| 34 | my $lock_fh = $self->_lock($file, LOCK_SH); | ||
| 35 | $reader->() | ||
| 36 | } | ||
| 37 | |||
| 38 | sub _write { | ||
| 39 | my $self = shift; | ||
| 40 | my ($file, $writer) = @_; | ||
| 41 | my $lock_fh = $self->_lock($file, LOCK_EX); | ||
| 42 | unlink $file; | ||
| 43 | $writer->(); | ||
| 44 | $self | ||
| 45 | } | ||
| 46 | |||
| 47 | sub _read_fh { | ||
| 48 | my $self = shift; | ||
| 49 | my ($file, $reader) = @_; | ||
| 50 | $self->_read( | ||
| 51 | $file, | ||
| 52 | sub { | ||
| 53 | open my $fh, "<", $file or die "Can't open $file: $!\n"; | ||
| 54 | my $data = $reader->($fh); | ||
| 55 | close $fh or die "Can't close $file: $!\n"; | ||
| 56 | $data | ||
| 57 | } | ||
| 58 | ) | ||
| 59 | } | ||
| 60 | |||
| 61 | sub _write_fh { | ||
| 62 | my $self = shift; | ||
| 63 | my ($file, $writer) = @_; | ||
| 64 | $self->_write( | ||
| 65 | $file, | ||
| 66 | sub { | ||
| 67 | open my $fh, ">", $file or die "Can't open $file: $!\n"; | ||
| 68 | $writer->($fh); | ||
| 69 | close $fh or die "Can't close $file: $!\n"; | ||
| 70 | } | ||
| 71 | ) | ||
| 72 | } | ||
| 73 | |||
| 74 | " | ||
| 75 | Green trees call to me | ||
| 76 | I am free but life is so cheap | ||
| 77 | " | ||
| 78 | |||
| 79 | __END__ |