home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl_ste.zip / File / CounterFile.pm next >
Text File  |  1996-10-31  |  8KB  |  326 lines

  1. # This -*-perl -*- module implements a persistent counter class.
  2. #
  3. # $Id: CounterFile.pm,v 0.9 1996/10/31 09:38:57 aas Exp $
  4. #
  5.  
  6. package File::CounterFile;
  7.  
  8.  
  9. =head1 NAME
  10.  
  11. File::CounterFile - Persistent counter class
  12.  
  13. =head1 SYNOPSIS
  14.  
  15.  use File::CounterFile;
  16.  $c = new File::CounterFile "COUNTER", "aa00";
  17.  
  18.  $id = $c->inc;
  19.  open(F, ">F$id");
  20.  
  21. =head1 DESCRIPTION
  22.  
  23. This module implements a persistent counter class.  Each counter is
  24. represented by a separate file in the file system.  File locking is
  25. applied, so multiple processes might try to access the same counters
  26. at the same time without risk of counter destruction.
  27.  
  28. You give the file name as the first parameter to the object
  29. constructor (C<new>).  The file is created if it does not exist.
  30.  
  31. If the file name does not start with "/" or ".", then it is
  32. interpreted as a file relative to C<$File::CounterFile::DEFAULT_DIR>.
  33. The default value for this variable is initialized from the
  34. environment variable C<TMPDIR>, or F</usr/tmp> is no environment
  35. variable is defined.  You may want to assign a different value to this
  36. variable before creating counters.
  37.  
  38. If you pass a second parameter to the constructor, that sets the
  39. initial value for a new counter.  This parameter only takes effect
  40. when the file is created (i.e. it does not exist before the call).
  41.  
  42. When you call the C<inc()> method, you increment the counter value by
  43. one. When you call C<dec()> the counter value is decrementd.  In both
  44. cases the new value is returned.  The C<dec()> method only works for
  45. numerical counters (digits only).
  46.  
  47. You can peek at the value of the counter (without incrementing it) by
  48. using the C<value()> method.
  49.  
  50. The counter can be locked and unlocked with the C<lock()> and
  51. C<unlock()> methods.  Incrementing and value retrieval is faster when
  52. the counter is locked, because we do not have to update the counter
  53. file all the time.  You can query whether the counter is locked with
  54. the C<locked()> method.
  55.  
  56. There is also an operator overloading interface to the
  57. File::CounterFile object.  This means that you might use the C<++>
  58. operator for incrementing the counter, C<--> operator for decrementing
  59. and you can interpolate counters diretly into strings.
  60.  
  61. =head1 BUGS
  62.  
  63. It uses flock(2) to lock the counter file.  This does not work on all
  64. systems.  Perhaps we should use the File::Lock module?
  65.  
  66. =head1 INSTALLATION
  67.  
  68. Copy this file to the F<File> subdirectory of your Perl 5 library
  69. directory (often F</usr/local/lib/perl5>).
  70.  
  71. =head1 COPYRIGHT
  72.  
  73. Copyright (c) 1995-1996 Gisle Aas. All rights reserved.
  74.  
  75. This library is free software; you can redistribute it and/or
  76. modify it under the same terms as Perl itself.
  77.  
  78. =head1 AUTHOR
  79.  
  80. Gisle Aas <aas@sn.no>
  81.  
  82. =cut
  83.  
  84. require 5.002;
  85. use Carp   qw(croak);
  86. use Symbol qw(gensym);
  87.  
  88. sub Version { $VERSION; }
  89. $VERSION = sprintf("%d.%02d", q$Revision: 0.9 $ =~ /(\d+)\.(\d+)/);
  90.  
  91. $MAGIC           = "#COUNTER-1.0\n";   # first line in counter files
  92. $DEFAULT_INITIAL = 0;                  # default initial counter value
  93.  
  94.  # default location for counter files
  95. $DEFAULT_DIR     = $ENV{TMPDIR} || "/usr/tmp";
  96.  
  97. # Experimental overloading.
  98. %OVERLOAD = ('++'     => \&inc,
  99.          '--'     => \&dec,
  100.          '""'     => \&value,
  101.          fallback => 1,
  102. );
  103.  
  104.  
  105. sub new
  106. {
  107.     my($class, $file, $initial) = @_;
  108.     croak "No file specified\n" unless defined $file;
  109.  
  110.     $file = "$DEFAULT_DIR/$file" unless $file =~ /^[\.\/]/;
  111.     $initial = $DEFAULT_INITIAL unless defined $initial;
  112.  
  113.     my $value;
  114.     if (-e $file) {
  115.     croak "Specified file is a directory" if -d _;
  116.     open(F, $file) or croak "Can't open $file: $!";
  117.     local($/) = "\n";
  118.     my $first_line = <F>;
  119.     $value = <F>;
  120.     close(F);
  121.     croak "Bad counter magic '$first_line' in $file" unless $first_line eq $MAGIC;
  122.     chomp($value);
  123.     } else {
  124.     open(F, ">$file") or croak "Can't create $file: $!";
  125.     print F $MAGIC;
  126.     print F $initial, "\n";
  127.     close(F);
  128.     $value = $initial;
  129.     }
  130.  
  131.     bless { file    => $file,  # the filename for the counter
  132.         value   => $value, # the current value
  133.         updated => 0,      # flag indicating if value has changed
  134.         # handle => XXX,   # file handle symbol. Only present when locked
  135.       };
  136. }
  137.  
  138.  
  139. sub locked
  140. {
  141.     exists shift->{handle};
  142. }
  143.  
  144.  
  145. sub lock
  146. {
  147.     my($self) = @_;
  148.     $self->unlock if $self->locked;
  149.  
  150.     my $fh = gensym();
  151.     my $file = $self->{file};
  152.  
  153.     open($fh, "+<$file") or croak "Can't open $file: $!";
  154.     flock($fh, 2) or croak "Can't flock: $!";  # 2 = exlusive lock
  155.  
  156.     local($/) = "\n";
  157.     my $magic = <$fh>;
  158.     if ($magic ne $MAGIC) {
  159.     $self->unlock;
  160.     croak("Bad counter magic '$magic' in $file");
  161.     }
  162.     chomp($self->{value} = <$fh>);
  163.  
  164.     $self->{handle}  = $fh;
  165.     $self->{updated} = 0;
  166.     $self;
  167. }
  168.  
  169.  
  170. sub unlock
  171. {
  172.     my($self) = @_;
  173.     return unless $self->locked;
  174.  
  175.     my $fh = $self->{handle};
  176.  
  177.     if ($self->{updated}) {
  178.     # write back new value
  179.     seek($fh, 0, 0) or croak "Can't seek to beginning: $!";
  180.     print $fh $MAGIC;
  181.     print $fh "$self->{value}\n";
  182.     }
  183.  
  184.     close($fh) or warn "Can't close: $!";
  185.     delete $self->{handle};
  186.     $self;
  187. }
  188.  
  189.  
  190. sub inc
  191. {
  192.     my($self) = @_;
  193.  
  194.     if ($self->locked) {
  195.     $self->{value}++;
  196.     $self->{updated} = 1;
  197.     } else {
  198.     $self->lock;
  199.     $self->{value}++;
  200.     $self->{updated} = 1;
  201.     $self->unlock;
  202.     }
  203.     $self->{value}; # return value
  204. }
  205.  
  206.  
  207. sub dec
  208. {
  209.     my($self) = @_;
  210.  
  211.     if ($self->locked) {
  212.     croak "Autodecrement is not magical in perl"
  213.         unless $self->{value} =~ /^\d+$/;
  214.     $self->{value}--;
  215.     $self->{updated} = 1;
  216.     } else {
  217.     $self->lock;
  218.     croak "Autodecrement is not magical in perl"
  219.         unless $self->{value} =~ /^\d+$/;
  220.     $self->{value}--;
  221.     $self->{updated} = 1;
  222.     $self->unlock;
  223.     }
  224.     $self->{value}; # return value
  225. }
  226.  
  227.  
  228. sub value
  229. {
  230.     my($self) = @_;
  231.     my $value;
  232.     if ($self->locked) {
  233.     $value = $self->{value};
  234.     } else {
  235.     $self->lock;
  236.     $value = $self->{value};
  237.     $self->unlock;
  238.     }
  239.     $value;
  240. }
  241.  
  242.  
  243. sub DESTROY
  244. {
  245.     my $self = shift;
  246.     $self->unlock;
  247. }
  248.  
  249. ####################################################################
  250. #
  251. # S E L F   T E S T   S E C T I O N
  252. #
  253. #####################################################################
  254. #
  255. # If we're not use'd or require'd execute self-test.
  256. #
  257. # Test is kept behind __END__ so it doesn't take uptime
  258. # and memory  unless explicitly required. If you're working
  259. # on the code you might find it easier to comment out the
  260. # eval and __END__ so that error line numbers make more sense.
  261.  
  262. package main;
  263.  
  264. eval join('',<DATA>) || die $@ unless caller();
  265.  
  266. 1;
  267.  
  268. __END__
  269.  
  270.  
  271. $cf = "./zz-counter-$$";  # the name for out temprary counter
  272.  
  273. # Test normal object creation and increment
  274.  
  275. $c = new File::CounterFile $cf;
  276.  
  277. $id1 = $c->inc;
  278. $id2 = $c->inc;
  279.  
  280. $c = new File::CounterFile $cf;
  281. $id3 = $c->inc;
  282. $id4 = $c->dec;
  283.  
  284. die "test failed" unless ($id1 == 1 && $id2 == 2 && $id3 == 3 && $id4 == 2);
  285. unlink $cf;
  286.  
  287. # Test magic increment
  288.  
  289. $id1 = (new File::CounterFile $cf, "aa98")->inc;
  290. $id2 = (new File::CounterFile $cf)->inc;
  291. $id3 = (new File::CounterFile $cf)->inc;
  292.  
  293. eval {
  294.     # This should now work because "Decrement is not magical in perl"
  295.     $c = new File::CounterFile $cf; $id4 = $c->dec; $c = undef;
  296. };
  297. die "test failed (No exception to catch)" unless $@;
  298.  
  299. #print "$id1 $id2 $id3\n";
  300.  
  301. die "test failed" unless ($id1 eq "aa99" && $id2 eq "ab00" && $id3 eq "ab01");
  302. unlink $cf;
  303.  
  304. # Test operator overloading
  305.  
  306. $c = new File::CounterFile $cf, "100";
  307.  
  308. $c->lock;
  309.  
  310. $c++;  # counter is now 101
  311. $c++;  # counter is now 102
  312. $c++;  # counter is now 103
  313. $c--;  # counter is now 102 again
  314.  
  315. $id1 = "$c";
  316. $id2 = ++$c;
  317.  
  318. $c = undef;  # destroy object
  319.  
  320. unlink $cf;
  321.  
  322. die "test failed" unless $id1 == 102 && $id2 == 103;
  323.  
  324.  
  325. print "Selftest for File::CounterFile $File::CounterFile::VERSION ok\n";
  326.