This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #22141] patch for Time::HiRes to get rid of -lrt on linux
[perl5.git] / lib / Tie / File.pm
CommitLineData
b5aed31e
AMS
1
2package Tie::File;
6fc0ea7e 3require 5.005;
b5aed31e
AMS
4use Carp;
5use POSIX 'SEEK_SET';
95f36366
AMS
6use Fcntl 'O_CREAT', 'O_RDWR', 'LOCK_EX', 'O_WRONLY', 'O_RDONLY';
7sub O_ACCMODE () { O_RDONLY | O_RDWR | O_WRONLY }
b5aed31e 8
0bf62e3b 9$VERSION = "0.93";
b3fe5a4c 10my $DEFAULT_MEMORY_SIZE = 1<<21; # 2 megabytes
6fc0ea7e
JH
11my $DEFAULT_AUTODEFER_THRESHHOLD = 3; # 3 records
12my $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD = 65536; # 16 disk blocksful
b3fe5a4c
AMS
13
14my %good_opt = map {$_ => 1, "-$_" => 1}
6fc0ea7e 15 qw(memory dw_size mode recsep discipline autodefer autochomp);
b5aed31e
AMS
16
17sub 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) {
b3fe5a4c
AMS
25 unless ($good_opt{$key}) {
26 croak("$pack: Unrecognized option '$key'\n");
27 }
b5aed31e
AMS
28 my $okey = $key;
29 if ($key =~ s/^-+//) {
30 $opts{$key} = delete $opts{$okey};
31 }
32 }
33
b3fe5a4c
AMS
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;
57c7bc08 40 # Dora Winifred Read
b3fe5a4c
AMS
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 }
57c7bc08
AMS
46 # are we in deferred-write mode?
47 $opts{defer} = 0 unless defined $opts{defer};
48 $opts{deferred} = {}; # no records are presently deferred
b3fe5a4c 49 $opts{deferred_s} = 0; # count of total bytes in ->{deferred}
6fc0ea7e 50 $opts{deferred_max} = -1; # empty
b5aed31e
AMS
51
52 # the cache is a hash instead of an array because it is likely to be
53 # sparsely populated
6fc0ea7e
JH
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};
b5aed31e
AMS
64
65 $opts{offsets} = [0];
66 $opts{filename} = $file;
b3fe5a4c
AMS
67 unless (defined $opts{recsep}) {
68 $opts{recsep} = _default_recsep();
69 }
b5aed31e
AMS
70 $opts{recseplen} = length($opts{recsep});
71 if ($opts{recseplen} == 0) {
72 croak "Empty record separator not supported by $pack";
73 }
74
0b28bc9a
AMS
75 $opts{autochomp} = 1 unless defined $opts{autochomp};
76
27531ffb
JH
77 $opts{mode} = O_CREAT|O_RDWR unless defined $opts{mode};
78 $opts{rdonly} = (($opts{mode} & O_ACCMODE) == O_RDONLY);
bf919750 79 $opts{sawlastrec} = undef;
27531ffb 80
fa408a35 81 my $fh;
b5aed31e 82
fa408a35 83 if (UNIVERSAL::isa($file, 'GLOB')) {
57c7bc08
AMS
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) {
fa408a35
AMS
89 croak "$pack: your filehandle does not appear to be seekable";
90 }
57c7bc08
AMS
91 seek $file, 0, SEEK_SET # put it back
92 $fh = $file; # setting binmode is the user's problem
fa408a35
AMS
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
27531ffb 97 sysopen $fh, $file, $opts{mode}, 0666 or return;
fa408a35
AMS
98 binmode $fh;
99 }
b5aed31e 100 { my $ofh = select $fh; $| = 1; select $ofh } # autoflush on write
b3fe5a4c
AMS
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 }
b5aed31e
AMS
107 $opts{fh} = $fh;
108
109 bless \%opts => $pack;
110}
111
112sub FETCH {
113 my ($self, $n) = @_;
6fc0ea7e
JH
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
57c7bc08 123 $self->_chomp1($rec);
0b28bc9a
AMS
124}
125
126# Chomp many records in-place; return nothing useful
127sub _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
139sub _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
147sub _fetch {
148 my ($self, $n) = @_;
b5aed31e
AMS
149
150 # check the record cache
6fc0ea7e 151 { my $cached = $self->{cache}->lookup($n);
b5aed31e
AMS
152 return $cached if defined $cached;
153 }
154
27531ffb
JH
155 if ($#{$self->{offsets}} < $n) {
156 return if $self->{eof};
b5aed31e
AMS
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;
b3fe5a4c
AMS
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
6fc0ea7e 178 $self->{cache}->insert($n, $rec) if defined $rec && not $self->{flushing};
b5aed31e
AMS
179 $rec;
180}
181
182sub STORE {
183 my ($self, $n, $rec) = @_;
6fc0ea7e 184 die "STORE called from _check_integrity!" if $DIAGNOSTIC;
b5aed31e
AMS
185
186 $self->_fixrecs($rec);
187
6fc0ea7e
JH
188 if ($self->{autodefer}) {
189 $self->_annotate_ad_history($n);
190 }
191
192 return $self->_store_deferred($n, $rec) if $self->_is_deferring;
193
b5aed31e
AMS
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
6fc0ea7e 198 # 20020324 Wait, but this DOES alter the cache. TODO BUG?
0b28bc9a 199 my $oldrec = $self->_fetch($n);
b5aed31e 200
6fc0ea7e
JH
201 if (defined($self->{cache}->lookup($n))) {
202 $self->{cache}->update($n, $rec);
fa408a35 203 }
b5aed31e
AMS
204
205 if (not defined $oldrec) {
206 # We're storing a record beyond the end of the file
51efdd02 207 $self->_extend_file_to($n+1);
b5aed31e
AMS
208 $oldrec = $self->{recsep};
209 }
210 my $len_diff = length($rec) - length($oldrec);
211
b3fe5a4c 212 # length($oldrec) here is not consistent with text mode TODO XXX BUG
b5aed31e
AMS
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
b3fe5a4c
AMS
223sub _store_deferred {
224 my ($self, $n, $rec) = @_;
6fc0ea7e 225 $self->{cache}->remove($n);
b3fe5a4c 226 my $old_deferred = $self->{deferred}{$n};
6fc0ea7e
JH
227
228 if (defined $self->{deferred_max} && $n > $self->{deferred_max}) {
229 $self->{deferred_max} = $n;
230 }
b3fe5a4c 231 $self->{deferred}{$n} = $rec;
6fc0ea7e
JH
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);
b3fe5a4c 237 if ($self->{deferred_s} > $self->{dw_size}) {
57c7bc08
AMS
238 $self->_flush;
239 } elsif ($self->_cache_too_full) {
b3fe5a4c
AMS
240 $self->_cache_flush;
241 }
242}
243
57c7bc08
AMS
244# Remove a single record from the deferred-write buffer without writing it
245# The record need not be present
246sub _delete_deferred {
247 my ($self, $n) = @_;
248 my $rec = delete $self->{deferred}{$n};
249 return unless defined $rec;
6fc0ea7e
JH
250
251 if (defined $self->{deferred_max}
252 && $n == $self->{deferred_max}) {
253 undef $self->{deferred_max};
254 }
255
57c7bc08 256 $self->{deferred_s} -= length $rec;
6fc0ea7e 257 $self->{cache}->adj_limit(length $rec);
57c7bc08
AMS
258}
259
b5aed31e
AMS
260sub FETCHSIZE {
261 my $self = shift;
262 my $n = $#{$self->{offsets}};
57c7bc08 263 # 20020317 Change this to binary search
27531ffb
JH
264 unless ($self->{eof}) {
265 while (defined ($self->_fill_offsets_to($n+1))) {
266 ++$n;
267 }
b5aed31e 268 }
6fc0ea7e
JH
269 my $top_deferred = $self->_defer_max;
270 $n = $top_deferred+1 if defined $top_deferred && $n < $top_deferred+1;
b5aed31e
AMS
271 $n;
272}
273
274sub STORESIZE {
275 my ($self, $len) = @_;
6fc0ea7e
JH
276
277 if ($self->{autodefer}) {
278 $self->_annotate_ad_history('STORESIZE');
279 }
280
b5aed31e
AMS
281 my $olen = $self->FETCHSIZE;
282 return if $len == $olen; # Woo-hoo!
283
284 # file gets longer
285 if ($len > $olen) {
6fc0ea7e 286 if ($self->_is_deferring) {
57c7bc08
AMS
287 for ($olen .. $len-1) {
288 $self->_store_deferred($_, $self->{recsep});
289 }
290 } else {
291 $self->_extend_file_to($len);
292 }
b5aed31e
AMS
293 return;
294 }
295
296 # file gets shorter
6fc0ea7e
JH
297 if ($self->_is_deferring) {
298 # TODO maybe replace this with map-plus-assignment?
57c7bc08
AMS
299 for (grep $_ >= $len, keys %{$self->{deferred}}) {
300 $self->_delete_deferred($_);
301 }
6fc0ea7e 302 $self->{deferred_max} = $len-1;
57c7bc08
AMS
303 }
304
b5aed31e
AMS
305 $self->_seek($len);
306 $self->_chop_file;
836d9961 307 $#{$self->{offsets}} = $len;
b3fe5a4c 308# $self->{offsets}[0] = 0; # in case we just chopped this
6fc0ea7e 309
bf919750 310 $self->{cache}->remove(grep $_ >= $len, $self->{cache}->ckeys);
b5aed31e
AMS
311}
312
51efdd02
AMS
313sub PUSH {
314 my $self = shift;
315 $self->SPLICE($self->FETCHSIZE, scalar(@_), @_);
57c7bc08 316# $self->FETCHSIZE; # av.c takes care of this for me
51efdd02
AMS
317}
318
319sub POP {
320 my $self = shift;
7b6b3db1
JH
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);
51efdd02
AMS
325}
326
327sub SHIFT {
328 my $self = shift;
329 scalar $self->SPLICE(0, 1);
330}
331
332sub UNSHIFT {
333 my $self = shift;
334 $self->SPLICE(0, 0, @_);
57c7bc08 335 # $self->FETCHSIZE; # av.c takes care of this for me
51efdd02
AMS
336}
337
338sub CLEAR {
51efdd02 339 my $self = shift;
6fc0ea7e
JH
340
341 if ($self->{autodefer}) {
342 $self->_annotate_ad_history('CLEAR');
343 }
344
51efdd02
AMS
345 $self->_seekb(0);
346 $self->_chop_file;
6fc0ea7e
JH
347 $self->{cache}->set_limit($self->{memory});
348 $self->{cache}->empty;
51efdd02 349 @{$self->{offsets}} = (0);
57c7bc08
AMS
350 %{$self->{deferred}}= ();
351 $self->{deferred_s} = 0;
6fc0ea7e 352 $self->{deferred_max} = -1;
51efdd02
AMS
353}
354
355sub EXTEND {
356 my ($self, $n) = @_;
57c7bc08
AMS
357
358 # No need to pre-extend anything in this case
6fc0ea7e 359 return if $self->_is_deferring;
57c7bc08 360
51efdd02
AMS
361 $self->_fill_offsets_to($n);
362 $self->_extend_file_to($n);
363}
364
365sub DELETE {
366 my ($self, $n) = @_;
6fc0ea7e
JH
367
368 if ($self->{autodefer}) {
369 $self->_annotate_ad_history('DELETE');
370 }
371
51efdd02 372 my $lastrec = $self->FETCHSIZE-1;
57c7bc08 373 my $rec = $self->FETCH($n);
6fc0ea7e 374 $self->_delete_deferred($n) if $self->_is_deferring;
51efdd02
AMS
375 if ($n == $lastrec) {
376 $self->_seek($n);
377 $self->_chop_file;
fa408a35 378 $#{$self->{offsets}}--;
6fc0ea7e 379 $self->{cache}->remove($n);
51efdd02 380 # perhaps in this case I should also remove trailing null records?
57c7bc08
AMS
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) {
51efdd02
AMS
386 $self->STORE($n, "");
387 }
57c7bc08 388 $rec;
51efdd02
AMS
389}
390
391sub EXISTS {
392 my ($self, $n) = @_;
57c7bc08
AMS
393 return 1 if exists $self->{deferred}{$n};
394 $self->_fill_offsets_to($n); # I think this is unnecessary
395 $n < $self->FETCHSIZE;
51efdd02
AMS
396}
397
b5aed31e 398sub SPLICE {
b3fe5a4c 399 my $self = shift;
6fc0ea7e
JH
400
401 if ($self->{autodefer}) {
402 $self->_annotate_ad_history('SPLICE');
403 }
404
405 $self->_flush if $self->_is_deferring; # move this up?
0b28bc9a
AMS
406 if (wantarray) {
407 $self->_chomp(my @a = $self->_splice(@_));
408 @a;
409 } else {
410 $self->_chomp1(scalar $self->_splice(@_));
411 }
b3fe5a4c
AMS
412}
413
414sub DESTROY {
57c7bc08 415 my $self = shift;
6fc0ea7e
JH
416 $self->flush if $self->_is_deferring;
417 $self->{cache}->delink if defined $self->{cache}; # break circular link
b3fe5a4c
AMS
418}
419
420sub _splice {
b5aed31e
AMS
421 my ($self, $pos, $nrecs, @data) = @_;
422 my @result;
423
7b6b3db1
JH
424 $pos = 0 unless defined $pos;
425
426 # Deal with negative and other out-of-range positions
427 # Also set default for $nrecs
51efdd02
AMS
428 {
429 my $oldsize = $self->FETCHSIZE;
7b6b3db1 430 $nrecs = $oldsize unless defined $nrecs;
51efdd02
AMS
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 }
bf919750
JH
444
445 # The manual is very unclear here
446 if ($nrecs < 0) {
447 $nrecs = $oldsize - $pos + $nrecs;
448 $nrecs = 0 if $nrecs < 0;
449 }
51efdd02 450 }
b5aed31e
AMS
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) {
27531ffb 459 last unless defined $self->_fill_offsets_to($_);
0b28bc9a 460 my $rec = $self->_fetch($_);
b5aed31e
AMS
461 last unless defined $rec;
462 push @result, $rec;
6fc0ea7e
JH
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,
27531ffb
JH
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
6fc0ea7e
JH
470 $oldlen += $self->{offsets}[$_+1] - $self->{offsets}[$_]
471 if defined $self->{offsets}[$_+1];
b5aed31e
AMS
472 }
473
51efdd02 474 # Modify the file
b5aed31e
AMS
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 }
27531ffb
JH
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 }
b5aed31e
AMS
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}};
27531ffb
JH
501 # If the file got longer, the offsets table is no longer complete
502 $self->{eof} = 0 if @data > $nrecs;
503
b5aed31e 504
51efdd02
AMS
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
b5aed31e
AMS
511 # update the read cache, part 1
512 # modified records
b5aed31e 513 for ($pos .. $pos+$nrecs-1) {
b5aed31e
AMS
514 my $new = $data[$_-$pos];
515 if (defined $new) {
6fc0ea7e 516 $self->{cache}->update($_, $new);
b5aed31e 517 } else {
6fc0ea7e 518 $self->{cache}->remove($_);
b5aed31e
AMS
519 }
520 }
6fc0ea7e 521
b5aed31e
AMS
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?
b3fe5a4c 526 {
bf919750 527 my @oldkeys = grep $_ >= $pos + $nrecs, $self->{cache}->ckeys;
6fc0ea7e
JH
528 my @newkeys = map $_-$nrecs+@data, @oldkeys;
529 $self->{cache}->rekey(\@oldkeys, \@newkeys);
b5aed31e 530 }
b5aed31e 531
b3fe5a4c
AMS
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
51efdd02
AMS
537 # Yes, the return value of 'splice' *is* actually this complicated
538 wantarray ? @result : @result ? $result[-1] : undef;
b5aed31e
AMS
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
548sub _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);
51efdd02 570 my $next_block;
6fc0ea7e 571 my $more_data;
b5aed31e
AMS
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);
51efdd02 578 my $br = read $self->{fh}, $next_block, $bufsize;
6fc0ea7e 579 $more_data = read $self->{fh}, my($dummy), 1;
b5aed31e
AMS
580 $self->_seekb($writepos);
581 $self->_write_record($data);
582 $readpos += $br;
583 $writepos += length $data;
584 $data = $next_block;
6fc0ea7e 585 } while $more_data; # BUG XXX TODO how could this have worked?
51efdd02
AMS
586 $self->_seekb($writepos);
587 $self->_write_record($next_block);
b5aed31e
AMS
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.
595sub _fixrecs {
596 my $self = shift;
597 for (@_) {
27531ffb 598 $_ = "" unless defined $_;
b5aed31e
AMS
599 $_ .= $self->{recsep}
600 unless substr($_, - $self->{recseplen}) eq $self->{recsep};
601 }
602}
603
57c7bc08
AMS
604
605################################################################
606#
607# Basic read, write, and seek
608#
609
b5aed31e
AMS
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#
617sub _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
626sub _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
634sub _fill_offsets_to {
635 my ($self, $n) = @_;
27531ffb
JH
636
637 return $self->{offsets}[$n] if $self->{eof};
638
b5aed31e
AMS
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) {
51efdd02 648 push @OFF, tell $fh;
b5aed31e 649 } else {
27531ffb 650 $self->{eof} = 1;
b5aed31e
AMS
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
661sub _write_record {
662 my ($self, $rec) = @_;
663 my $fh = $self->{fh};
bf919750 664 local $\ = "";
b5aed31e
AMS
665 print $fh $rec
666 or die "Couldn't write record: $!"; # "Should never happen."
27531ffb 667# $self->{_written} += length($rec);
b5aed31e
AMS
668}
669
670sub _read_record {
671 my $self = shift;
672 my $rec;
673 { local $/ = $self->{recsep};
674 my $fh = $self->{fh};
675 $rec = <$fh>;
676 }
27531ffb 677 return unless defined $rec;
bf919750
JH
678 if (! $self->{sawlastrec} &&
679 substr($rec, -$self->{recseplen}) ne $self->{recsep}) {
27531ffb
JH
680 # improperly terminated final record --- quietly fix it.
681# my $ac = substr($rec, -$self->{recseplen});
682# $ac =~ s/\n/\\n/g;
bf919750 683 $self->{sawlastrec} = 1;
27531ffb 684 unless ($self->{rdonly}) {
bf919750 685 local $\ = "";
27531ffb
JH
686 my $fh = $self->{fh};
687 print $fh $self->{recsep};
688 }
689 $rec .= $self->{recsep};
690 }
691# $self->{_read} += length($rec) if defined $rec;
b5aed31e
AMS
692 $rec;
693}
694
6fc0ea7e 695sub _rw_stats {
27531ffb 696 my $self = shift;
6fc0ea7e
JH
697 @{$self}{'_read', '_written'};
698}
699
57c7bc08
AMS
700################################################################
701#
702# Read cache management
703
6fc0ea7e
JH
704sub _cache_flush {
705 my ($self) = @_;
706 $self->{cache}->reduce_size_to($self->{memory} - $self->{deferred_s});
b5aed31e
AMS
707}
708
57c7bc08
AMS
709sub _cache_too_full {
710 my $self = shift;
6fc0ea7e 711 $self->{cache}->bytes + $self->{deferred_s} >= $self->{memory};
b5aed31e
AMS
712}
713
57c7bc08
AMS
714################################################################
715#
716# File custodial services
717#
718
719
b5aed31e
AMS
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
51efdd02
AMS
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.
b5aed31e
AMS
727sub _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
6fc0ea7e 733 my $extras = $n - $#{$self->{offsets}};
b5aed31e
AMS
734
735 # Todo : just use $self->{recsep} x $extras here?
736 while ($extras-- > 0) {
737 $self->_write_record($self->{recsep});
fa408a35 738 push @{$self->{offsets}}, tell $self->{fh};
b5aed31e
AMS
739 }
740}
741
742# Truncate the file at the current position
743sub _chop_file {
744 my $self = shift;
745 truncate $self->{fh}, tell($self->{fh});
746}
747
57c7bc08 748
b5aed31e
AMS
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.
753sub _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
57c7bc08
AMS
761################################################################
762#
763# Miscellaneous public methods
764#
765
51efdd02
AMS
766# Lock the file
767sub 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}
b5aed31e 777
0b28bc9a
AMS
778# Get/set autochomp option
779sub 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
57c7bc08
AMS
790################################################################
791#
792# Matters related to deferred writing
793#
794
795# Defer writes
796sub defer {
797 my $self = shift;
6fc0ea7e
JH
798 $self->_stop_autodeferring;
799 @{$self->{ad_history}} = ();
57c7bc08
AMS
800 $self->{defer} = 1;
801}
802
b3fe5a4c
AMS
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.
808sub flush {
809 my $self = shift;
810
811 $self->_flush;
812 $self->{defer} = 0;
813}
814
815sub _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
57c7bc08 831 $self->_discard; # clear out defered-write-cache
b3fe5a4c
AMS
832}
833
57c7bc08 834# Discard deferred writes and disable future deferred writes
b3fe5a4c
AMS
835sub discard {
836 my $self = shift;
57c7bc08 837 $self->_discard;
b3fe5a4c
AMS
838 $self->{defer} = 0;
839}
840
57c7bc08
AMS
841# Discard deferred writes, but retain old deferred writing mode
842sub _discard {
843 my $self = shift;
6fc0ea7e
JH
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})
852sub _is_deferring {
853 my $self = shift;
854 $self->{defer} || $self->{autodeferring};
855}
856
857# The largest record number of any deferred record
858sub _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;
57c7bc08
AMS
867}
868
6fc0ea7e
JH
869################################################################
870#
871# Matters related to autodeferment
872#
873
874# Get/set autodefer option
875sub 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#
913sub _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
944sub _stop_autodeferring {
945 my $self = shift;
946 if ($self->{autodeferring}) {
947 $self->_flush;
948 }
949 $self->{autodeferring} = 0;
950}
951
952################################################################
953
b3fe5a4c 954
57c7bc08
AMS
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.
b3fe5a4c
AMS
959sub _default_recsep {
960 my $recsep = $/;
57c7bc08 961 if ($^O eq 'MSWin32') { # Dos too?
b3fe5a4c
AMS
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
57c7bc08
AMS
971# Utility function for _check_integrity
972sub _ci_warn {
973 my $msg = shift;
974 $msg =~ s/\n/\\n/g;
975 $msg =~ s/\r/\\r/g;
976 print "# $msg\n";
977}
978
b5aed31e 979# Given a file, make sure the cache is consistent with the
57c7bc08
AMS
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.
b5aed31e
AMS
985sub _check_integrity {
986 my ($self, $file, $warn) = @_;
6fc0ea7e
JH
987 my $rsl = $self->{recseplen};
988 my $rs = $self->{recsep};
b5aed31e 989 my $good = 1;
6fc0ea7e
JH
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 }
fa408a35 1004
836d9961 1005 if (not defined $self->{offsets}[0]) {
57c7bc08 1006 _ci_warn("offset 0 is missing!");
836d9961 1007 $good = 0;
bf919750 1008
836d9961 1009 } elsif ($self->{offsets}[0] != 0) {
57c7bc08 1010 _ci_warn("rec 0: offset <$self->{offsets}[0]> s/b 0!");
b5aed31e
AMS
1011 $good = 0;
1012 }
fa408a35 1013
57c7bc08 1014 my $cached = 0;
6fc0ea7e
JH
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) {
27531ffb 1035 $good = 0;
6fc0ea7e
JH
1036 _ci_warn("rec $n in the cache is missing the record separator");
1037 }
27531ffb
JH
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 $.");
6fc0ea7e 1047 }
b5aed31e 1048
6fc0ea7e 1049 my $deferring = $self->_is_deferring;
bf919750 1050 for my $n ($self->{cache}->ckeys) {
6fc0ea7e
JH
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");
b5aed31e
AMS
1055 $good = 0;
1056 }
6fc0ea7e
JH
1057 my $b = $self->{cache}->bytes;
1058 if ($cached != $b) {
1059 _ci_warn("cache size is $b, should be $cached");
b5aed31e
AMS
1060 $good = 0;
1061 }
1062 }
1063
bf919750 1064 # That cache has its own set of tests
6fc0ea7e
JH
1065 $good = 0 unless $self->{cache}->_check_integrity;
1066
57c7bc08
AMS
1067 # Now let's check the deferbuffer
1068 # Unless deferred writing is enabled, it should be empty
6fc0ea7e 1069 if (! $self->_is_deferring && %{$self->{deferred}}) {
57c7bc08
AMS
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);
6fc0ea7e 1078 if (defined $self->{cache}->_produce($n)) {
57c7bc08
AMS
1079 _ci_warn("record $n is in the deferbuffer *and* the readcache");
1080 $good = 0;
1081 }
6fc0ea7e 1082 if (substr($r, -$rsl) ne $rs) {
57c7bc08
AMS
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
6fc0ea7e
JH
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
b5aed31e
AMS
1136 $good;
1137}
1138
6fc0ea7e
JH
1139################################################################
1140#
1141# Tie::File::Cache
1142#
1143# Read cache
1144
1145package Tie::File::Cache;
1146$Tie::File::Cache::VERSION = $Tie::File::VERSION;
1147use Carp ':DEFAULT', 'confess';
1148
1149sub HEAP () { 0 }
1150sub HASH () { 1 }
1151sub MAX () { 2 }
1152sub BYTES() { 3 }
1153use strict 'vars';
1154
1155sub 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
1165sub adj_limit {
1166 my ($self, $n) = @_;
1167 $self->[MAX] += $n;
1168}
1169
1170sub 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.
1181sub _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
1190sub 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
1210sub 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
1218sub 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
1230sub 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
1242sub _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
1250sub _promote {
1251 my ($self, $key) = @_;
1252 $self->[HEAP]->promote($self->[HASH]{$key});
1253}
1254
1255sub empty {
1256 my ($self) = @_;
1257 %{$self->[HASH]} = ();
1258 $self->[BYTES] = 0;
1259 $self->[HEAP]->empty;
1260}
1261
1262sub is_empty {
1263 my ($self) = @_;
1264 keys %{$self->[HASH]} == 0;
1265}
1266
1267sub 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
1285sub 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
bf919750 1304sub ckeys {
6fc0ea7e
JH
1305 my $self = shift;
1306 my @a = keys %{$self->[HASH]};
1307 @a;
1308}
1309
1310sub bytes {
1311 my $self = shift;
1312 $self->[BYTES];
1313}
1314
1315sub reduce_size_to {
1316 my ($self, $max) = @_;
1317 until ($self->is_empty || $self->[BYTES] <= $max) {
1318 $self->expire;
1319 }
1320}
1321
1322sub 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
1330sub _produce_lru {
1331 my $self = shift;
1332 $self->[HEAP]->expire_order;
1333}
1334
bf919750
JH
1335BEGIN { *_ci_warn = \&Tie::File::_ci_warn }
1336
1337sub _check_integrity { # For CACHE
6fc0ea7e 1338 my $self = shift;
bf919750
JH
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;
6fc0ea7e
JH
1387}
1388
1389sub 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
1400package Tie::File::Heap;
1401use Carp ':DEFAULT', 'confess';
1402$Tie::File::Heap::VERSION = $Tie::File::Cache::VERSION;
1403sub SEQ () { 0 };
1404sub KEY () { 1 };
1405sub DAT () { 2 };
1406
1407sub 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
1416sub _nseq {
1417 my $self = shift;
1418 $self->[0][0]++;
1419}
1420
1421sub _cache {
1422 my $self = shift;
1423 $self->[0][1];
1424}
1425
1426sub _nelts {
1427 my $self = shift;
1428 $self->[0][2];
1429}
1430
1431sub _nelts_inc {
1432 my $self = shift;
1433 ++$self->[0][2];
1434}
1435
1436sub _nelts_dec {
1437 my $self = shift;
1438 --$self->[0][2];
1439}
1440
1441sub is_empty {
1442 my $self = shift;
1443 $self->_nelts == 0;
1444}
1445
1446sub 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
27531ffb 1453# notify the parent cache object that we moved something
6fc0ea7e
JH
1454sub _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.
1463sub 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
1470sub _insert_new {
1471 my ($self, $item) = @_;
1472 my $i = @$self;
1473 $i = int($i/2) until defined $self->[$i/2];
1474 $self->[$i] = $item;
27531ffb 1475 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
6fc0ea7e
JH
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.)
1481sub _insert {
1482 my ($self, $item, $i) = @_;
bf919750 1483# $self->_check_loc($i) if defined $i;
6fc0ea7e
JH
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]);
27531ffb 1488 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
6fc0ea7e
JH
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;
27531ffb 1498 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
6fc0ea7e
JH
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.
1506sub 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
27531ffb 1525 $self->[0][1]->_heap_move($self->[$i][KEY], $i);
6fc0ea7e
JH
1526 $i = $ii; # Fill new vacated spot
1527 }
27531ffb 1528 $self->[0][1]->_heap_move($top->[KEY], undef);
6fc0ea7e
JH
1529 undef $self->[$i];
1530 $self->_nelts_dec;
1531 return $top->[DAT];
1532}
1533
1534sub 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.
1542sub promote {
1543 my ($self, $n) = @_;
bf919750 1544# $self->_check_loc($n);
6fc0ea7e
JH
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) {
27531ffb 1558 $self->[0][1]->_heap_move($self->[$_][KEY], $_) if defined $self->[$_];
6fc0ea7e
JH
1559 }
1560 $i = $dir;
1561 }
1562}
1563
1564# Return item $n from the heap, promoting its LRU status
1565sub lookup {
1566 my ($self, $n) = @_;
bf919750 1567# $self->_check_loc($n);
6fc0ea7e
JH
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
1575sub set_val {
1576 my ($self, $n, $val) = @_;
bf919750 1577# $self->_check_loc($n);
6fc0ea7e
JH
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
1586sub rekey {
1587 my ($self, $n, $new_key) = @_;
bf919750 1588# $self->_check_loc($n);
6fc0ea7e
JH
1589 $self->[$n][KEY] = $new_key;
1590}
1591
1592sub _check_loc {
1593 my ($self, $n) = @_;
bf919750 1594 unless (1 || defined $self->[$n]) {
6fc0ea7e
JH
1595 confess "_check_loc($n) failed";
1596 }
1597}
1598
bf919750
JH
1599BEGIN { *_ci_warn = \&Tie::File::_ci_warn }
1600
6fc0ea7e
JH
1601sub _check_integrity {
1602 my $self = shift;
1603 my $good = 1;
bf919750
JH
1604 my %seq;
1605
6fc0ea7e 1606 unless (eval {$self->[0][1]->isa("Tie::File::Cache")}) {
bf919750 1607 _ci_warn "Element 0 of heap corrupt";
6fc0ea7e
JH
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]) {
bf919750 1614 _ci_warn "Element $i of heap defined, but parent $p isn't";
6fc0ea7e
JH
1615 $good = 0;
1616 }
bf919750
JH
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 }
6fc0ea7e 1627 }
bf919750 1628
6fc0ea7e
JH
1629 return $good;
1630}
1631
1632sub _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]) {
bf919750 1640 _ci_warn "Node $n of heap does not predate node $c";
6fc0ea7e
JH
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
1649sub expire_order {
1650 my $self = shift;
1651 my @nodes = sort {$a->[SEQ] <=> $b->[SEQ]} $self->_nodes;
1652 map { $_->[KEY] } @nodes;
1653}
1654
1655sub _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
fa408a35
AMS
1662"Cogito, ergo sum."; # don't forget to return a true value from the file
1663
b5aed31e
AMS
1664=head1 NAME
1665
1666Tie::File - Access the lines of a disk file via a Perl array
1667
1668=head1 SYNOPSIS
1669
0bf62e3b 1670 # This file documents Tie::File version 0.93
b5aed31e
AMS
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?
57c7bc08
AMS
1678 $#array -= 2; # chop two records off the end
1679
b5aed31e 1680
57c7bc08
AMS
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
51efdd02
AMS
1687
1688 push @array, new recs...;
1689 my $r1 = pop @array;
1690 unshift @array, new recs...;
1691 my $r1 = shift @array;
b5aed31e
AMS
1692 @old_recs = splice @array, 3, 7, new recs...;
1693
1694 untie @array; # all finished
1695
57c7bc08 1696
b5aed31e
AMS
1697=head1 DESCRIPTION
1698
1699C<Tie::File> represents a regular text file as a Perl array. Each
1700element in the array corresponds to a record in the file. The first
1701line of the file is element 0 of the array; the second line is element
17021, and so on.
1703
1704The file is I<not> loaded into memory, so this will work even for
1705gigantic files.
1706
1707Changes to the array are reflected in the file immediately.
1708
57c7bc08 1709Lazy people and beginners may now stop reading the manual.
b3fe5a4c 1710
b5aed31e
AMS
1711=head2 C<recsep>
1712
1713What is a 'record'? By default, the meaning is the same as for the
1714C<E<lt>...E<gt>> operator: It's a string terminated by C<$/>, which is
b3fe5a4c
AMS
1715probably C<"\n">. (Minor exception: on dos and Win32 systems, a
1716'record' is a string terminated by C<"\r\n">.) You may change the
1717definition of "record" by supplying the C<recsep> option in the C<tie>
1718call:
b5aed31e
AMS
1719
1720 tie @array, 'Tie::File', $file, recsep => 'es';
1721
b3fe5a4c
AMS
1722This says that records are delimited by the string C<es>. If the file
1723contained the following data:
b5aed31e
AMS
1724
1725 Curse these pesky flies!\n
1726
27531ffb 1727then the C<@array> would appear to have four elements:
b5aed31e 1728
0b28bc9a
AMS
1729 "Curse th"
1730 "e p"
1731 "ky fli"
b5aed31e
AMS
1732 "!\n"
1733
1734An undefined value is not permitted as a record separator. Perl's
1735special "paragraph mode" semantics (E<agrave> la C<$/ = "">) are not
1736emulated.
1737
0b28bc9a 1738Records read from the tied array do not have the record separator
27531ffb 1739string on the end; this is to allow
0b28bc9a
AMS
1740
1741 $array[17] .= "extra";
1742
1743to work as expected.
1744
1745(See L<"autochomp">, below.) Records stored into the array will have
1746the record separator string appended before they are written to the
1747file, if they don't have one already. For example, if the record
1748separator string is C<"\n">, then the following two lines do exactly
1749the same thing:
b5aed31e
AMS
1750
1751 $array[17] = "Cherry pie";
1752 $array[17] = "Cherry pie\n";
1753
1754The result is that the contents of line 17 of the file will be
1755replaced with "Cherry pie"; a newline character will separate line 17
27531ffb 1756from line 18. This means that this code will do nothing:
b5aed31e
AMS
1757
1758 chomp $array[17];
1759
1760Because the C<chomp>ed value will have the separator reattached when
1761it is written back to the file. There is no way to create a file
1762whose trailing record separator string is missing.
1763
27531ffb
JH
1764Inserting records that I<contain> the record separator string is not
1765supported by this module. It will probably produce a reasonable
1766result, but what this result will be may change in a future version.
1767Use 'splice' to insert records or to replace one record with several.
b5aed31e 1768
0b28bc9a
AMS
1769=head2 C<autochomp>
1770
1771Normally, array elements have the record separator removed, so that if
1772the file contains the text
1773
1774 Gold
1775 Frankincense
1776 Myrrh
1777
57c7bc08
AMS
1778the tied array will appear to contain C<("Gold", "Frankincense",
1779"Myrrh")>. If you set C<autochomp> to a false value, the record
1780separator will not be removed. If the file above was tied with
0b28bc9a
AMS
1781
1782 tie @gifts, "Tie::File", $gifts, autochomp => 0;
1783
1784then 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
b5aed31e
AMS
1788=head2 C<mode>
1789
1790Normally, the specified file will be opened for read and write access,
1791and will be created if it does not exist. (That is, the flags
1792C<O_RDWR | O_CREAT> are supplied in the C<open> call.) If you want to
1793change this, you may supply alternative flags in the C<mode> option.
1794See L<Fcntl> for a listing of available flags.
1795For 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
1809Opening the data file in write-only or append mode is not supported.
1810
b3fe5a4c
AMS
1811=head2 C<memory>
1812
57c7bc08
AMS
1813This is an upper limit on the amount of memory that C<Tie::File> will
1814consume at any time while managing the file. This is used for two
1815things: managing the I<read cache> and managing the I<deferred write
1816buffer>.
b5aed31e
AMS
1817
1818Records read in from the file are cached, to avoid having to re-read
1819them repeatedly. If you read the same record twice, the first time it
1820will be stored in memory, and the second time it will be fetched from
b3fe5a4c
AMS
1821the I<read cache>. The amount of data in the read cache will not
1822exceed the value you specified for C<memory>. If C<Tie::File> wants
1823to cache a new record, but the read cache is full, it will make room
1824by expiring the least-recently visited records from the read cache.
b5aed31e 1825
b3fe5a4c
AMS
1826The default memory limit is 2Mib. You can adjust the maximum read
1827cache size by supplying the C<memory> option. The argument is the
1828desired cache size, in bytes.
b5aed31e
AMS
1829
1830 # I have a lot of memory, so use a large cache to speed up access
b3fe5a4c 1831 tie @array, 'Tie::File', $file, memory => 20_000_000;
b5aed31e 1832
b3fe5a4c 1833Setting the memory limit to 0 will inhibit caching; records will be
b5aed31e
AMS
1834fetched from disk every time you examine them.
1835
27531ffb
JH
1836The C<memory> value is not an absolute or exact limit on the memory
1837used. C<Tie::File> objects contains some structures besides the read
1838cache and the deferred write buffer, whose sizes are not charged
1839against C<memory>.
1840
57c7bc08
AMS
1841=head2 C<dw_size>
1842
1843(This is an advanced feature. Skip this section on first reading.)
27531ffb 1844
57c7bc08
AMS
1845If you use deferred writing (See L<"Deferred Writing">, below) then
1846data you write into the array will not be written directly to the
1847file; instead, it will be saved in the I<deferred write buffer> to be
1848written out later. Data in the deferred write buffer is also charged
1849against the memory limit you set with the C<memory> option.
1850
1851You may set the C<dw_size> option to limit the amount of data that can
1852be saved in the deferred write buffer. This limit may not exceed the
1853total memory limit. For example, if you set C<dw_size> to 1000 and
1854C<memory> to 2500, that means that no more than 1000 bytes of deferred
1855writes will be saved up. The space available for the read cache will
1856vary, but it will always be at least 1500 bytes (if the deferred write
1857buffer is full) and it could grow as large as 2500 bytes (if the
1858deferred write buffer is empty.)
1859
1860If you don't specify a C<dw_size>, it defaults to the entire memory
1861limit.
1862
b5aed31e
AMS
1863=head2 Option Format
1864
1865C<-mode> is a synonym for C<mode>. C<-recsep> is a synonym for
b3fe5a4c 1866C<recsep>. C<-memory> is a synonym for C<memory>. You get the
b5aed31e
AMS
1867idea.
1868
1869=head1 Public Methods
1870
27531ffb 1871The C<tie> call returns an object, say C<$o>. You may call
b5aed31e
AMS
1872
1873 $rec = $o->FETCH($n);
1874 $o->STORE($n, $rec);
1875
b3fe5a4c
AMS
1876to fetch or store the record at line C<$n>, respectively; similarly
1877the other tied array methods. (See L<perltie> for details.) You may
1878also call the following methods on this object:
51efdd02
AMS
1879
1880=head2 C<flock>
1881
1882 $o->flock(MODE)
1883
1884will lock the tied file. C<MODE> has the same meaning as the second
1885argument to the Perl built-in C<flock> function; for example
1886C<LOCK_SH> or C<LOCK_EX | LOCK_NB>. (These constants are provided by
1887the C<use Fcntl ':flock'> declaration.)
1888
57c7bc08
AMS
1889C<MODE> is optional; the default is C<LOCK_EX>.
1890
1891C<Tie::File> promises that the following sequence of operations will
1892be safe:
1893
1894 my $o = tie @array, "Tie::File", $filename;
1895 $o->flock;
1896
1897In particular, C<Tie::File> will I<not> read or write the file during
1898the C<tie> call. (Exception: Using C<mode =E<gt> O_TRUNC> will, of
1899course, erase the file during the C<tie> call. If you want to do this
1900safely, then open the file without C<O_TRUNC>, lock the file, and use
1901C<@array = ()>.)
51efdd02
AMS
1902
1903The best way to unlock a file is to discard the object and untie the
1904array. It is probably unsafe to unlock the file without also untying
1905it, because if you do, changes may remain unwritten inside the object.
1906That is why there is no shortcut for unlocking. If you really want to
1907unlock the file prematurely, you know what to do; if you don't know
1908what to do, then don't do it.
1909
1910All the usual warnings about file locking apply here. In particular,
1911note that file locking in Perl is B<advisory>, which means that
1912holding a lock will not prevent anyone else from reading, writing, or
1913erasing the file; it only prevents them from getting another lock at
1914the same time. Locks are analogous to green traffic lights: If you
1915have a green light, that does not prevent the idiot coming the other
1916way from plowing into you sideways; it merely guarantees to you that
1917the idiot does not also have a green light at the same time.
b5aed31e 1918
0b28bc9a
AMS
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
1926See L<"autochomp">, above.
1927
6fc0ea7e 1928=head2 C<defer>, C<flush>, C<discard>, and C<autodefer>
57c7bc08
AMS
1929
1930See L<"Deferred Writing">, below.
1931
0b28bc9a 1932=head1 Tying to an already-opened filehandle
fa408a35
AMS
1933
1934If C<$fh> is a filehandle, such as is returned by C<IO::File> or one
1935of the other C<IO> modules, you may use:
1936
1937 tie @array, 'Tie::File', $fh, ...;
1938
1939Similarly if you opened that handle C<FH> with regular C<open> or
1940C<sysopen>, you may use:
1941
1942 tie @array, 'Tie::File', \*FH, ...;
1943
1944Handles that were opened write-only won't work. Handles that were
57c7bc08
AMS
1945opened read-only will work as long as you don't try to modify the
1946array. Handles must be attached to seekable sources of data---that
27531ffb
JH
1947means no pipes or sockets. If C<Tie::File> can detect that you
1948supplied a non-seekable handle, the C<tie> call will throw an
1949exception. (On Unix systems, it can detect this.)
57c7bc08
AMS
1950
1951=head1 Deferred Writing
1952
1953(This is an advanced feature. Skip this section on first reading.)
1954
1955Normally, modifying a C<Tie::File> array writes to the underlying file
1956immediately. Every assignment like C<$a[3] = ...> rewrites as much of
1957the file as is necessary; typically, everything from line 3 through
1958the end will need to be rewritten. This is the simplest and most
1959transparent behavior. Performance even for large files is reasonably
1960good.
1961
1962However, under some circumstances, this behavior may be excessively
1963slow. For example, suppose you have a million-record file, and you
1964want to do:
1965
1966 for (@FILE) {
1967 $_ = "> $_";
1968 }
1969
1970The first time through the loop, you will rewrite the entire file,
1971from line 0 through the end. The second time through the loop, you
1972will rewrite the entire file from line 1 through the end. The third
1973time through the loop, you will rewrite the entire file from line 2 to
1974the end. And so on.
1975
1976If the performance in such cases is unacceptable, you may defer the
1977actual writing, and then have it done all at once. The following loop
1978will perform much better for large files:
1979
1980 (tied @a)->defer;
1981 for (@a) {
1982 $_ = "> $_";
1983 }
1984 (tied @a)->flush;
1985
1986If C<Tie::File>'s memory limit is large enough, all the writing will
1987done in memory. Then, when you call C<-E<gt>flush>, the entire file
1988will be rewritten in a single pass.
1989
6fc0ea7e
JH
1990(Actually, the preceding discussion is something of a fib. You don't
1991need to enable deferred writing to get good performance for this
1992common case, because C<Tie::File> will do it for you automatically
1993unless you specifically tell it not to. See L<"autodeferring">,
1994below.)
1995
57c7bc08
AMS
1996Calling C<-E<gt>flush> returns the array to immediate-write mode. If
1997you wish to discard the deferred writes, you may call C<-E<gt>discard>
1998instead of C<-E<gt>flush>. Note that in some cases, some of the data
1999will have been written already, and it will be too late for
6fc0ea7e
JH
2000C<-E<gt>discard> to discard all the changes. Support for
2001C<-E<gt>discard> may be withdrawn in a future version of C<Tie::File>.
57c7bc08
AMS
2002
2003Deferred writes are cached in memory up to the limit specified by the
2004C<dw_size> option (see above). If the deferred-write buffer is full
2005and you try to write still more deferred data, the buffer will be
2006flushed. All buffered data will be written immediately, the buffer
2007will be emptied, and the now-empty space will be used for future
2008deferred writes.
2009
2010If the deferred-write buffer isn't yet full, but the total size of the
2011buffer and the read cache would exceed the C<memory> limit, the oldest
27531ffb 2012records will be expired from the read cache until the total size is
57c7bc08
AMS
2013under the limit.
2014
2015C<push>, C<pop>, C<shift>, C<unshift>, and C<splice> cannot be
2016deferred. When you perform one of these operations, any deferred data
2017is written to the file and the operation is performed immediately.
2018This may change in a future version.
2019
6fc0ea7e
JH
2020If you resize the array with deferred writing enabled, the file will
2021be resized immediately, but deferred records will not be written.
27531ffb
JH
2022This has a surprising consequence: C<@a = (...)> erases the file
2023immediately, but the writing of the actual data is deferred. This
2024might be a bug. If it is a bug, it will be fixed in a future version.
6fc0ea7e
JH
2025
2026=head2 Autodeferring
2027
2028C<Tie::File> tries to guess when deferred writing might be helpful,
27531ffb
JH
2029and to turn it on and off automatically.
2030
2031 for (@a) {
2032 $_ = "> $_";
2033 }
2034
2035In this example, only the first two assignments will be done
2036immediately; after this, all the changes to the file will be deferred
2037up to the user-specified memory limit.
6fc0ea7e
JH
2038
2039You should usually be able to ignore this and just use the module
2040without thinking about deferring. However, special applications may
2041require fine control over which writes are deferred, or may require
2042that all writes be immediate. To disable the autodeferment feature,
2043use
57c7bc08
AMS
2044
2045 (tied @o)->autodefer(0);
2046
6fc0ea7e
JH
2047or
2048
2049 tie @array, 'Tie::File', $file, autodefer => 0;
2050
fa408a35 2051
27531ffb
JH
2052Similarly, C<-E<gt>autodefer(1)> re-enables autodeferment, and
2053C<-E<gt>autodefer()> recovers the current value of the autodefer setting.
2054
b5aed31e
AMS
2055=head1 CAVEATS
2056
2057(That's Latin for 'warnings'.)
2058
b3fe5a4c
AMS
2059=over 4
2060
2061=item *
2062
2063This is BETA RELEASE SOFTWARE. It may have bugs. See the discussion
2064below about the (lack of any) warranty.
2065
6fc0ea7e
JH
2066In particular, this means that the interface may change in
2067incompatible ways from one version to the next, without warning. That
2068has happened at least once already. The interface will freeze before
2069Perl 5.8 is released, probably sometime in April 2002.
2070
27531ffb 2071=item *
b5aed31e 2072
6fc0ea7e 2073Reasonable effort was made to make this module efficient. Nevertheless,
b5aed31e 2074changing the size of a record in the middle of a large file will
b3fe5a4c
AMS
2075always be fairly slow, because everything after the new record must be
2076moved.
b5aed31e 2077
b3fe5a4c
AMS
2078=item *
2079
2080The behavior of tied arrays is not precisely the same as for regular
2081arrays. For example:
b5aed31e 2082
57c7bc08
AMS
2083 # This DOES print "How unusual!"
2084 undef $a[10]; print "How unusual!\n" if defined $a[10];
b3fe5a4c
AMS
2085
2086C<undef>-ing a C<Tie::File> array element just blanks out the
2087corresponding record in the file. When you read it back again, you'll
57c7bc08
AMS
2088get the empty string, so the supposedly-C<undef>'ed value will be
2089defined. Similarly, if you have C<autochomp> disabled, then
2090
2091 # This DOES print "How unusual!" if 'autochomp' is disabled
27531ffb 2092 undef $a[10];
57c7bc08
AMS
2093 print "How unusual!\n" if $a[10];
2094
2095Because when C<autochomp> is disabled, C<$a[10]> will read back as
2096C<"\n"> (or whatever the record separator string is.)
b5aed31e 2097
6fc0ea7e
JH
2098There are other minor differences, particularly regarding C<exists>
2099and C<delete>, but in general, the correspondence is extremely close.
b3fe5a4c
AMS
2100
2101=item *
2102
2103Not quite every effort was made to make this module as efficient as
b5aed31e 2104possible. C<FETCHSIZE> should use binary search instead of linear
27531ffb 2105search.
57c7bc08
AMS
2106
2107The performance of the C<flush> method could be improved. At present,
2108it still rewrites the tail of the file once for each block of
2109contiguous lines to be changed. In the typical case, this will result
2110in only one rewrite, but in peculiar cases it might be bad. It should
2111be possible to perform I<all> deferred writing with a single rewrite.
2112
27531ffb
JH
2113Profiling suggests that these defects are probably minor; in any
2114event, they will be fixed in a future version of the module.
b5aed31e 2115
b3fe5a4c 2116=item *
b5aed31e 2117
27531ffb
JH
2118I have supposed that since this module is concerned with file I/O,
2119almost all normal use of it will be heavily I/O bound. This means
2120that the time to maintain complicated data structures inside the
2121module will be dominated by the time to actually perform the I/O.
2122When there was an opportunity to spend CPU time to avoid doing I/O, I
2123tried to take it.
b5aed31e 2124
57c7bc08 2125=item *
6fc0ea7e 2126
57c7bc08
AMS
2127You might be tempted to think that deferred writing is like
2128transactions, with C<flush> as C<commit> and C<discard> as
6fc0ea7e 2129C<rollback>, but it isn't, so don't.
57c7bc08 2130
b3fe5a4c 2131=back
51efdd02 2132
57c7bc08
AMS
2133=head1 SUBCLASSING
2134
2135This version promises absolutely nothing about the internals, which
2136may change without notice. A future version of the module will have a
2137well-defined and stable subclassing API.
2138
b3fe5a4c 2139=head1 WHAT ABOUT C<DB_File>?
51efdd02 2140
27531ffb
JH
2141People sometimes point out that L<DB_File> will do something similar,
2142and ask why C<Tie::File> module is necessary.
b3fe5a4c 2143
27531ffb
JH
2144There are a number of reasons that you might prefer C<Tie::File>.
2145A list is available at C<http://perl.plover.com/TieFile/why-not-DB_File>.
b5aed31e
AMS
2146
2147=head1 AUTHOR
2148
2149Mark Jason Dominus
2150
2151To contact the author, send email to: C<mjd-perl-tiefile+@plover.com>
2152
2153To receive an announcement whenever a new version of this module is
2154released, send a blank email message to
2155C<mjd-perl-tiefile-subscribe@plover.com>.
2156
57c7bc08
AMS
2157The most recent version of this module, including documentation and
2158any news of importance, will be available at
2159
2160 http://perl.plover.com/TieFile/
2161
2162
b5aed31e
AMS
2163=head1 LICENSE
2164
0bf62e3b 2165C<Tie::File> version 0.93 is copyright (C) 2002 Mark Jason Dominus.
7b6b3db1
JH
2166
2167This library is free software; you may redistribute it and/or modify
2168it under the same terms as Perl itself.
b5aed31e 2169
57c7bc08
AMS
2170These terms are your choice of any of (1) the Perl Artistic Licence,
2171or (2) version 2 of the GNU General Public License as published by the
7b6b3db1
JH
2172Free Software Foundation, or (3) any later version of the GNU General
2173Public License.
b5aed31e 2174
7b6b3db1 2175This library is distributed in the hope that it will be useful,
b5aed31e
AMS
2176but WITHOUT ANY WARRANTY; without even the implied warranty of
2177MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2178GNU General Public License for more details.
2179
2180You should have received a copy of the GNU General Public License
7b6b3db1
JH
2181along with this library program; it should be in the file C<COPYING>.
2182If not, write to the Free Software Foundation, Inc., 59 Temple Place,
2183Suite 330, Boston, MA 02111 USA
b5aed31e
AMS
2184
2185For 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
0bf62e3b 2193C<Tie::File> version 0.93 comes with ABSOLUTELY NO WARRANTY.
b5aed31e
AMS
2194For details, see the license.
2195
fa408a35
AMS
2196=head1 THANKS
2197
2198Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the
2199core when I hadn't written it yet, and for generally being helpful,
2200supportive, and competent. (Usually the rule is "choose any one.")
2201Also big thanks to Abhijit Menon-Sen for all of the same things.
2202
57c7bc08
AMS
2203Special thanks to Craig Berry and Peter Prymmer (for VMS portability
2204help), Randy Kobes (for Win32 portability help), Clinton Pierce and
2205Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond
6fc0ea7e
JH
2206the call of duty), Michael G Schwern (for testing advice), and the
2207rest of the CPAN testers (for testing generally).
b5aed31e 2208
57c7bc08 2209Additional thanks to:
b3fe5a4c 2210Edward Avis /
fa408a35 2211Gerrit Haase /
b3fe5a4c 2212Nikola Knezevic /
836d9961 2213Nick Ing-Simmons /
fa408a35
AMS
2214Tassilo von Parseval /
2215H. Dieter Pearcey /
b3fe5a4c 2216Slaven Rezic /
6fc0ea7e 2217Peter Scott /
fa408a35 2218Peter Somu /
57c7bc08 2219Autrijus Tang (again) /
27531ffb
JH
2220Tels /
2221Juerd Wallboer
7b6b3db1 2222
fa408a35
AMS
2223=head1 TODO
2224
27531ffb 2225More tests. (The cache and heap modules need more unit tests.)
b5aed31e 2226
6fc0ea7e 2227Improve SPLICE algorithm to use deferred writing machinery.
b5aed31e 2228
27531ffb
JH
2229Cleverer strategy for flushing deferred writes.
2230
b5aed31e
AMS
2231More tests. (Stuff I didn't think of yet.)
2232
b5aed31e
AMS
2233Paragraph mode?
2234
6fc0ea7e 2235Fixed-length mode. Leave-blanks mode.
b5aed31e 2236
fa408a35
AMS
2237Maybe an autolocking mode?
2238
6fc0ea7e
JH
2239Record locking with fcntl()? Then the module might support an undo
2240log and get real transactions. What a tour de force that would be.
b3fe5a4c 2241
27531ffb 2242More tests.
b3fe5a4c 2243
b5aed31e
AMS
2244=cut
2245