3f2ae663f6b5d4fa225aa6f6fdb30ee83be0ff22
[perl-indexdata-utils.git] / lib / IndexData / Utils / PersistentCounter.pm
1 package IndexData::Utils::PersistentCounter;
2
3 use 5.018002;
4 use strict;
5 use warnings;
6
7 use IO::File;
8
9
10 sub new {
11     my $class = shift();
12     my($file, $create) = @_;
13
14     if (! -f $file) {
15         return undef if !$create;
16         #   ### There is a bit of a race condition here, but it's not
17         #       something that's going to crop up in real life.
18         my $fh = new IO::File(">$file") || return undef;
19         $fh->print("1\n");
20         $fh->close() or return undef;
21     }
22
23     my $this = bless {
24         file => $file,
25     }, $class;
26
27     return $this;
28 }
29
30
31 sub next {
32     my $this = shift();
33
34     my $fh = new IO::File('+<' . $this->{file}) || return undef;
35     flock($fh, 2) || die "can't lock file";
36     my $n = <$fh>;
37     $fh->seek(0, 0);
38     sleep(int(rand(2)));
39     $fh->print($n+1, "\n");
40     $fh->close() or return undef;
41     return $n+0;
42 }
43
44
45 sub delete {
46     my $this = shift();
47
48     unlink $this->{file} or return 0;
49     return 1;
50 }
51
52
53 1;