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