home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 March / PCWorld_2003-03_cd.bin / Software / Topware / activeperl / ActivePerl / Perl / lib / Tie / File.pm < prev    next >
Encoding:
Perl POD Document  |  2002-06-19  |  65.4 KB  |  2,246 lines

  1.  
  2. package Tie::File;
  3. require 5.005;
  4. use Carp;
  5. use POSIX 'SEEK_SET';
  6. use Fcntl 'O_CREAT', 'O_RDWR', 'LOCK_EX', 'O_WRONLY', 'O_RDONLY';
  7. sub O_ACCMODE () { O_RDONLY | O_RDWR | O_WRONLY }
  8.  
  9. $VERSION = "0.93";
  10. my $DEFAULT_MEMORY_SIZE = 1<<21;    # 2 megabytes
  11. my $DEFAULT_AUTODEFER_THRESHHOLD = 3; # 3 records
  12. my $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD = 65536; # 16 disk blocksful
  13.  
  14. my %good_opt = map {$_ => 1, "-$_" => 1} 
  15.                qw(memory dw_size mode recsep discipline autodefer autochomp);
  16.  
  17. sub TIEARRAY {
  18.   if (@_ % 2 != 0) {
  19.     croak "usage: tie \@array, $_[0], filename, [option => value]...";
  20.   }
  21.   my ($pack, $file, %opts) = @_;
  22.  
  23.   # transform '-foo' keys into 'foo' keys
  24.   for my $key (keys %opts) {
  25.     unless ($good_opt{$key}) {
  26.       croak("$pack: Unrecognized option '$key'\n");
  27.     }
  28.     my $okey = $key;
  29.     if ($key =~ s/^-+//) {
  30.       $opts{$key} = delete $opts{$okey};
  31.     }
  32.   }
  33.  
  34.   unless (defined $opts{memory}) {
  35.     # default is the larger of the default cache size and the 
  36.     # deferred-write buffer size (if specified)
  37.     $opts{memory} = $DEFAULT_MEMORY_SIZE;
  38.     $opts{memory} = $opts{dw_size} 
  39.       if defined $opts{dw_size} && $opts{dw_size} > $DEFAULT_MEMORY_SIZE;
  40.     # Dora Winifred Read
  41.   }
  42.   $opts{dw_size} = $opts{memory} unless defined $opts{dw_size};
  43.   if ($opts{dw_size} > $opts{memory}) {
  44.       croak("$pack: dw_size may not be larger than total memory allocation\n");
  45.   }
  46.   # are we in deferred-write mode?
  47.   $opts{defer} = 0 unless defined $opts{defer};
  48.   $opts{deferred} = {};         # no records are presently deferred
  49.   $opts{deferred_s} = 0;        # count of total bytes in ->{deferred}
  50.   $opts{deferred_max} = -1;     # empty
  51.  
  52.   # the cache is a hash instead of an array because it is likely to be
  53.   # sparsely populated
  54.   $opts{cache} = Tie::File::Cache->new($opts{memory}); 
  55.  
  56.   # autodeferment is enabled by default
  57.   $opts{autodefer} = 1 unless defined $opts{autodefer};
  58.   $opts{autodeferring} = 0;     # but is not initially active
  59.   $opts{ad_history} = [];
  60.   $opts{autodefer_threshhold} = $DEFAULT_AUTODEFER_THRESHHOLD
  61.     unless defined $opts{autodefer_threshhold};
  62.   $opts{autodefer_filelen_threshhold} = $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD
  63.     unless defined $opts{autodefer_filelen_threshhold};
  64.  
  65.   $opts{offsets} = [0];
  66.   $opts{filename} = $file;
  67.   unless (defined $opts{recsep}) { 
  68.     $opts{recsep} = _default_recsep();
  69.   }
  70.   $opts{recseplen} = length($opts{recsep});
  71.   if ($opts{recseplen} == 0) {
  72.     croak "Empty record separator not supported by $pack";
  73.   }
  74.  
  75.   $opts{autochomp} = 1 unless defined $opts{autochomp};
  76.  
  77.   $opts{mode} = O_CREAT|O_RDWR unless defined $opts{mode};
  78.   $opts{rdonly} = (($opts{mode} & O_ACCMODE) == O_RDONLY);
  79.   $opts{sawlastrec} = undef;
  80.  
  81.   my $fh;
  82.  
  83.   if (UNIVERSAL::isa($file, 'GLOB')) {
  84.     # We use 1 here on the theory that some systems 
  85.     # may not indicate failure if we use 0.
  86.     # MSWin32 does not indicate failure with 0, but I don't know if
  87.     # it will indicate failure with 1 or not.
  88.     unless (seek $file, 1, SEEK_SET) {
  89.       croak "$pack: your filehandle does not appear to be seekable";
  90.     }
  91.     seek $file, 0, SEEK_SET     # put it back
  92.     $fh = $file;                # setting binmode is the user's problem
  93.   } elsif (ref $file) {
  94.     croak "usage: tie \@array, $pack, filename, [option => value]...";
  95.   } else {
  96.     $fh = \do { local *FH };   # only works in 5.005 and later
  97.     sysopen $fh, $file, $opts{mode}, 0666 or return;
  98.     binmode $fh;
  99.   }
  100.   { my $ofh = select $fh; $| = 1; select $ofh } # autoflush on write
  101.   if (defined $opts{discipline} && $] >= 5.006) {
  102.     # This avoids a compile-time warning under 5.005
  103.     eval 'binmode($fh, $opts{discipline})';
  104.     croak $@ if $@ =~ /unknown discipline/i;
  105.     die if $@;
  106.   }
  107.   $opts{fh} = $fh;
  108.  
  109.   bless \%opts => $pack;
  110. }
  111.  
  112. sub FETCH {
  113.   my ($self, $n) = @_;
  114.   my $rec;
  115.  
  116.   # check the defer buffer
  117.   if ($self->_is_deferring && exists $self->{deferred}{$n}) {
  118.     $rec = $self->{deferred}{$n};
  119.   } else {
  120.     $rec = $self->_fetch($n);
  121.   }
  122.  
  123.   $self->_chomp1($rec);
  124. }
  125.  
  126. # Chomp many records in-place; return nothing useful
  127. sub _chomp {
  128.   my $self = shift;
  129.   return unless $self->{autochomp};
  130.   if ($self->{autochomp}) {
  131.     for (@_) {
  132.       next unless defined;
  133.       substr($_, - $self->{recseplen}) = "";
  134.     }
  135.   }
  136. }
  137.  
  138. # Chomp one record in-place; return modified record
  139. sub _chomp1 {
  140.   my ($self, $rec) = @_;
  141.   return $rec unless $self->{autochomp};
  142.   return unless defined $rec;
  143.   substr($rec, - $self->{recseplen}) = "";
  144.   $rec;
  145. }
  146.  
  147. sub _fetch {
  148.   my ($self, $n) = @_;
  149.  
  150.   # check the record cache
  151.   { my $cached = $self->{cache}->lookup($n);
  152.     return $cached if defined $cached;
  153.   }
  154.  
  155.   if ($#{$self->{offsets}} < $n) {
  156.     return if $self->{eof};
  157.     my $o = $self->_fill_offsets_to($n);
  158.     # If it's still undefined, there is no such record, so return 'undef'
  159.     return unless defined $o;
  160.   }
  161.  
  162.   my $fh = $self->{FH};
  163.   $self->_seek($n);             # we can do this now that offsets is populated
  164.   my $rec = $self->_read_record;
  165.  
  166. # If we happen to have just read the first record, check to see if
  167. # the length of the record matches what 'tell' says.  If not, Tie::File
  168. # won't work, and should drop dead.
  169. #
  170. #  if ($n == 0 && defined($rec) && tell($self->{fh}) != length($rec)) {
  171. #    if (defined $self->{discipline}) {
  172. #      croak "I/O discipline $self->{discipline} not supported";
  173. #    } else {
  174. #      croak "File encoding not supported";
  175. #    }
  176. #  }
  177.  
  178.   $self->{cache}->insert($n, $rec) if defined $rec && not $self->{flushing};
  179.   $rec;
  180. }
  181.  
  182. sub STORE {
  183.   my ($self, $n, $rec) = @_;
  184.   die "STORE called from _check_integrity!" if $DIAGNOSTIC;
  185.  
  186.   $self->_fixrecs($rec);
  187.  
  188.   if ($self->{autodefer}) {
  189.     $self->_annotate_ad_history($n);
  190.   }
  191.  
  192.   return $self->_store_deferred($n, $rec) if $self->_is_deferring;
  193.  
  194.  
  195.   # We need this to decide whether the new record will fit
  196.   # It incidentally populates the offsets table 
  197.   # Note we have to do this before we alter the cache
  198.   # 20020324 Wait, but this DOES alter the cache.  TODO BUG?
  199.   my $oldrec = $self->_fetch($n);
  200.  
  201.   if (defined($self->{cache}->lookup($n))) {
  202.     $self->{cache}->update($n, $rec);
  203.   }
  204.  
  205.   if (not defined $oldrec) {
  206.     # We're storing a record beyond the end of the file
  207.     $self->_extend_file_to($n+1);
  208.     $oldrec = $self->{recsep};
  209.   }
  210.   my $len_diff = length($rec) - length($oldrec);
  211.  
  212.   # length($oldrec) here is not consistent with text mode  TODO XXX BUG
  213.   $self->_twrite($rec, $self->{offsets}[$n], length($oldrec));
  214.  
  215.   # now update the offsets
  216.   # array slice goes from element $n+1 (the first one to move)
  217.   # to the end
  218.   for (@{$self->{offsets}}[$n+1 .. $#{$self->{offsets}}]) {
  219.     $_ += $len_diff;
  220.   }
  221. }
  222.  
  223. sub _store_deferred {
  224.   my ($self, $n, $rec) = @_;
  225.   $self->{cache}->remove($n);
  226.   my $old_deferred = $self->{deferred}{$n};
  227.  
  228.   if (defined $self->{deferred_max} && $n > $self->{deferred_max}) {
  229.     $self->{deferred_max} = $n;
  230.   }
  231.   $self->{deferred}{$n} = $rec;
  232.  
  233.   my $len_diff = length($rec);
  234.   $len_diff -= length($old_deferred) if defined $old_deferred;
  235.   $self->{deferred_s} += $len_diff;
  236.   $self->{cache}->adj_limit(-$len_diff);
  237.   if ($self->{deferred_s} > $self->{dw_size}) {
  238.     $self->_flush;
  239.   } elsif ($self->_cache_too_full) {
  240.     $self->_cache_flush;
  241.   }
  242. }
  243.  
  244. # Remove a single record from the deferred-write buffer without writing it
  245. # The record need not be present
  246. sub _delete_deferred {
  247.   my ($self, $n) = @_;
  248.   my $rec = delete $self->{deferred}{$n};
  249.   return unless defined $rec;
  250.  
  251.   if (defined $self->{deferred_max} 
  252.       && $n == $self->{deferred_max}) {
  253.     undef $self->{deferred_max};
  254.   }
  255.  
  256.   $self->{deferred_s} -= length $rec;
  257.   $self->{cache}->adj_limit(length $rec);
  258. }
  259.  
  260. sub FETCHSIZE {
  261.   my $self = shift;
  262.   my $n = $#{$self->{offsets}};
  263.   # 20020317 Change this to binary search
  264.   unless ($self->{eof}) {
  265.     while (defined ($self->_fill_offsets_to($n+1))) {
  266.       ++$n;
  267.     }
  268.   }
  269.   my $top_deferred = $self->_defer_max;
  270.   $n = $top_deferred+1 if defined $top_deferred && $n < $top_deferred+1;
  271.   $n;
  272. }
  273.  
  274. sub STORESIZE {
  275.   my ($self, $len) = @_;
  276.  
  277.   if ($self->{autodefer}) {
  278.     $self->_annotate_ad_history('STORESIZE');
  279.   }
  280.  
  281.   my $olen = $self->FETCHSIZE;
  282.   return if $len == $olen;      # Woo-hoo!
  283.  
  284.   # file gets longer
  285.   if ($len > $olen) {
  286.     if ($self->_is_deferring) {
  287.       for ($olen .. $len-1) {
  288.         $self->_store_deferred($_, $self->{recsep});
  289.       }
  290.     } else {
  291.       $self->_extend_file_to($len);
  292.     }
  293.     return;
  294.   }
  295.  
  296.   # file gets shorter
  297.   if ($self->_is_deferring) {
  298.     # TODO maybe replace this with map-plus-assignment?
  299.     for (grep $_ >= $len, keys %{$self->{deferred}}) {
  300.       $self->_delete_deferred($_);
  301.     }
  302.     $self->{deferred_max} = $len-1;
  303.   }
  304.  
  305.   $self->_seek($len);
  306.   $self->_chop_file;
  307.   $#{$self->{offsets}} = $len;
  308. #  $self->{offsets}[0] = 0;      # in case we just chopped this
  309.  
  310.   $self->{cache}->remove(grep $_ >= $len, $self->{cache}->ckeys);
  311. }
  312.  
  313. sub PUSH {
  314.   my $self = shift;
  315.   $self->SPLICE($self->FETCHSIZE, scalar(@_), @_);
  316. #  $self->FETCHSIZE;  # av.c takes care of this for me
  317. }
  318.  
  319. sub POP {
  320.   my $self = shift;
  321.   my $size = $self->FETCHSIZE;
  322.   return if $size == 0;
  323. #  print STDERR "# POPPITY POP POP POP\n";
  324.   scalar $self->SPLICE($size-1, 1);
  325. }
  326.  
  327. sub SHIFT {
  328.   my $self = shift;
  329.   scalar $self->SPLICE(0, 1);
  330. }
  331.  
  332. sub UNSHIFT {
  333.   my $self = shift;
  334.   $self->SPLICE(0, 0, @_);
  335.   # $self->FETCHSIZE; # av.c takes care of this for me
  336. }
  337.  
  338. sub CLEAR {
  339.   my $self = shift;
  340.  
  341.   if ($self->{autodefer}) {
  342.     $self->_annotate_ad_history('CLEAR');
  343.   }
  344.  
  345.   $self->_seekb(0);
  346.   $self->_chop_file;
  347.     $self->{cache}->set_limit($self->{memory});
  348.     $self->{cache}->empty;
  349.   @{$self->{offsets}} = (0);
  350.   %{$self->{deferred}}= ();
  351.     $self->{deferred_s} = 0;
  352.     $self->{deferred_max} = -1;
  353. }
  354.  
  355. sub EXTEND {
  356.   my ($self, $n) = @_;
  357.  
  358.   # No need to pre-extend anything in this case
  359.   return if $self->_is_deferring;
  360.  
  361.   $self->_fill_offsets_to($n);
  362.   $self->_extend_file_to($n);
  363. }
  364.  
  365. sub DELETE {
  366.   my ($self, $n) = @_;
  367.  
  368.   if ($self->{autodefer}) {
  369.     $self->_annotate_ad_history('DELETE');
  370.   }
  371.  
  372.   my $lastrec = $self->FETCHSIZE-1;
  373.   my $rec = $self->FETCH($n);
  374.   $self->_delete_deferred($n) if $self->_is_deferring;
  375.   if ($n == $lastrec) {
  376.     $self->_seek($n);
  377.     $self->_chop_file;
  378.     $#{$self->{offsets}}--;
  379.     $self->{cache}->remove($n);
  380.     # perhaps in this case I should also remove trailing null records?
  381.     # 20020316
  382.     # Note that delete @a[-3..-1] deletes the records in the wrong order,
  383.     # so we only chop the very last one out of the file.  We could repair this
  384.     # by tracking deleted records inside the object.
  385.   } elsif ($n < $lastrec) {
  386.     $self->STORE($n, "");
  387.   }
  388.   $rec;
  389. }
  390.  
  391. sub EXISTS {
  392.   my ($self, $n) = @_;
  393.   return 1 if exists $self->{deferred}{$n};
  394.   $self->_fill_offsets_to($n);  # I think this is unnecessary
  395.   $n < $self->FETCHSIZE;
  396. }
  397.  
  398. sub SPLICE {
  399.   my $self = shift;
  400.  
  401.   if ($self->{autodefer}) {
  402.     $self->_annotate_ad_history('SPLICE');
  403.   }
  404.  
  405.   $self->_flush if $self->_is_deferring; # move this up?
  406.   if (wantarray) {
  407.     $self->_chomp(my @a = $self->_splice(@_));
  408.     @a;
  409.   } else {
  410.     $self->_chomp1(scalar $self->_splice(@_));
  411.   }
  412. }
  413.  
  414. sub DESTROY {
  415.   my $self = shift;
  416.   $self->flush if $self->_is_deferring;
  417.   $self->{cache}->delink if defined $self->{cache}; # break circular link
  418. }
  419.  
  420. sub _splice {
  421.   my ($self, $pos, $nrecs, @data) = @_;
  422.   my @result;
  423.  
  424.   $pos = 0 unless defined $pos;
  425.  
  426.   # Deal with negative and other out-of-range positions
  427.   # Also set default for $nrecs 
  428.   {
  429.     my $oldsize = $self->FETCHSIZE;
  430.     $nrecs = $oldsize unless defined $nrecs;
  431.     my $oldpos = $pos;
  432.  
  433.     if ($pos < 0) {
  434.       $pos += $oldsize;
  435.       if ($pos < 0) {
  436.         croak "Modification of non-creatable array value attempted, subscript $oldpos";
  437.       }
  438.     }
  439.  
  440.     if ($pos > $oldsize) {
  441.       return unless @data;
  442.       $pos = $oldsize;          # This is what perl does for normal arrays
  443.     }
  444.  
  445.     # The manual is very unclear here
  446.     if ($nrecs < 0) {
  447.       $nrecs = $oldsize - $pos + $nrecs;
  448.       $nrecs = 0 if $nrecs < 0;
  449.     }
  450.   }
  451.  
  452.   $self->_fixrecs(@data);
  453.   my $data = join '', @data;
  454.   my $datalen = length $data;
  455.   my $oldlen = 0;
  456.  
  457.   # compute length of data being removed
  458.   for ($pos .. $pos+$nrecs-1) {
  459.     last unless defined $self->_fill_offsets_to($_);
  460.     my $rec = $self->_fetch($_);
  461.     last unless defined $rec;
  462.     push @result, $rec;
  463.  
  464.     # Why don't we just use length($rec) here?
  465.     # Because that record might have come from the cache.  _splice
  466.     # might have been called to flush out the deferred-write records,
  467.     # and in this case length($rec) is the length of the record to be
  468.     # *written*, not the length of the actual record in the file.  But
  469.     # the offsets are still true. 20020322
  470.     $oldlen += $self->{offsets}[$_+1] - $self->{offsets}[$_]
  471.       if defined $self->{offsets}[$_+1];
  472.   }
  473.  
  474.   # Modify the file
  475.   $self->_twrite($data, $self->{offsets}[$pos], $oldlen);
  476.  
  477.   # update the offsets table part 1
  478.   # compute the offsets of the new records:
  479.   my @new_offsets;
  480.   if (@data) {
  481.     push @new_offsets, $self->{offsets}[$pos];
  482.     for (0 .. $#data-1) {
  483.       push @new_offsets, $new_offsets[-1] + length($data[$_]);
  484.     }
  485.   }
  486.  
  487.   # If we're about to splice out the end of the offsets table...
  488.   if ($pos + $nrecs >= @{$self->{offsets}}) {
  489.     $self->{eof} = 0;           # ... the table is no longer complete
  490.   }
  491.   splice(@{$self->{offsets}}, $pos, $nrecs, @new_offsets);
  492.  
  493.   # update the offsets table part 2
  494.   # adjust the offsets of the following old records
  495.   for ($pos+@data .. $#{$self->{offsets}}) {
  496.     $self->{offsets}[$_] += $datalen - $oldlen;
  497.   }
  498.   # If we scrubbed out all known offsets, regenerate the trivial table
  499.   # that knows that the file does indeed start at 0.
  500.   $self->{offsets}[0] = 0 unless @{$self->{offsets}};
  501.   # If the file got longer, the offsets table is no longer complete
  502.   $self->{eof} = 0 if @data > $nrecs;
  503.   
  504.  
  505.   # Perhaps the following cache foolery could be factored out
  506.   # into a bunch of mor opaque cache functions.  For example,
  507.   # it's odd to delete a record from the cache and then remove
  508.   # it from the LRU queue later on; there should be a function to
  509.   # do both at once.
  510.  
  511.   # update the read cache, part 1
  512.   # modified records
  513.   for ($pos .. $pos+$nrecs-1) {
  514.     my $new = $data[$_-$pos];
  515.     if (defined $new) {
  516.       $self->{cache}->update($_, $new);
  517.     } else {
  518.       $self->{cache}->remove($_);
  519.     }
  520.   }
  521.  
  522.   # update the read cache, part 2
  523.   # moved records - records past the site of the change
  524.   # need to be renumbered
  525.   # Maybe merge this with the previous block?
  526.   {
  527.     my @oldkeys = grep $_ >= $pos + $nrecs, $self->{cache}->ckeys;
  528.     my @newkeys = map $_-$nrecs+@data, @oldkeys;
  529.     $self->{cache}->rekey(\@oldkeys, \@newkeys);
  530.   }
  531.  
  532.   # Now there might be too much data in the cache, if we spliced out
  533.   # some short records and spliced in some long ones.  If so, flush
  534.   # the cache.
  535.   $self->_cache_flush;
  536.  
  537.   # Yes, the return value of 'splice' *is* actually this complicated
  538.   wantarray ? @result : @result ? $result[-1] : undef;
  539. }
  540.  
  541. # write data into the file
  542. # $data is the data to be written. 
  543. # it should be written at position $pos, and should overwrite
  544. # exactly $len of the following bytes.  
  545. # Note that if length($data) > $len, the subsequent bytes will have to 
  546. # be moved up, and if length($data) < $len, they will have to
  547. # be moved down
  548. sub _twrite {
  549.   my ($self, $data, $pos, $len) = @_;
  550.  
  551.   unless (defined $pos) {
  552.     die "\$pos was undefined in _twrite";
  553.   }
  554.  
  555.   my $len_diff = length($data) - $len;
  556.  
  557.   if ($len_diff == 0) {          # Woo-hoo!
  558.     my $fh = $self->{fh};
  559.     $self->_seekb($pos);
  560.     $self->_write_record($data);
  561.     return;                     # well, that was easy.
  562.   }
  563.  
  564.   # the two records are of different lengths
  565.   # our strategy here: rewrite the tail of the file,
  566.   # reading ahead one buffer at a time
  567.   # $bufsize is required to be at least as large as the data we're overwriting
  568.   my $bufsize = _bufsize($len_diff);
  569.   my ($writepos, $readpos) = ($pos, $pos+$len);
  570.   my $next_block;
  571.   my $more_data;
  572.  
  573.   # Seems like there ought to be a way to avoid the repeated code
  574.   # and the special case here.  The read(1) is also a little weird.
  575.   # Think about this.
  576.   do {
  577.     $self->_seekb($readpos);
  578.     my $br = read $self->{fh}, $next_block, $bufsize;
  579.     $more_data = read $self->{fh}, my($dummy), 1;
  580.     $self->_seekb($writepos);
  581.     $self->_write_record($data);
  582.     $readpos += $br;
  583.     $writepos += length $data;
  584.     $data = $next_block;
  585.   } while $more_data;           # BUG XXX TODO how could this have worked?
  586.   $self->_seekb($writepos);
  587.   $self->_write_record($next_block);
  588.  
  589.   # There might be leftover data at the end of the file
  590.   $self->_chop_file if $len_diff < 0;
  591. }
  592.  
  593. # If a record does not already end with the appropriate terminator
  594. # string, append one.
  595. sub _fixrecs {
  596.   my $self = shift;
  597.   for (@_) {
  598.     $_ = "" unless defined $_;
  599.     $_ .= $self->{recsep}
  600.       unless substr($_, - $self->{recseplen}) eq $self->{recsep};
  601.   }
  602. }
  603.  
  604.  
  605. ################################################################
  606. #
  607. # Basic read, write, and seek
  608. #
  609.  
  610. # seek to the beginning of record #$n
  611. # Assumes that the offsets table is already correctly populated
  612. #
  613. # Note that $n=-1 has a special meaning here: It means the start of
  614. # the last known record; this may or may not be the very last record
  615. # in the file, depending on whether the offsets table is fully populated.
  616. #
  617. sub _seek {
  618.   my ($self, $n) = @_;
  619.   my $o = $self->{offsets}[$n];
  620.   defined($o)
  621.     or confess("logic error: undefined offset for record $n");
  622.   seek $self->{fh}, $o, SEEK_SET
  623.     or die "Couldn't seek filehandle: $!";  # "Should never happen."
  624. }
  625.  
  626. sub _seekb {
  627.   my ($self, $b) = @_;
  628.   seek $self->{fh}, $b, SEEK_SET
  629.     or die "Couldn't seek filehandle: $!";  # "Should never happen."
  630. }
  631.  
  632. # populate the offsets table up to the beginning of record $n
  633. # return the offset of record $n
  634. sub _fill_offsets_to {
  635.   my ($self, $n) = @_;
  636.  
  637.   return $self->{offsets}[$n] if $self->{eof};
  638.  
  639.   my $fh = $self->{fh};
  640.   local *OFF = $self->{offsets};
  641.   my $rec;
  642.  
  643.   until ($#OFF >= $n) {
  644.     my $o = $OFF[-1];
  645.     $self->_seek(-1);           # tricky -- see comment at _seek
  646.     $rec = $self->_read_record;
  647.     if (defined $rec) {
  648.       push @OFF, tell $fh;
  649.     } else {
  650.       $self->{eof} = 1;
  651.       return;                   # It turns out there is no such record
  652.     }
  653.   }
  654.  
  655.   # we have now read all the records up to record n-1,
  656.   # so we can return the offset of record n
  657.   return $OFF[$n];
  658. }
  659.  
  660. # assumes that $rec is already suitably terminated
  661. sub _write_record {
  662.   my ($self, $rec) = @_;
  663.   my $fh = $self->{fh};
  664.   local $\ = "";
  665.   print $fh $rec
  666.     or die "Couldn't write record: $!";  # "Should never happen."
  667. #  $self->{_written} += length($rec);
  668. }
  669.  
  670. sub _read_record {
  671.   my $self = shift;
  672.   my $rec;
  673.   { local $/ = $self->{recsep};
  674.     my $fh = $self->{fh};
  675.     $rec = <$fh>;
  676.   }
  677.   return unless defined $rec;
  678.   if (! $self->{sawlastrec} && 
  679.       substr($rec, -$self->{recseplen}) ne $self->{recsep}) {
  680.     # improperly terminated final record --- quietly fix it.
  681. #    my $ac = substr($rec, -$self->{recseplen});
  682. #    $ac =~ s/\n/\\n/g;
  683.     $self->{sawlastrec} = 1;
  684.     unless ($self->{rdonly}) {
  685.       local $\ = "";
  686.       my $fh = $self->{fh};
  687.       print $fh $self->{recsep};
  688.     }
  689.     $rec .= $self->{recsep};
  690.   }
  691. #  $self->{_read} += length($rec) if defined $rec;
  692.   $rec;
  693. }
  694.  
  695. sub _rw_stats {
  696.   my $self = shift;
  697.   @{$self}{'_read', '_written'};
  698. }
  699.  
  700. ################################################################
  701. #
  702. # Read cache management
  703.  
  704. sub _cache_flush {
  705.   my ($self) = @_;
  706.   $self->{cache}->reduce_size_to($self->{memory} - $self->{deferred_s});
  707. }
  708.  
  709. sub _cache_too_full {
  710.   my $self = shift;
  711.   $self->{cache}->bytes + $self->{deferred_s} >= $self->{memory};
  712. }
  713.  
  714. ################################################################
  715. #
  716. # File custodial services
  717. #
  718.  
  719.  
  720. # We have read to the end of the file and have the offsets table
  721. # entirely populated.  Now we need to write a new record beyond
  722. # the end of the file.  We prepare for this by writing
  723. # empty records into the file up to the position we want
  724. #
  725. # assumes that the offsets table already contains the offset of record $n,
  726. # if it exists, and extends to the end of the file if not.
  727. sub _extend_file_to {
  728.   my ($self, $n) = @_;
  729.   $self->_seek(-1);             # position after the end of the last record
  730.   my $pos = $self->{offsets}[-1];
  731.  
  732.   # the offsets table has one entry more than the total number of records
  733.   my $extras = $n - $#{$self->{offsets}};
  734.  
  735.   # Todo : just use $self->{recsep} x $extras here?
  736.   while ($extras-- > 0) {
  737.     $self->_write_record($self->{recsep});
  738.     push @{$self->{offsets}}, tell $self->{fh};
  739.   }
  740. }
  741.  
  742. # Truncate the file at the current position
  743. sub _chop_file {
  744.   my $self = shift;
  745.   truncate $self->{fh}, tell($self->{fh});
  746. }
  747.  
  748.  
  749. # compute the size of a buffer suitable for moving
  750. # all the data in a file forward $n bytes
  751. # ($n may be negative)
  752. # The result should be at least $n.
  753. sub _bufsize {
  754.   my $n = shift;
  755.   return 8192 if $n < 0;
  756.   my $b = $n & ~8191;
  757.   $b += 8192 if $n & 8191;
  758.   $b;
  759. }
  760.  
  761. ################################################################
  762. #
  763. # Miscellaneous public methods
  764. #
  765.  
  766. # Lock the file
  767. sub flock {
  768.   my ($self, $op) = @_;
  769.   unless (@_ <= 3) {
  770.     my $pack = ref $self;
  771.     croak "Usage: $pack\->flock([OPERATION])";
  772.   }
  773.   my $fh = $self->{fh};
  774.   $op = LOCK_EX unless defined $op;
  775.   flock $fh, $op;
  776. }
  777.  
  778. # Get/set autochomp option
  779. sub autochomp {
  780.   my $self = shift;
  781.   if (@_) {
  782.     my $old = $self->{autochomp};
  783.     $self->{autochomp} = shift;
  784.     $old;
  785.   } else {
  786.     $self->{autochomp};
  787.   }
  788. }
  789.  
  790. ################################################################
  791. #
  792. # Matters related to deferred writing
  793. #
  794.  
  795. # Defer writes
  796. sub defer {
  797.   my $self = shift;
  798.   $self->_stop_autodeferring;
  799.   @{$self->{ad_history}} = ();
  800.   $self->{defer} = 1;
  801. }
  802.  
  803. # Flush deferred writes
  804. #
  805. # This could be better optimized to write the file in one pass, instead
  806. # of one pass per block of records.  But that will require modifications
  807. # to _twrite, so I should have a good _twite test suite first.
  808. sub flush {
  809.   my $self = shift;
  810.  
  811.   $self->_flush;
  812.   $self->{defer} = 0;
  813. }
  814.  
  815. sub _flush {
  816.   my $self = shift;
  817.   my @writable = sort {$a<=>$b} (keys %{$self->{deferred}});
  818.   
  819.   while (@writable) {
  820.     # gather all consecutive records from the front of @writable
  821.     my $first_rec = shift @writable;
  822.     my $last_rec = $first_rec+1;
  823.     ++$last_rec, shift @writable while @writable && $last_rec == $writable[0];
  824.     --$last_rec;
  825.     $self->_fill_offsets_to($last_rec);
  826.     $self->_extend_file_to($last_rec);
  827.     $self->_splice($first_rec, $last_rec-$first_rec+1, 
  828.                    @{$self->{deferred}}{$first_rec .. $last_rec});
  829.   }
  830.  
  831.   $self->_discard;               # clear out defered-write-cache
  832. }
  833.  
  834. # Discard deferred writes and disable future deferred writes
  835. sub discard {
  836.   my $self = shift;
  837.   $self->_discard;
  838.   $self->{defer} = 0;
  839. }
  840.  
  841. # Discard deferred writes, but retain old deferred writing mode
  842. sub _discard {
  843.   my $self = shift;
  844.   %{$self->{deferred}} = ();
  845.   $self->{deferred_s}  = 0;
  846.   $self->{deferred_max}  = -1;
  847.   $self->{cache}->set_limit($self->{memory});
  848. }
  849.  
  850. # Deferred writing is enabled, either explicitly ($self->{defer})
  851. # or automatically ($self->{autodeferring})
  852. sub _is_deferring {
  853.   my $self = shift;
  854.   $self->{defer} || $self->{autodeferring};
  855. }
  856.  
  857. # The largest record number of any deferred record
  858. sub _defer_max {
  859.   my $self = shift;
  860.   return $self->{deferred_max} if defined $self->{deferred_max};
  861.   my $max = -1;
  862.   for my $key (keys %{$self->{deferred}}) {
  863.     $max = $key if $key > $max;
  864.   }
  865.   $self->{deferred_max} = $max;
  866.   $max;
  867. }
  868.  
  869. ################################################################
  870. #
  871. # Matters related to autodeferment
  872. #
  873.  
  874. # Get/set autodefer option
  875. sub autodefer {
  876.   my $self = shift;
  877.   if (@_) {
  878.     my $old = $self->{autodefer};
  879.     $self->{autodefer} = shift;
  880.     if ($old) {
  881.       $self->_stop_autodeferring;
  882.       @{$self->{ad_history}} = ();
  883.     }
  884.     $old;
  885.   } else {
  886.     $self->{autodefer};
  887.   }
  888. }
  889.  
  890. # The user is trying to store record #$n Record that in the history,
  891. # and then enable (or disable) autodeferment if that seems useful.
  892. # Note that it's OK for $n to be a non-number, as long as the function
  893. # is prepared to deal with that.  Nobody else looks at the ad_history.
  894. #
  895. # Now, what does the ad_history mean, and what is this function doing?
  896. # Essentially, the idea is to enable autodeferring when we see that the
  897. # user has made three consecutive STORE calls to three consecutive records.
  898. # ("Three" is actually ->{autodefer_threshhold}.)
  899. # A STORE call for record #$n inserts $n into the autodefer history,
  900. # and if the history contains three consecutive records, we enable 
  901. # autodeferment.  An ad_history of [X, Y] means that the most recent
  902. # STOREs were for records X, X+1, ..., Y, in that order.  
  903. #
  904. # Inserting a nonconsecutive number erases the history and starts over.
  905. #
  906. # Performing a special operation like SPLICE erases the history.
  907. #
  908. # There's one special case: CLEAR means that CLEAR was just called.
  909. # In this case, we prime the history with [-2, -1] so that if the next
  910. # write is for record 0, autodeferring goes on immediately.  This is for
  911. # the common special case of "@a = (...)".
  912. #
  913. sub _annotate_ad_history {
  914.   my ($self, $n) = @_;
  915.   return unless $self->{autodefer}; # feature is disabled
  916.   return if $self->{defer};     # already in explicit defer mode
  917.   return unless $self->{offsets}[-1] >= $self->{autodefer_filelen_threshhold};
  918.  
  919.   local *H = $self->{ad_history};
  920.   if ($n eq 'CLEAR') {
  921.     @H = (-2, -1);              # prime the history with fake records
  922.     $self->_stop_autodeferring;
  923.   } elsif ($n =~ /^\d+$/) {
  924.     if (@H == 0) {
  925.       @H =  ($n, $n);
  926.     } else {                    # @H == 2
  927.       if ($H[1] == $n-1) {      # another consecutive record
  928.         $H[1]++;
  929.         if ($H[1] - $H[0] + 1 >= $self->{autodefer_threshhold}) {
  930.           $self->{autodeferring} = 1;
  931.         }
  932.       } else {                  # nonconsecutive- erase and start over
  933.         @H = ($n, $n);
  934.         $self->_stop_autodeferring;
  935.       }
  936.     }
  937.   } else {                      # SPLICE or STORESIZE or some such
  938.     @H = ();
  939.     $self->_stop_autodeferring;
  940.   }
  941. }
  942.  
  943. # If autodferring was enabled, cut it out and discard the history
  944. sub _stop_autodeferring {
  945.   my $self = shift;
  946.   if ($self->{autodeferring}) {
  947.     $self->_flush;
  948.   }
  949.   $self->{autodeferring} = 0;
  950. }
  951.  
  952. ################################################################
  953.  
  954.  
  955. # This is NOT a method.  It is here for two reasons:
  956. #  1. To factor a fairly complicated block out of the constructor
  957. #  2. To provide access for the test suite, which need to be sure
  958. #     files are being written properly.
  959. sub _default_recsep {
  960.   my $recsep = $/;
  961.   if ($^O eq 'MSWin32') {       # Dos too?
  962.     # Windows users expect files to be terminated with \r\n
  963.     # But $/ is set to \n instead
  964.     # Note that this also transforms \n\n into \r\n\r\n.
  965.     # That is a feature.
  966.     $recsep =~ s/\n/\r\n/g;
  967.   }
  968.   $recsep;
  969. }
  970.  
  971. # Utility function for _check_integrity
  972. sub _ci_warn {
  973.   my $msg = shift;
  974.   $msg =~ s/\n/\\n/g;
  975.   $msg =~ s/\r/\\r/g;
  976.   print "# $msg\n";
  977. }
  978.  
  979. # Given a file, make sure the cache is consistent with the
  980. # file contents and the internal data structures are consistent with
  981. # each other.  Returns true if everything checks out, false if not
  982. #
  983. # The $file argument is no longer used.  It is retained for compatibility
  984. # with the existing test suite.
  985. sub _check_integrity {
  986.   my ($self, $file, $warn) = @_;
  987.   my $rsl = $self->{recseplen};
  988.   my $rs  = $self->{recsep};
  989.   my $good = 1; 
  990.   local *_;                     # local $_ does not work here
  991.   local $DIAGNOSTIC = 1;
  992.  
  993.   if (not defined $rs) {
  994.     _ci_warn("recsep is undef!");
  995.     $good = 0;
  996.   } elsif ($rs eq "") {
  997.     _ci_warn("recsep is empty!");
  998.     $good = 0;
  999.   } elsif ($rsl != length $rs) {
  1000.     my $ln = length $rs;
  1001.     _ci_warn("recsep <$rs> has length $ln, should be $rsl");
  1002.     $good = 0;
  1003.   }
  1004.  
  1005.   if (not defined $self->{offsets}[0]) {
  1006.     _ci_warn("offset 0 is missing!");
  1007.     $good = 0;
  1008.  
  1009.   } elsif ($self->{offsets}[0] != 0) {
  1010.     _ci_warn("rec 0: offset <$self->{offsets}[0]> s/b 0!");
  1011.     $good = 0;
  1012.   }
  1013.  
  1014.   my $cached = 0;
  1015.   {
  1016.     local *F = $self->{fh};
  1017.     seek F, 0, SEEK_SET;
  1018.     local $. = 0;
  1019.     local $/ = $rs;
  1020.  
  1021.     while (<F>) {
  1022.       my $n = $. - 1;
  1023.       my $cached = $self->{cache}->_produce($n);
  1024.       my $offset = $self->{offsets}[$.];
  1025.       my $ao = tell F;
  1026.       if (defined $offset && $offset != $ao) {
  1027.         _ci_warn("rec $n: offset <$offset> actual <$ao>");
  1028.         $good = 0;
  1029.       }
  1030.       if (defined $cached && $_ ne $cached && ! $self->{deferred}{$n}) {
  1031.         $good = 0;
  1032.         _ci_warn("rec $n: cached <$cached> actual <$_>");
  1033.       }
  1034.       if (defined $cached && substr($cached, -$rsl) ne $rs) {
  1035.         $good = 0;
  1036.         _ci_warn("rec $n in the cache is missing the record separator");
  1037.       }
  1038.       if (! defined $offset && $self->{eof}) {
  1039.         $good = 0;
  1040.         _ci_warn("The offset table was marked complete, but it is missing element $.");
  1041.       }
  1042.     }
  1043.     if (@{$self->{offsets}} > $.+1) {
  1044.         $good = 0;
  1045.         my $n = @{$self->{offsets}};
  1046.         _ci_warn("The offset table has $n items, but the file has only $.");
  1047.     }
  1048.  
  1049.     my $deferring = $self->_is_deferring;
  1050.     for my $n ($self->{cache}->ckeys) {
  1051.       my $r = $self->{cache}->_produce($n);
  1052.       $cached += length($r);
  1053.       next if $n+1 <= $.;         # checked this already
  1054.       _ci_warn("spurious caching of record $n");
  1055.       $good = 0;
  1056.     }
  1057.     my $b = $self->{cache}->bytes;
  1058.     if ($cached != $b) {
  1059.       _ci_warn("cache size is $b, should be $cached");
  1060.       $good = 0;
  1061.     }
  1062.   }
  1063.  
  1064.   # That cache has its own set of tests
  1065.   $good = 0 unless $self->{cache}->_check_integrity;
  1066.  
  1067.   # Now let's check the deferbuffer
  1068.   # Unless deferred writing is enabled, it should be empty
  1069.   if (! $self->_is_deferring && %{$self->{deferred}}) {
  1070.     _ci_warn("deferred writing disabled, but deferbuffer nonempty");
  1071.     $good = 0;
  1072.   }
  1073.  
  1074.   # Any record in the deferbuffer should *not* be present in the readcache
  1075.   my $deferred_s = 0;
  1076.   while (my ($n, $r) = each %{$self->{deferred}}) {
  1077.     $deferred_s += length($r);
  1078.     if (defined $self->{cache}->_produce($n)) {
  1079.       _ci_warn("record $n is in the deferbuffer *and* the readcache");
  1080.       $good = 0;
  1081.     }
  1082.     if (substr($r, -$rsl) ne $rs) {
  1083.       _ci_warn("rec $n in the deferbuffer is missing the record separator");
  1084.       $good = 0;
  1085.     }
  1086.   }
  1087.  
  1088.   # Total size of deferbuffer should match internal total
  1089.   if ($deferred_s != $self->{deferred_s}) {
  1090.     _ci_warn("buffer size is $self->{deferred_s}, should be $deferred_s");
  1091.     $good = 0;
  1092.   }
  1093.  
  1094.   # Total size of deferbuffer should not exceed the specified limit
  1095.   if ($deferred_s > $self->{dw_size}) {
  1096.     _ci_warn("buffer size is $self->{deferred_s} which exceeds the limit of $self->{dw_size}");
  1097.     $good = 0;
  1098.   }
  1099.  
  1100.   # Total size of cached data should not exceed the specified limit
  1101.   if ($deferred_s + $cached > $self->{memory}) {
  1102.     my $total = $deferred_s + $cached;
  1103.     _ci_warn("total stored data size is $total which exceeds the limit of $self->{memory}");
  1104.     $good = 0;
  1105.   }
  1106.  
  1107.   # Stuff related to autodeferment
  1108.   if (!$self->{autodefer} && @{$self->{ad_history}}) {
  1109.     _ci_warn("autodefer is disabled, but ad_history is nonempty");
  1110.     $good = 0;
  1111.   }
  1112.   if ($self->{autodeferring} && $self->{defer}) {
  1113.     _ci_warn("both autodeferring and explicit deferring are active");
  1114.     $good = 0;
  1115.   }
  1116.   if (@{$self->{ad_history}} == 0) {
  1117.     # That's OK, no additional tests required
  1118.   } elsif (@{$self->{ad_history}} == 2) {
  1119.     my @non_number = grep !/^-?\d+$/, @{$self->{ad_history}};
  1120.     if (@non_number) {
  1121.       my $msg;
  1122.       { local $" = ')(';
  1123.         $msg = "ad_history contains non-numbers (@{$self->{ad_history}})";
  1124.       }
  1125.       _ci_warn($msg);
  1126.       $good = 0;
  1127.     } elsif ($self->{ad_history}[1] < $self->{ad_history}[0]) {
  1128.       _ci_warn("ad_history has nonsensical values @{$self->{ad_history}}");
  1129.       $good = 0;
  1130.     }
  1131.   } else {
  1132.     _ci_warn("ad_history has bad length <@{$self->{ad_history}}>");
  1133.     $good = 0;
  1134.   }
  1135.  
  1136.   $good;
  1137. }
  1138.  
  1139. ################################################################
  1140. #
  1141. # Tie::File::Cache
  1142. #
  1143. # Read cache
  1144.  
  1145. package Tie::File::Cache;
  1146. $Tie::File::Cache::VERSION = $Tie::File::VERSION;
  1147. use Carp ':DEFAULT', 'confess';
  1148.  
  1149. sub HEAP () { 0 }
  1150. sub HASH () { 1 }
  1151. sub MAX  () { 2 }
  1152. sub BYTES() { 3 }
  1153. use strict 'vars';
  1154.  
  1155. sub new {
  1156.   my ($pack, $max) = @_;
  1157.   local *_;
  1158.   croak "missing argument to ->new" unless defined $max;
  1159.   my $self = [];
  1160.   bless $self => $pack;
  1161.   @$self = (Tie::File::Heap->new($self), {}, $max, 0);
  1162.   $self;
  1163. }
  1164.  
  1165. sub adj_limit {
  1166.   my ($self, $n) = @_;
  1167.   $self->[MAX] += $n;
  1168. }
  1169.  
  1170. sub set_limit {
  1171.   my ($self, $n) = @_;
  1172.   $self->[MAX] = $n;
  1173. }
  1174.  
  1175. # For internal use only
  1176. # Will be called by the heap structure to notify us that a certain 
  1177. # piece of data has moved from one heap element to another.
  1178. # $k is the hash key of the item
  1179. # $n is the new index into the heap at which it is stored
  1180. # If $n is undefined, the item has been removed from the heap.
  1181. sub _heap_move {
  1182.   my ($self, $k, $n) = @_;
  1183.   if (defined $n) {
  1184.     $self->[HASH]{$k} = $n;
  1185.   } else {
  1186.     delete $self->[HASH]{$k}; 
  1187.   }
  1188. }
  1189.  
  1190. sub insert {
  1191.   my ($self, $key, $val) = @_;
  1192.   local *_;
  1193.   croak "missing argument to ->insert" unless defined $key;
  1194.   unless (defined $self->[MAX]) {
  1195.     confess "undefined max" ;
  1196.   }
  1197.   confess "undefined val" unless defined $val;
  1198.   return if length($val) > $self->[MAX];
  1199.   my $oldnode = $self->[HASH]{$key};
  1200.   if (defined $oldnode) {
  1201.     my $oldval = $self->[HEAP]->set_val($oldnode, $val);
  1202.     $self->[BYTES] -= length($oldval);
  1203.   } else {
  1204.     $self->[HEAP]->insert($key, $val);
  1205.   }
  1206.   $self->[BYTES] += length($val);
  1207.   $self->flush;
  1208. }
  1209.  
  1210. sub expire {
  1211.   my $self = shift;
  1212.   my $old_data = $self->[HEAP]->popheap;
  1213.   return unless defined $old_data;
  1214.   $self->[BYTES] -= length $old_data;
  1215.   $old_data;
  1216. }
  1217.  
  1218. sub remove {
  1219.   my ($self, @keys) = @_;
  1220.   my @result;
  1221.   for my $key (@keys) {
  1222.     next unless exists $self->[HASH]{$key};
  1223.     my $old_data = $self->[HEAP]->remove($self->[HASH]{$key});
  1224.     $self->[BYTES] -= length $old_data;
  1225.     push @result, $old_data;
  1226.   }
  1227.   @result;
  1228. }
  1229.  
  1230. sub lookup {
  1231.   my ($self, $key) = @_;
  1232.   local *_;
  1233.   croak "missing argument to ->lookup" unless defined $key;
  1234.   if (exists $self->[HASH]{$key}) {
  1235.     $self->[HEAP]->lookup($self->[HASH]{$key});
  1236.   } else {
  1237.     return;
  1238.   }
  1239. }
  1240.  
  1241. # For internal use only
  1242. sub _produce {
  1243.   my ($self, $key) = @_;
  1244.   my $loc = $self->[HASH]{$key};
  1245.   return unless defined $loc;
  1246.   $self->[HEAP][$loc][2];
  1247. }
  1248.  
  1249. # For internal use only
  1250. sub _promote {
  1251.   my ($self, $key) = @_;
  1252.   $self->[HEAP]->promote($self->[HASH]{$key});
  1253. }
  1254.  
  1255. sub empty {
  1256.   my ($self) = @_;
  1257.   %{$self->[HASH]} = ();
  1258.     $self->[BYTES] = 0;
  1259.     $self->[HEAP]->empty;
  1260. }
  1261.  
  1262. sub is_empty {
  1263.   my ($self) = @_;
  1264.   keys %{$self->[HASH]} == 0;
  1265. }
  1266.  
  1267. sub update {
  1268.   my ($self, $key, $val) = @_;
  1269.   local *_;
  1270.   croak "missing argument to ->update" unless defined $key;
  1271.   if (length($val) > $self->[MAX]) {
  1272.     my $oldval = $self->remove($key);
  1273.     $self->[BYTES] -= length($oldval) if defined $oldval;
  1274.   } elsif (exists $self->[HASH]{$key}) {
  1275.     my $oldval = $self->[HEAP]->set_val($self->[HASH]{$key}, $val);
  1276.     $self->[BYTES] += length($val);
  1277.     $self->[BYTES] -= length($oldval) if defined $oldval;
  1278.   } else {
  1279.     $self->[HEAP]->insert($key, $val);
  1280.     $self->[BYTES] += length($val);
  1281.   }
  1282.   $self->flush;
  1283. }
  1284.  
  1285. sub rekey {
  1286.   my ($self, $okeys, $nkeys) = @_;
  1287.   local *_;
  1288.   my %map;
  1289.   @map{@$okeys} = @$nkeys;
  1290.   croak "missing argument to ->rekey" unless defined $nkeys;
  1291.   croak "length mismatch in ->rekey arguments" unless @$nkeys == @$okeys;
  1292.   my %adjusted;                 # map new keys to heap indices
  1293.   # You should be able to cut this to one loop TODO XXX
  1294.   for (0 .. $#$okeys) {
  1295.     $adjusted{$nkeys->[$_]} = delete $self->[HASH]{$okeys->[$_]};
  1296.   }
  1297.   while (my ($nk, $ix) = each %adjusted) {
  1298.     # @{$self->[HASH]}{keys %adjusted} = values %adjusted;
  1299.     $self->[HEAP]->rekey($ix, $nk);
  1300.     $self->[HASH]{$nk} = $ix;
  1301.   }
  1302. }
  1303.  
  1304. sub ckeys {
  1305.   my $self = shift;
  1306.   my @a = keys %{$self->[HASH]};
  1307.   @a;
  1308. }
  1309.  
  1310. sub bytes {
  1311.   my $self = shift;
  1312.   $self->[BYTES];
  1313. }
  1314.  
  1315. sub reduce_size_to {
  1316.   my ($self, $max) = @_;
  1317.   until ($self->is_empty || $self->[BYTES] <= $max) {
  1318.     $self->expire;
  1319.   }
  1320. }
  1321.  
  1322. sub flush {
  1323.   my $self = shift;
  1324.   until ($self->is_empty || $self->[BYTES] <= $self->[MAX]) {
  1325.     $self->expire;
  1326.   }
  1327. }
  1328.  
  1329. # For internal use only
  1330. sub _produce_lru {
  1331.   my $self = shift;
  1332.   $self->[HEAP]->expire_order;
  1333. }
  1334.  
  1335. BEGIN { *_ci_warn = \&Tie::File::_ci_warn }
  1336.  
  1337. sub _check_integrity {          # For CACHE
  1338.   my $self = shift;
  1339.   my $good = 1;
  1340.  
  1341.   # Test HEAP
  1342.   $self->[HEAP]->_check_integrity or $good = 0;
  1343.  
  1344.   # Test HASH
  1345.   my $bytes = 0;
  1346.   for my $k (keys %{$self->[HASH]}) {
  1347.     if ($k ne '0' && $k !~ /^[1-9][0-9]*$/) {
  1348.       $good = 0;
  1349.       _ci_warn "Cache hash key <$k> is non-numeric";
  1350.     }
  1351.  
  1352.     my $h = $self->[HASH]{$k};
  1353.     if (! defined $h) {
  1354.       $good = 0;
  1355.       _ci_warn "Heap index number for key $k is undefined";
  1356.     } elsif ($h == 0) {
  1357.       $good = 0;
  1358.       _ci_warn "Heap index number for key $k is zero";
  1359.     } else {
  1360.       my $j = $self->[HEAP][$h];
  1361.       if (! defined $j) {
  1362.         $good = 0;
  1363.         _ci_warn "Heap contents key $k (=> $h) are undefined";
  1364.       } else {
  1365.         $bytes += length($j->[2]);
  1366.         if ($k ne $j->[1]) {
  1367.           $good = 0;
  1368.           _ci_warn "Heap contents key $k (=> $h) is $j->[1], should be $k";
  1369.         }
  1370.       }
  1371.     }
  1372.   }
  1373.  
  1374.   # Test BYTES
  1375.   if ($bytes != $self->[BYTES]) {
  1376.     $good = 0;
  1377.     _ci_warn "Total data in cache is $bytes, expected $self->[BYTES]";
  1378.   }
  1379.  
  1380.   # Test MAX
  1381.   if ($bytes > $self->[MAX]) {
  1382.     $good = 0;
  1383.     _ci_warn "Total data in cache is $bytes, exceeds maximum $self->[MAX]";
  1384.   }
  1385.  
  1386.   return $good;
  1387. }
  1388.  
  1389. sub delink {
  1390.   my $self = shift;
  1391.   $self->[HEAP] = undef;        # Bye bye heap
  1392. }
  1393.  
  1394. ################################################################
  1395. #
  1396. # Tie::File::Heap
  1397. #
  1398. # Heap data structure for use by cache LRU routines
  1399.  
  1400. package Tie::File::Heap;
  1401. use Carp ':DEFAULT', 'confess';
  1402. $Tie::File::Heap::VERSION = $Tie::File::Cache::VERSION;
  1403. sub SEQ () { 0 };
  1404. sub KEY () { 1 };
  1405. sub DAT () { 2 };
  1406.  
  1407. sub new {
  1408.   my ($pack, $cache) = @_;
  1409.   die "$pack: Parent cache object $cache does not support _heap_move method"
  1410.     unless eval { $cache->can('_heap_move') };
  1411.   my $self = [[0,$cache,0]];
  1412.   bless $self => $pack;
  1413. }
  1414.  
  1415. # Allocate a new sequence number, larger than all previously allocated numbers
  1416. sub _nseq {
  1417.   my $self = shift;
  1418.   $self->[0][0]++;
  1419. }
  1420.  
  1421. sub _cache {
  1422.   my $self = shift;
  1423.   $self->[0][1];
  1424. }
  1425.  
  1426. sub _nelts {
  1427.   my $self = shift;
  1428.   $self->[0][2];
  1429. }
  1430.  
  1431. sub _nelts_inc {
  1432.   my $self = shift;
  1433.   ++$self->[0][2];
  1434. }  
  1435.  
  1436. sub _nelts_dec {
  1437.   my $self = shift;
  1438.   --$self->[0][2];
  1439. }  
  1440.  
  1441. sub is_empty {
  1442.   my $self = shift;
  1443.   $self->_nelts == 0;
  1444. }
  1445.  
  1446. sub empty {
  1447.   my $self = shift;
  1448.   $#$self = 0;
  1449.   $self->[0][2] = 0;
  1450.   $self->[0][0] = 0;            # might as well reset the sequence numbers
  1451. }
  1452.  
  1453. # notify the parent cache object that we moved something
  1454. sub _heap_move {
  1455.   my $self = shift;
  1456.   $self->_cache->_heap_move(@_);
  1457. }
  1458.  
  1459. # Insert a piece of data into the heap with the indicated sequence number.
  1460. # The item with the smallest sequence number is always at the top.
  1461. # If no sequence number is specified, allocate a new one and insert the
  1462. # item at the bottom.
  1463. sub insert {
  1464.   my ($self, $key, $data, $seq) = @_;
  1465.   $seq = $self->_nseq unless defined $seq;
  1466.   $self->_insert_new([$seq, $key, $data]);
  1467. }
  1468.  
  1469. # Insert a new, fresh item at the bottom of the heap
  1470. sub _insert_new {
  1471.   my ($self, $item) = @_;
  1472.   my $i = @$self;
  1473.   $i = int($i/2) until defined $self->[$i/2];
  1474.   $self->[$i] = $item;
  1475.   $self->[0][1]->_heap_move($self->[$i][KEY], $i);
  1476.   $self->_nelts_inc;
  1477. }
  1478.  
  1479. # Insert [$data, $seq] pair at or below item $i in the heap.
  1480. # If $i is omitted, default to 1 (the top element.)
  1481. sub _insert {
  1482.   my ($self, $item, $i) = @_;
  1483. #  $self->_check_loc($i) if defined $i;
  1484.   $i = 1 unless defined $i;
  1485.   until (! defined $self->[$i]) {
  1486.     if ($self->[$i][SEQ] > $item->[SEQ]) { # inserted item is older
  1487.       ($self->[$i], $item) = ($item, $self->[$i]);
  1488.       $self->[0][1]->_heap_move($self->[$i][KEY], $i);
  1489.     }
  1490.     # If either is undefined, go that way.  Otherwise, choose at random
  1491.     my $dir;
  1492.     $dir = 0 if !defined $self->[2*$i];
  1493.     $dir = 1 if !defined $self->[2*$i+1];
  1494.     $dir = int(rand(2)) unless defined $dir;
  1495.     $i = 2*$i + $dir;
  1496.   }
  1497.   $self->[$i] = $item;
  1498.   $self->[0][1]->_heap_move($self->[$i][KEY], $i);
  1499.   $self->_nelts_inc;
  1500. }
  1501.  
  1502. # Remove the item at node $i from the heap, moving child items upwards.
  1503. # The item with the smallest sequence number is always at the top.
  1504. # Moving items upwards maintains this condition.
  1505. # Return the removed item.
  1506. sub remove {
  1507.   my ($self, $i) = @_;
  1508.   $i = 1 unless defined $i;
  1509.   my $top = $self->[$i];
  1510.   return unless defined $top;
  1511.   while (1) {
  1512.     my $ii;
  1513.     my ($L, $R) = (2*$i, 2*$i+1);
  1514.  
  1515.     # If either is undefined, go the other way.
  1516.     # Otherwise, go towards the smallest.
  1517.     last unless defined $self->[$L] || defined $self->[$R];
  1518.     $ii = $R if not defined $self->[$L];
  1519.     $ii = $L if not defined $self->[$R];
  1520.     unless (defined $ii) {
  1521.       $ii = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
  1522.     }
  1523.  
  1524.     $self->[$i] = $self->[$ii]; # Promote child to fill vacated spot
  1525.     $self->[0][1]->_heap_move($self->[$i][KEY], $i);
  1526.     $i = $ii; # Fill new vacated spot
  1527.   }
  1528.   $self->[0][1]->_heap_move($top->[KEY], undef);
  1529.   undef $self->[$i];
  1530.   $self->_nelts_dec;
  1531.   return $top->[DAT];
  1532. }
  1533.  
  1534. sub popheap {
  1535.   my $self = shift;
  1536.   $self->remove(1);
  1537. }
  1538.  
  1539. # set the sequence number of the indicated item to a higher number
  1540. # than any other item in the heap, and bubble the item down to the
  1541. # bottom.
  1542. sub promote {
  1543.   my ($self, $n) = @_;
  1544. #  $self->_check_loc($n);
  1545.   $self->[$n][SEQ] = $self->_nseq;
  1546.   my $i = $n;
  1547.   while (1) {
  1548.     my ($L, $R) = (2*$i, 2*$i+1);
  1549.     my $dir;
  1550.     last unless defined $self->[$L] || defined $self->[$R];
  1551.     $dir = $R unless defined $self->[$L];
  1552.     $dir = $L unless defined $self->[$R];
  1553.     unless (defined $dir) {
  1554.       $dir = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R;
  1555.     }
  1556.     @{$self}[$i, $dir] = @{$self}[$dir, $i];
  1557.     for ($i, $dir) {
  1558.       $self->[0][1]->_heap_move($self->[$_][KEY], $_) if defined $self->[$_];
  1559.     }
  1560.     $i = $dir;
  1561.   }
  1562. }
  1563.  
  1564. # Return item $n from the heap, promoting its LRU status
  1565. sub lookup {
  1566.   my ($self, $n) = @_;
  1567. #  $self->_check_loc($n);
  1568.   my $val = $self->[$n];
  1569.   $self->promote($n);
  1570.   $val->[DAT];
  1571. }
  1572.  
  1573.  
  1574. # Assign a new value for node $n, promoting it to the bottom of the heap
  1575. sub set_val {
  1576.   my ($self, $n, $val) = @_;
  1577. #  $self->_check_loc($n);
  1578.   my $oval = $self->[$n][DAT];
  1579.   $self->[$n][DAT] = $val;
  1580.   $self->promote($n);
  1581.   return $oval;
  1582. }
  1583.  
  1584. # The hask key has changed for an item;
  1585. # alter the heap's record of the hash key
  1586. sub rekey {
  1587.   my ($self, $n, $new_key) = @_;
  1588. #  $self->_check_loc($n);
  1589.   $self->[$n][KEY] = $new_key;
  1590. }
  1591.  
  1592. sub _check_loc {
  1593.   my ($self, $n) = @_;
  1594.   unless (1 || defined $self->[$n]) {
  1595.     confess "_check_loc($n) failed";
  1596.   }
  1597. }
  1598.  
  1599. BEGIN { *_ci_warn = \&Tie::File::_ci_warn }
  1600.  
  1601. sub _check_integrity {
  1602.   my $self = shift;
  1603.   my $good = 1;
  1604.   my %seq;
  1605.  
  1606.   unless (eval {$self->[0][1]->isa("Tie::File::Cache")}) {
  1607.     _ci_warn "Element 0 of heap corrupt";
  1608.     $good = 0;
  1609.   }
  1610.   $good = 0 unless $self->_satisfies_heap_condition(1);
  1611.   for my $i (2 .. $#{$self}) {
  1612.     my $p = int($i/2);          # index of parent node
  1613.     if (defined $self->[$i] && ! defined $self->[$p]) {
  1614.       _ci_warn "Element $i of heap defined, but parent $p isn't";
  1615.       $good = 0;
  1616.     }
  1617.  
  1618.     if (defined $self->[$i]) {
  1619.       if ($seq{$self->[$i][SEQ]}) {
  1620.         my $seq = $self->[$i][SEQ];
  1621.         _ci_warn "Nodes $i and $seq{$seq} both have SEQ=$seq";
  1622.         $good = 0;
  1623.       } else {
  1624.         $seq{$self->[$i][SEQ]} = $i;
  1625.       }
  1626.     }
  1627.   }
  1628.  
  1629.   return $good;
  1630. }
  1631.  
  1632. sub _satisfies_heap_condition {
  1633.   my $self = shift;
  1634.   my $n = shift || 1;
  1635.   my $good = 1;
  1636.   for (0, 1) {
  1637.     my $c = $n*2 + $_;
  1638.     next unless defined $self->[$c];
  1639.     if ($self->[$n][SEQ] >= $self->[$c]) {
  1640.       _ci_warn "Node $n of heap does not predate node $c";
  1641.       $good = 0 ;
  1642.     }
  1643.     $good = 0 unless $self->_satisfies_heap_condition($c);
  1644.   }
  1645.   return $good;
  1646. }
  1647.  
  1648. # Return a list of all the values, sorted by expiration order
  1649. sub expire_order {
  1650.   my $self = shift;
  1651.   my @nodes = sort {$a->[SEQ] <=> $b->[SEQ]} $self->_nodes;
  1652.   map { $_->[KEY] } @nodes;
  1653. }
  1654.  
  1655. sub _nodes {
  1656.   my $self = shift;
  1657.   my $i = shift || 1;
  1658.   return unless defined $self->[$i];
  1659.   ($self->[$i], $self->_nodes($i*2), $self->_nodes($i*2+1));
  1660. }
  1661.  
  1662. "Cogito, ergo sum.";  # don't forget to return a true value from the file
  1663.  
  1664. =head1 NAME
  1665.  
  1666. Tie::File - Access the lines of a disk file via a Perl array
  1667.  
  1668. =head1 SYNOPSIS
  1669.  
  1670.     # This file documents Tie::File version 0.93
  1671.  
  1672.     tie @array, 'Tie::File', filename or die ...;
  1673.  
  1674.     $array[13] = 'blah';     # line 13 of the file is now 'blah'
  1675.     print $array[42];        # display line 42 of the file
  1676.  
  1677.     $n_recs = @array;        # how many records are in the file?
  1678.     $#array -= 2;            # chop two records off the end
  1679.  
  1680.  
  1681.     for (@array) {
  1682.       s/PERL/Perl/g;         # Replace PERL with Perl everywhere in the file
  1683.     }
  1684.  
  1685.     # These are just like regular push, pop, unshift, shift, and splice
  1686.     # Except that they modify the file in the way you would expect
  1687.  
  1688.     push @array, new recs...;
  1689.     my $r1 = pop @array;
  1690.     unshift @array, new recs...;
  1691.     my $r1 = shift @array;
  1692.     @old_recs = splice @array, 3, 7, new recs...;
  1693.  
  1694.     untie @array;            # all finished
  1695.  
  1696.  
  1697. =head1 DESCRIPTION
  1698.  
  1699. C<Tie::File> represents a regular text file as a Perl array.  Each
  1700. element in the array corresponds to a record in the file.  The first
  1701. line of the file is element 0 of the array; the second line is element
  1702. 1, and so on.
  1703.  
  1704. The file is I<not> loaded into memory, so this will work even for
  1705. gigantic files.
  1706.  
  1707. Changes to the array are reflected in the file immediately.
  1708.  
  1709. Lazy people and beginners may now stop reading the manual.
  1710.  
  1711. =head2 C<recsep>
  1712.  
  1713. What is a 'record'?  By default, the meaning is the same as for the
  1714. C<E<lt>...E<gt>> operator: It's a string terminated by C<$/>, which is
  1715. probably C<"\n">.  (Minor exception: on dos and Win32 systems, a
  1716. 'record' is a string terminated by C<"\r\n">.)  You may change the
  1717. definition of "record" by supplying the C<recsep> option in the C<tie>
  1718. call:
  1719.  
  1720.     tie @array, 'Tie::File', $file, recsep => 'es';
  1721.  
  1722. This says that records are delimited by the string C<es>.  If the file
  1723. contained the following data:
  1724.  
  1725.     Curse these pesky flies!\n
  1726.  
  1727. then the C<@array> would appear to have four elements:
  1728.  
  1729.     "Curse th"
  1730.     "e p"
  1731.     "ky fli"
  1732.     "!\n"
  1733.  
  1734. An undefined value is not permitted as a record separator.  Perl's
  1735. special "paragraph mode" semantics (E<agrave> la C<$/ = "">) are not
  1736. emulated.
  1737.  
  1738. Records read from the tied array do not have the record separator
  1739. string on the end; this is to allow
  1740.  
  1741.     $array[17] .= "extra";
  1742.  
  1743. to work as expected.
  1744.  
  1745. (See L<"autochomp">, below.)  Records stored into the array will have
  1746. the record separator string appended before they are written to the
  1747. file, if they don't have one already.  For example, if the record
  1748. separator string is C<"\n">, then the following two lines do exactly
  1749. the same thing:
  1750.  
  1751.     $array[17] = "Cherry pie";
  1752.     $array[17] = "Cherry pie\n";
  1753.  
  1754. The result is that the contents of line 17 of the file will be
  1755. replaced with "Cherry pie"; a newline character will separate line 17
  1756. from line 18.  This means that this code will do nothing:
  1757.  
  1758.     chomp $array[17];
  1759.  
  1760. Because the C<chomp>ed value will have the separator reattached when
  1761. it is written back to the file.  There is no way to create a file
  1762. whose trailing record separator string is missing.
  1763.  
  1764. Inserting records that I<contain> the record separator string is not
  1765. supported by this module.  It will probably produce a reasonable
  1766. result, but what this result will be may change in a future version.
  1767. Use 'splice' to insert records or to replace one record with several.
  1768.  
  1769. =head2 C<autochomp>
  1770.  
  1771. Normally, array elements have the record separator removed, so that if
  1772. the file contains the text
  1773.  
  1774.     Gold
  1775.     Frankincense
  1776.     Myrrh
  1777.  
  1778. the tied array will appear to contain C<("Gold", "Frankincense",
  1779. "Myrrh")>.  If you set C<autochomp> to a false value, the record
  1780. separator will not be removed.  If the file above was tied with
  1781.  
  1782.     tie @gifts, "Tie::File", $gifts, autochomp => 0;
  1783.  
  1784. then the array C<@gifts> would appear to contain C<("Gold\n",
  1785. "Frankincense\n", "Myrrh\n")>, or (on Win32 systems) C<("Gold\r\n",
  1786. "Frankincense\r\n", "Myrrh\r\n")>.
  1787.  
  1788. =head2 C<mode>
  1789.  
  1790. Normally, the specified file will be opened for read and write access,
  1791. and will be created if it does not exist.  (That is, the flags
  1792. C<O_RDWR | O_CREAT> are supplied in the C<open> call.)  If you want to
  1793. change this, you may supply alternative flags in the C<mode> option.
  1794. See L<Fcntl> for a listing of available flags.
  1795. For example:
  1796.  
  1797.     # open the file if it exists, but fail if it does not exist
  1798.     use Fcntl 'O_RDWR';
  1799.     tie @array, 'Tie::File', $file, mode => O_RDWR;
  1800.  
  1801.     # create the file if it does not exist
  1802.     use Fcntl 'O_RDWR', 'O_CREAT';
  1803.     tie @array, 'Tie::File', $file, mode => O_RDWR | O_CREAT;
  1804.  
  1805.     # open an existing file in read-only mode
  1806.     use Fcntl 'O_RDONLY';
  1807.     tie @array, 'Tie::File', $file, mode => O_RDONLY;
  1808.  
  1809. Opening the data file in write-only or append mode is not supported.
  1810.  
  1811. =head2 C<memory>
  1812.  
  1813. This is an upper limit on the amount of memory that C<Tie::File> will
  1814. consume at any time while managing the file.  This is used for two
  1815. things: managing the I<read cache> and managing the I<deferred write
  1816. buffer>.
  1817.  
  1818. Records read in from the file are cached, to avoid having to re-read
  1819. them repeatedly.  If you read the same record twice, the first time it
  1820. will be stored in memory, and the second time it will be fetched from
  1821. the I<read cache>.  The amount of data in the read cache will not
  1822. exceed the value you specified for C<memory>.  If C<Tie::File> wants
  1823. to cache a new record, but the read cache is full, it will make room
  1824. by expiring the least-recently visited records from the read cache.
  1825.  
  1826. The default memory limit is 2Mib.  You can adjust the maximum read
  1827. cache size by supplying the C<memory> option.  The argument is the
  1828. desired cache size, in bytes.
  1829.  
  1830.     # I have a lot of memory, so use a large cache to speed up access
  1831.     tie @array, 'Tie::File', $file, memory => 20_000_000;
  1832.  
  1833. Setting the memory limit to 0 will inhibit caching; records will be
  1834. fetched from disk every time you examine them.
  1835.  
  1836. The C<memory> value is not an absolute or exact limit on the memory
  1837. used.  C<Tie::File> objects contains some structures besides the read
  1838. cache and the deferred write buffer, whose sizes are not charged
  1839. against C<memory>.
  1840.  
  1841. =head2 C<dw_size>
  1842.  
  1843. (This is an advanced feature.  Skip this section on first reading.)
  1844.  
  1845. If you use deferred writing (See L<"Deferred Writing">, below) then
  1846. data you write into the array will not be written directly to the
  1847. file; instead, it will be saved in the I<deferred write buffer> to be
  1848. written out later.  Data in the deferred write buffer is also charged
  1849. against the memory limit you set with the C<memory> option.
  1850.  
  1851. You may set the C<dw_size> option to limit the amount of data that can
  1852. be saved in the deferred write buffer.  This limit may not exceed the
  1853. total memory limit.  For example, if you set C<dw_size> to 1000 and
  1854. C<memory> to 2500, that means that no more than 1000 bytes of deferred
  1855. writes will be saved up.  The space available for the read cache will
  1856. vary, but it will always be at least 1500 bytes (if the deferred write
  1857. buffer is full) and it could grow as large as 2500 bytes (if the
  1858. deferred write buffer is empty.)
  1859.  
  1860. If you don't specify a C<dw_size>, it defaults to the entire memory
  1861. limit.
  1862.  
  1863. =head2 Option Format
  1864.  
  1865. C<-mode> is a synonym for C<mode>.  C<-recsep> is a synonym for
  1866. C<recsep>.  C<-memory> is a synonym for C<memory>.  You get the
  1867. idea.
  1868.  
  1869. =head1 Public Methods
  1870.  
  1871. The C<tie> call returns an object, say C<$o>.  You may call
  1872.  
  1873.     $rec = $o->FETCH($n);
  1874.     $o->STORE($n, $rec);
  1875.  
  1876. to fetch or store the record at line C<$n>, respectively; similarly
  1877. the other tied array methods.  (See L<perltie> for details.)  You may
  1878. also call the following methods on this object:
  1879.  
  1880. =head2 C<flock>
  1881.  
  1882.     $o->flock(MODE)
  1883.  
  1884. will lock the tied file.  C<MODE> has the same meaning as the second
  1885. argument to the Perl built-in C<flock> function; for example
  1886. C<LOCK_SH> or C<LOCK_EX | LOCK_NB>.  (These constants are provided by
  1887. the C<use Fcntl ':flock'> declaration.)
  1888.  
  1889. C<MODE> is optional; the default is C<LOCK_EX>.
  1890.  
  1891. C<Tie::File> promises that the following sequence of operations will
  1892. be safe:
  1893.  
  1894.     my $o = tie @array, "Tie::File", $filename;
  1895.     $o->flock;
  1896.  
  1897. In particular, C<Tie::File> will I<not> read or write the file during
  1898. the C<tie> call.  (Exception: Using C<mode =E<gt> O_TRUNC> will, of
  1899. course, erase the file during the C<tie> call.  If you want to do this
  1900. safely, then open the file without C<O_TRUNC>, lock the file, and use
  1901. C<@array = ()>.)
  1902.  
  1903. The best way to unlock a file is to discard the object and untie the
  1904. array.  It is probably unsafe to unlock the file without also untying
  1905. it, because if you do, changes may remain unwritten inside the object.
  1906. That is why there is no shortcut for unlocking.  If you really want to
  1907. unlock the file prematurely, you know what to do; if you don't know
  1908. what to do, then don't do it.
  1909.  
  1910. All the usual warnings about file locking apply here.  In particular,
  1911. note that file locking in Perl is B<advisory>, which means that
  1912. holding a lock will not prevent anyone else from reading, writing, or
  1913. erasing the file; it only prevents them from getting another lock at
  1914. the same time.  Locks are analogous to green traffic lights: If you
  1915. have a green light, that does not prevent the idiot coming the other
  1916. way from plowing into you sideways; it merely guarantees to you that
  1917. the idiot does not also have a green light at the same time.
  1918.  
  1919. =head2 C<autochomp>
  1920.  
  1921.     my $old_value = $o->autochomp(0);    # disable autochomp option
  1922.     my $old_value = $o->autochomp(1);    #  enable autochomp option
  1923.  
  1924.     my $ac = $o->autochomp();   # recover current value
  1925.  
  1926. See L<"autochomp">, above.
  1927.  
  1928. =head2 C<defer>, C<flush>, C<discard>, and C<autodefer>
  1929.  
  1930. See L<"Deferred Writing">, below.
  1931.  
  1932. =head1 Tying to an already-opened filehandle
  1933.  
  1934. If C<$fh> is a filehandle, such as is returned by C<IO::File> or one
  1935. of the other C<IO> modules, you may use:
  1936.  
  1937.     tie @array, 'Tie::File', $fh, ...;
  1938.  
  1939. Similarly if you opened that handle C<FH> with regular C<open> or
  1940. C<sysopen>, you may use:
  1941.  
  1942.     tie @array, 'Tie::File', \*FH, ...;
  1943.  
  1944. Handles that were opened write-only won't work.  Handles that were
  1945. opened read-only will work as long as you don't try to modify the
  1946. array.  Handles must be attached to seekable sources of data---that
  1947. means no pipes or sockets.  If C<Tie::File> can detect that you
  1948. supplied a non-seekable handle, the C<tie> call will throw an
  1949. exception.  (On Unix systems, it can detect this.)
  1950.  
  1951. =head1 Deferred Writing
  1952.  
  1953. (This is an advanced feature.  Skip this section on first reading.)
  1954.  
  1955. Normally, modifying a C<Tie::File> array writes to the underlying file
  1956. immediately.  Every assignment like C<$a[3] = ...> rewrites as much of
  1957. the file as is necessary; typically, everything from line 3 through
  1958. the end will need to be rewritten.  This is the simplest and most
  1959. transparent behavior.  Performance even for large files is reasonably
  1960. good.
  1961.  
  1962. However, under some circumstances, this behavior may be excessively
  1963. slow.  For example, suppose you have a million-record file, and you
  1964. want to do:
  1965.  
  1966.     for (@FILE) {
  1967.       $_ = "> $_";
  1968.     }
  1969.  
  1970. The first time through the loop, you will rewrite the entire file,
  1971. from line 0 through the end.  The second time through the loop, you
  1972. will rewrite the entire file from line 1 through the end.  The third
  1973. time through the loop, you will rewrite the entire file from line 2 to
  1974. the end.  And so on.
  1975.  
  1976. If the performance in such cases is unacceptable, you may defer the
  1977. actual writing, and then have it done all at once.  The following loop
  1978. will perform much better for large files:
  1979.  
  1980.     (tied @a)->defer;
  1981.     for (@a) {
  1982.       $_ = "> $_";
  1983.     }
  1984.     (tied @a)->flush;
  1985.  
  1986. If C<Tie::File>'s memory limit is large enough, all the writing will
  1987. done in memory.  Then, when you call C<-E<gt>flush>, the entire file
  1988. will be rewritten in a single pass.
  1989.  
  1990. (Actually, the preceding discussion is something of a fib.  You don't
  1991. need to enable deferred writing to get good performance for this
  1992. common case, because C<Tie::File> will do it for you automatically
  1993. unless you specifically tell it not to.  See L<"autodeferring">,
  1994. below.)
  1995.  
  1996. Calling C<-E<gt>flush> returns the array to immediate-write mode.  If
  1997. you wish to discard the deferred writes, you may call C<-E<gt>discard>
  1998. instead of C<-E<gt>flush>.  Note that in some cases, some of the data
  1999. will have been written already, and it will be too late for
  2000. C<-E<gt>discard> to discard all the changes.  Support for
  2001. C<-E<gt>discard> may be withdrawn in a future version of C<Tie::File>.
  2002.  
  2003. Deferred writes are cached in memory up to the limit specified by the
  2004. C<dw_size> option (see above).  If the deferred-write buffer is full
  2005. and you try to write still more deferred data, the buffer will be
  2006. flushed.  All buffered data will be written immediately, the buffer
  2007. will be emptied, and the now-empty space will be used for future
  2008. deferred writes.
  2009.  
  2010. If the deferred-write buffer isn't yet full, but the total size of the
  2011. buffer and the read cache would exceed the C<memory> limit, the oldest
  2012. records will be expired from the read cache until the total size is
  2013. under the limit.
  2014.  
  2015. C<push>, C<pop>, C<shift>, C<unshift>, and C<splice> cannot be
  2016. deferred.  When you perform one of these operations, any deferred data
  2017. is written to the file and the operation is performed immediately.
  2018. This may change in a future version.
  2019.  
  2020. If you resize the array with deferred writing enabled, the file will
  2021. be resized immediately, but deferred records will not be written.
  2022. This has a surprising consequence: C<@a = (...)> erases the file
  2023. immediately, but the writing of the actual data is deferred.  This
  2024. might be a bug.  If it is a bug, it will be fixed in a future version.
  2025.  
  2026. =head2 Autodeferring
  2027.  
  2028. C<Tie::File> tries to guess when deferred writing might be helpful,
  2029. and to turn it on and off automatically. 
  2030.  
  2031.     for (@a) {
  2032.       $_ = "> $_";
  2033.     }
  2034.  
  2035. In this example, only the first two assignments will be done
  2036. immediately; after this, all the changes to the file will be deferred
  2037. up to the user-specified memory limit.
  2038.  
  2039. You should usually be able to ignore this and just use the module
  2040. without thinking about deferring.  However, special applications may
  2041. require fine control over which writes are deferred, or may require
  2042. that all writes be immediate.  To disable the autodeferment feature,
  2043. use
  2044.  
  2045.     (tied @o)->autodefer(0);
  2046.  
  2047. or
  2048.  
  2049.            tie @array, 'Tie::File', $file, autodefer => 0;
  2050.  
  2051.  
  2052. Similarly, C<-E<gt>autodefer(1)> re-enables autodeferment, and 
  2053. C<-E<gt>autodefer()> recovers the current value of the autodefer setting.
  2054.  
  2055. =head1 CAVEATS
  2056.  
  2057. (That's Latin for 'warnings'.)
  2058.  
  2059. =over 4
  2060.  
  2061. =item *
  2062.  
  2063. This is BETA RELEASE SOFTWARE.  It may have bugs.  See the discussion
  2064. below about the (lack of any) warranty.
  2065.  
  2066. In particular, this means that the interface may change in
  2067. incompatible ways from one version to the next, without warning.  That
  2068. has happened at least once already.  The interface will freeze before
  2069. Perl 5.8 is released, probably sometime in April 2002.
  2070.  
  2071. =item *
  2072.  
  2073. Reasonable effort was made to make this module efficient.  Nevertheless,
  2074. changing the size of a record in the middle of a large file will
  2075. always be fairly slow, because everything after the new record must be
  2076. moved.
  2077.  
  2078. =item *
  2079.  
  2080. The behavior of tied arrays is not precisely the same as for regular
  2081. arrays.  For example:
  2082.  
  2083.     # This DOES print "How unusual!"
  2084.     undef $a[10];  print "How unusual!\n" if defined $a[10];
  2085.  
  2086. C<undef>-ing a C<Tie::File> array element just blanks out the
  2087. corresponding record in the file.  When you read it back again, you'll
  2088. get the empty string, so the supposedly-C<undef>'ed value will be
  2089. defined.  Similarly, if you have C<autochomp> disabled, then
  2090.  
  2091.     # This DOES print "How unusual!" if 'autochomp' is disabled
  2092.     undef $a[10];
  2093.         print "How unusual!\n" if $a[10];
  2094.  
  2095. Because when C<autochomp> is disabled, C<$a[10]> will read back as
  2096. C<"\n"> (or whatever the record separator string is.)  
  2097.  
  2098. There are other minor differences, particularly regarding C<exists>
  2099. and C<delete>, but in general, the correspondence is extremely close.
  2100.  
  2101. =item *
  2102.  
  2103. Not quite every effort was made to make this module as efficient as
  2104. possible.  C<FETCHSIZE> should use binary search instead of linear
  2105. search.
  2106.  
  2107. The performance of the C<flush> method could be improved.  At present,
  2108. it still rewrites the tail of the file once for each block of
  2109. contiguous lines to be changed.  In the typical case, this will result
  2110. in only one rewrite, but in peculiar cases it might be bad.  It should
  2111. be possible to perform I<all> deferred writing with a single rewrite.
  2112.  
  2113. Profiling suggests that these defects are probably minor; in any
  2114. event, they will be fixed in a future version of the module.
  2115.  
  2116. =item *
  2117.  
  2118. I have supposed that since this module is concerned with file I/O,
  2119. almost all normal use of it will be heavily I/O bound.  This means
  2120. that the time to maintain complicated data structures inside the
  2121. module will be dominated by the time to actually perform the I/O.
  2122. When there was an opportunity to spend CPU time to avoid doing I/O, I
  2123. tried to take it.
  2124.  
  2125. =item *
  2126.  
  2127. You might be tempted to think that deferred writing is like
  2128. transactions, with C<flush> as C<commit> and C<discard> as
  2129. C<rollback>, but it isn't, so don't.
  2130.  
  2131. =back
  2132.  
  2133. =head1 SUBCLASSING
  2134.  
  2135. This version promises absolutely nothing about the internals, which
  2136. may change without notice.  A future version of the module will have a
  2137. well-defined and stable subclassing API.
  2138.  
  2139. =head1 WHAT ABOUT C<DB_File>?
  2140.  
  2141. People sometimes point out that L<DB_File> will do something similar,
  2142. and ask why C<Tie::File> module is necessary.
  2143.  
  2144. There are a number of reasons that you might prefer C<Tie::File>.
  2145. A list is available at C<http://perl.plover.com/TieFile/why-not-DB_File>.
  2146.  
  2147. =head1 AUTHOR
  2148.  
  2149. Mark Jason Dominus
  2150.  
  2151. To contact the author, send email to: C<mjd-perl-tiefile+@plover.com>
  2152.  
  2153. To receive an announcement whenever a new version of this module is
  2154. released, send a blank email message to
  2155. C<mjd-perl-tiefile-subscribe@plover.com>.
  2156.  
  2157. The most recent version of this module, including documentation and
  2158. any news of importance, will be available at
  2159.  
  2160.     http://perl.plover.com/TieFile/
  2161.  
  2162.  
  2163. =head1 LICENSE
  2164.  
  2165. C<Tie::File> version 0.93 is copyright (C) 2002 Mark Jason Dominus.
  2166.  
  2167. This library is free software; you may redistribute it and/or modify
  2168. it under the same terms as Perl itself.
  2169.  
  2170. These terms are your choice of any of (1) the Perl Artistic Licence,
  2171. or (2) version 2 of the GNU General Public License as published by the
  2172. Free Software Foundation, or (3) any later version of the GNU General
  2173. Public License.
  2174.  
  2175. This library is distributed in the hope that it will be useful,
  2176. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2177. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  2178. GNU General Public License for more details.
  2179.  
  2180. You should have received a copy of the GNU General Public License
  2181. along with this library program; it should be in the file C<COPYING>.
  2182. If not, write to the Free Software Foundation, Inc., 59 Temple Place,
  2183. Suite 330, Boston, MA 02111 USA
  2184.  
  2185. For licensing inquiries, contact the author at:
  2186.  
  2187.     Mark Jason Dominus
  2188.     255 S. Warnock St.
  2189.     Philadelphia, PA 19107
  2190.  
  2191. =head1 WARRANTY
  2192.  
  2193. C<Tie::File> version 0.93 comes with ABSOLUTELY NO WARRANTY.
  2194. For details, see the license.
  2195.  
  2196. =head1 THANKS
  2197.  
  2198. Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the
  2199. core when I hadn't written it yet, and for generally being helpful,
  2200. supportive, and competent.  (Usually the rule is "choose any one.")
  2201. Also big thanks to Abhijit Menon-Sen for all of the same things.
  2202.  
  2203. Special thanks to Craig Berry and Peter Prymmer (for VMS portability
  2204. help), Randy Kobes (for Win32 portability help), Clinton Pierce and
  2205. Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond
  2206. the call of duty), Michael G Schwern (for testing advice), and the
  2207. rest of the CPAN testers (for testing generally).
  2208.  
  2209. Additional thanks to:
  2210. Edward Avis /
  2211. Gerrit Haase /
  2212. Nikola Knezevic /
  2213. Nick Ing-Simmons /
  2214. Tassilo von Parseval /
  2215. H. Dieter Pearcey /
  2216. Slaven Rezic /
  2217. Peter Scott /
  2218. Peter Somu /
  2219. Autrijus Tang (again) /
  2220. Tels /
  2221. Juerd Wallboer
  2222.  
  2223. =head1 TODO
  2224.  
  2225. More tests.  (The cache and heap modules need more unit tests.) 
  2226.  
  2227. Improve SPLICE algorithm to use deferred writing machinery.
  2228.  
  2229. Cleverer strategy for flushing deferred writes.
  2230.  
  2231. More tests.  (Stuff I didn't think of yet.)
  2232.  
  2233. Paragraph mode?
  2234.  
  2235. Fixed-length mode.  Leave-blanks mode.
  2236.  
  2237. Maybe an autolocking mode?
  2238.  
  2239. Record locking with fcntl()?  Then the module might support an undo
  2240. log and get real transactions.  What a tour de force that would be.
  2241.  
  2242. More tests.
  2243.  
  2244. =cut
  2245.  
  2246.