Added tests for storing tied stuff
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep / Engine.pm
1 package DBM::Deep::Engine;
2
3 use strict;
4
5 use Fcntl qw( :DEFAULT :flock :seek );
6
7 ##
8 # Setup file and tag signatures.  These should never change.
9 ##
10 sub SIG_FILE     () { 'DPDB' }
11 sub SIG_INTERNAL () { 'i'    }
12 sub SIG_HASH     () { 'H'    }
13 sub SIG_ARRAY    () { 'A'    }
14 sub SIG_NULL     () { 'N'    }
15 sub SIG_DATA     () { 'D'    }
16 sub SIG_INDEX    () { 'I'    }
17 sub SIG_BLIST    () { 'B'    }
18 sub SIG_FREE     () { 'F'    }
19 sub SIG_SIZE     () {  1     }
20
21 sub precalc_sizes {
22     ##
23     # Precalculate index, bucket and bucket list sizes
24     ##
25     my $self = shift;
26
27     $self->{index_size}       = (2**8) * $self->{long_size};
28     $self->{bucket_size}      = $self->{hash_size} + $self->{long_size} * 2;
29     $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
30
31     return 1;
32 }
33
34 sub set_pack {
35     ##
36     # Set pack/unpack modes (see file header for more)
37     ##
38     my $self = shift;
39     my ($long_s, $long_p, $data_s, $data_p) = @_;
40
41     ##
42     # Set to 4 and 'N' for 32-bit offset tags (default).  Theoretical limit of 4
43     # GB per file.
44     #    (Perl must be compiled with largefile support for files > 2 GB)
45     #
46     # Set to 8 and 'Q' for 64-bit offsets.  Theoretical limit of 16 XB per file.
47     #    (Perl must be compiled with largefile and 64-bit long support)
48     ##
49     $self->{long_size} = $long_s ? $long_s : 4;
50     $self->{long_pack} = $long_p ? $long_p : 'N';
51
52     ##
53     # Set to 4 and 'N' for 32-bit data length prefixes.  Limit of 4 GB for each
54     # key/value. Upgrading this is possible (see above) but probably not
55     # necessary. If you need more than 4 GB for a single key or value, this
56     # module is really not for you :-)
57     ##
58     $self->{data_size} = $data_s ? $data_s : 4;
59     $self->{data_pack} = $data_p ? $data_p : 'N';
60
61     return $self->precalc_sizes();
62 }
63
64 sub set_digest {
65     ##
66     # Set key digest function (default is MD5)
67     ##
68     my $self = shift;
69     my ($digest_func, $hash_size) = @_;
70
71     $self->{digest} = $digest_func ? $digest_func : \&Digest::MD5::md5;
72     $self->{hash_size} = $hash_size ? $hash_size : 16;
73
74     return $self->precalc_sizes();
75 }
76
77 sub new {
78     my $class = shift;
79     my ($args) = @_;
80
81     my $self = bless {
82         long_size   => 4,
83         long_pack   => 'N',
84         data_size   => 4,
85         data_pack   => 'N',
86
87         digest      => \&Digest::MD5::md5,
88         hash_size   => 16,
89
90         ##
91         # Maximum number of buckets per list before another level of indexing is
92         # done.
93         # Increase this value for slightly greater speed, but larger database
94         # files. DO NOT decrease this value below 16, due to risk of recursive
95         # reindex overrun.
96         ##
97         max_buckets => 16,
98     }, $class;
99
100     $self->precalc_sizes;
101
102     return $self;
103 }
104
105 sub setup_fh {
106     my $self = shift;
107     my ($obj) = @_;
108
109     $self->open( $obj ) if !defined $obj->_fh;
110
111     my $fh = $obj->_fh;
112     flock $fh, LOCK_EX;
113
114     unless ( $obj->{base_offset} ) {
115         seek($fh, 0 + $obj->_root->{file_offset}, SEEK_SET);
116         my $signature;
117         my $bytes_read = read( $fh, $signature, length(SIG_FILE));
118
119         ##
120         # File is empty -- write signature and master index
121         ##
122         if (!$bytes_read) {
123             my $loc = $self->_request_space( $obj, length( SIG_FILE ) );
124             seek($fh, $loc + $obj->_root->{file_offset}, SEEK_SET);
125             print( $fh SIG_FILE);
126
127             $obj->{base_offset} = $self->_request_space(
128                 $obj, $self->tag_size( $self->{index_size} ),
129             );
130
131             $self->write_tag(
132                 $obj, $obj->_base_offset, $obj->_type,
133                 chr(0)x$self->{index_size},
134             );
135
136             # Flush the filehandle
137             my $old_fh = select $fh;
138             my $old_af = $|; $| = 1; $| = $old_af;
139             select $old_fh;
140         }
141         else {
142             $obj->{base_offset} = $bytes_read;
143
144             ##
145             # Check signature was valid
146             ##
147             unless ($signature eq SIG_FILE) {
148                 $self->close_fh( $obj );
149                 $obj->_throw_error("Signature not found -- file is not a Deep DB");
150             }
151
152             ##
153             # Get our type from master index signature
154             ##
155             my $tag = $self->load_tag($obj, $obj->_base_offset)
156             or $obj->_throw_error("Corrupted file, no master index record");
157
158             unless ($obj->{type} eq $tag->{signature}) {
159                 $obj->_throw_error("File type mismatch");
160             }
161         }
162     }
163
164     #XXX We have to make sure we don't mess up when autoflush isn't turned on
165     unless ( $obj->_root->{inode} ) {
166         my @stats = stat($obj->_fh);
167         $obj->_root->{inode} = $stats[1];
168         $obj->_root->{end} = $stats[7];
169     }
170
171     flock $fh, LOCK_UN;
172
173     return 1;
174 }
175
176 sub open {
177     ##
178     # Open a fh to the database, create if nonexistent.
179     # Make sure file signature matches DBM::Deep spec.
180     ##
181     my $self = shift;
182     my ($obj) = @_;
183
184     # Theoretically, adding O_BINARY should remove the need for the binmode
185     # Of course, testing it is going to be ... interesting.
186     my $flags = O_RDWR | O_CREAT | O_BINARY;
187
188     my $fh;
189     my $filename = $obj->_root->{file};
190     sysopen( $fh, $filename, $flags )
191         or $obj->_throw_error("Cannot sysopen file '$filename': $!");
192     $obj->_root->{fh} = $fh;
193
194     #XXX Can we remove this by using the right sysopen() flags?
195     # Maybe ... q.v. above
196     binmode $fh; # for win32
197
198     if ($obj->_root->{autoflush}) {
199         my $old = select $fh;
200         $|=1;
201         select $old;
202     }
203
204     return 1;
205 }
206
207 sub close_fh {
208     my $self = shift;
209     my ($obj) = @_;
210
211     if ( my $fh = $obj->_root->{fh} ) {
212         close $fh;
213     }
214     $obj->_root->{fh} = undef;
215
216     return 1;
217 }
218
219 sub tag_size {
220     my $self = shift;
221     my ($size) = @_;
222     return SIG_SIZE + $self->{data_size} + $size;
223 }
224
225 sub write_tag {
226     ##
227     # Given offset, signature and content, create tag and write to disk
228     ##
229     my $self = shift;
230     my ($obj, $offset, $sig, $content) = @_;
231     my $size = length( $content );
232
233     my $fh = $obj->_fh;
234
235     if ( defined $offset ) {
236         seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
237     }
238
239     print( $fh $sig . pack($self->{data_pack}, $size) . $content );
240
241     return unless defined $offset;
242
243     return {
244         signature => $sig,
245         size => $size,
246         offset => $offset + SIG_SIZE + $self->{data_size},
247         content => $content
248     };
249 }
250
251 sub load_tag {
252     ##
253     # Given offset, load single tag and return signature, size and data
254     ##
255     my $self = shift;
256     my ($obj, $offset) = @_;
257
258 #    print join(':',map{$_||''}caller(1)), $/;
259
260     my $fh = $obj->_fh;
261
262     seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
263
264     #XXX I'm not sure this check will work if autoflush isn't enabled ...
265     return if eof $fh;
266
267     my $b;
268     read( $fh, $b, SIG_SIZE + $self->{data_size} );
269     my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
270
271     my $buffer;
272     read( $fh, $buffer, $size);
273
274     return {
275         signature => $sig,
276         size => $size,
277         offset => $offset + SIG_SIZE + $self->{data_size},
278         content => $buffer
279     };
280 }
281
282 sub _length_needed {
283     my $self = shift;
284     my ($obj, $value, $key) = @_;
285
286     my $is_dbm_deep = eval {
287         local $SIG{'__DIE__'};
288         $value->isa( 'DBM::Deep' );
289     };
290
291     my $len = SIG_SIZE + $self->{data_size}
292             + $self->{data_size} + length( $key );
293
294     if ( $is_dbm_deep && $value->_root eq $obj->_root ) {
295         return $len + $self->{long_size};
296     }
297
298     my $r = Scalar::Util::reftype( $value ) || '';
299     if ( $obj->_root->{autobless} ) {
300         # This is for the bit saying whether or not this thing is blessed.
301         $len += 1;
302     }
303
304     unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
305         if ( defined $value ) {
306             $len += length( $value );
307         }
308         return $len;
309     }
310
311     $len += $self->{index_size};
312
313     # if autobless is enabled, must also take into consideration
314     # the class name as it is stored after the key.
315     if ( $obj->_root->{autobless} ) {
316         my $value_class = Scalar::Util::blessed($value);
317         if ( defined $value_class && !$is_dbm_deep ) {
318             $len += $self->{data_size} + length($value_class);
319         }
320     }
321
322     return $len;
323 }
324
325 sub add_bucket {
326     ##
327     # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
328     # plain (undigested) key and value.
329     ##
330     my $self = shift;
331     my ($obj, $tag, $md5, $plain_key, $value) = @_;
332
333     # This verifies that only supported values will be stored.
334     {
335         my $r = Scalar::Util::reftype( $value );
336         last if !defined $r;
337
338         last if $r eq 'HASH';
339         last if $r eq 'ARRAY';
340
341         $obj->_throw_error(
342             "Storage of variables of type '$r' is not supported."
343         );
344     }
345
346     my $location = 0;
347     my $result = 2;
348
349     my $root = $obj->_root;
350     my $fh   = $obj->_fh;
351
352     my $actual_length = $self->_length_needed( $obj, $value, $plain_key );
353
354     my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
355
356 #    $self->_release_space( $obj, $size, $subloc );
357     # Updating a known md5
358 #XXX This needs updating to use _release_space
359     if ( $subloc ) {
360         $result = 1;
361
362         if ($actual_length <= $size) {
363             $location = $subloc;
364         }
365         else {
366             $location = $self->_request_space( $obj, $actual_length );
367             seek(
368                 $fh,
369                 $tag->{offset} + $offset
370               + $self->{hash_size} + $root->{file_offset},
371                 SEEK_SET,
372             );
373             print( $fh pack($self->{long_pack}, $location ) );
374             print( $fh pack($self->{long_pack}, $actual_length ) );
375         }
376     }
377     # Adding a new md5
378     elsif ( defined $offset ) {
379         $location = $self->_request_space( $obj, $actual_length );
380
381         seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
382         print( $fh $md5 . pack($self->{long_pack}, $location ) );
383         print( $fh pack($self->{long_pack}, $actual_length ) );
384     }
385     # If bucket didn't fit into list, split into a new index level
386     # split_index() will do the _request_space() call
387     else {
388         $location = $self->split_index( $obj, $md5, $tag );
389     }
390
391     $self->write_value( $obj, $location, $plain_key, $value );
392
393     return $result;
394 }
395
396 sub write_value {
397     my $self = shift;
398     my ($obj, $location, $key, $value) = @_;
399
400     my $fh = $obj->_fh;
401     my $root = $obj->_root;
402
403     my $is_dbm_deep = eval {
404         local $SIG{'__DIE__'};
405         $value->isa( 'DBM::Deep' );
406     };
407
408     my $is_internal_ref = $is_dbm_deep && ($value->_root eq $root);
409
410     seek($fh, $location + $root->{file_offset}, SEEK_SET);
411
412     ##
413     # Write signature based on content type, set content length and write
414     # actual value.
415     ##
416     my $r = Scalar::Util::reftype($value) || '';
417     if ( $is_internal_ref ) {
418         $self->write_tag( $obj, undef, SIG_INTERNAL,pack($self->{long_pack}, $value->_base_offset) );
419     }
420     elsif ($r eq 'HASH') {
421         if ( tied( %{$value} ) ) {
422             $obj->_throw_error( "Cannot store something that is tied" );
423         }
424         $self->write_tag( $obj, undef, SIG_HASH, chr(0)x$self->{index_size} );
425     }
426     elsif ($r eq 'ARRAY') {
427         if ( tied( @{$value} ) ) {
428             $obj->_throw_error( "Cannot store something that is tied" );
429         }
430         $self->write_tag( $obj, undef, SIG_ARRAY, chr(0)x$self->{index_size} );
431     }
432     elsif (!defined($value)) {
433         $self->write_tag( $obj, undef, SIG_NULL, '' );
434     }
435     else {
436         $self->write_tag( $obj, undef, SIG_DATA, $value );
437     }
438
439     ##
440     # Plain key is stored AFTER value, as keys are typically fetched less often.
441     ##
442     print( $fh pack($self->{data_pack}, length($key)) . $key );
443
444     # Internal references don't care about autobless
445     return 1 if $is_internal_ref;
446
447     ##
448     # If value is blessed, preserve class name
449     ##
450     if ( $root->{autobless} ) {
451         my $value_class = Scalar::Util::blessed($value);
452         if ( defined $value_class && !$is_dbm_deep ) {
453             print( $fh chr(1) );
454             print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
455         }
456         else {
457             print( $fh chr(0) );
458         }
459     }
460
461     ##
462     # If content is a hash or array, create new child DBM::Deep object and
463     # pass each key or element to it.
464     ##
465     if ( !$is_internal_ref ) {
466         if ($r eq 'HASH') {
467             my $branch = DBM::Deep->new(
468                 type => DBM::Deep->TYPE_HASH,
469                 base_offset => $location,
470                 root => $root,
471             );
472             foreach my $key (keys %{$value}) {
473                 $branch->STORE( $key, $value->{$key} );
474             }
475         }
476         elsif ($r eq 'ARRAY') {
477             my $branch = DBM::Deep->new(
478                 type => DBM::Deep->TYPE_ARRAY,
479                 base_offset => $location,
480                 root => $root,
481             );
482             my $index = 0;
483             foreach my $element (@{$value}) {
484                 $branch->STORE( $index, $element );
485                 $index++;
486             }
487         }
488     }
489
490     return 1;
491 }
492
493 sub split_index {
494     my $self = shift;
495     my ($obj, $md5, $tag) = @_;
496
497     my $fh = $obj->_fh;
498     my $root = $obj->_root;
499
500     my $loc = $self->_request_space(
501         $obj, $self->tag_size( $self->{index_size} ),
502     );
503
504     seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
505     print( $fh pack($self->{long_pack}, $loc) );
506
507     my $index_tag = $self->write_tag(
508         $obj, $loc, SIG_INDEX,
509         chr(0)x$self->{index_size},
510     );
511
512     my $newtag_loc = $self->_request_space(
513         $obj, $self->tag_size( $self->{bucket_list_size} ),
514     );
515
516     my $keys = $tag->{content}
517              . $md5 . pack($self->{long_pack}, $newtag_loc)
518                     . pack($self->{long_pack}, 0);
519
520     my @newloc = ();
521     BUCKET:
522     for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
523         my ($key, $old_subloc, $size) = $self->_get_key_subloc( $keys, $i );
524
525         die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
526         die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
527
528         my $num = ord(substr($key, $tag->{ch} + 1, 1));
529
530         if ($newloc[$num]) {
531             seek($fh, $newloc[$num] + $root->{file_offset}, SEEK_SET);
532             my $subkeys;
533             read( $fh, $subkeys, $self->{bucket_list_size});
534
535             # This is looking for the first empty spot
536             my ($subloc, $offset, $size) = $self->_find_in_buckets(
537                 { content => $subkeys }, '',
538             );
539
540             seek($fh, $newloc[$num] + $offset + $root->{file_offset}, SEEK_SET);
541             print( $fh $key . pack($self->{long_pack}, $old_subloc) );
542
543             next;
544         }
545
546         seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
547
548         my $loc = $self->_request_space(
549             $obj, $self->tag_size( $self->{bucket_list_size} ),
550         );
551
552         print( $fh pack($self->{long_pack}, $loc) );
553
554         my $blist_tag = $self->write_tag(
555             $obj, $loc, SIG_BLIST,
556             chr(0)x$self->{bucket_list_size},
557         );
558
559         seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
560         print( $fh $key . pack($self->{long_pack}, $old_subloc) );
561
562         $newloc[$num] = $blist_tag->{offset};
563     }
564
565     $self->_release_space(
566         $obj, $self->tag_size( $self->{bucket_list_size} ),
567         $tag->{offset} - SIG_SIZE - $self->{data_size},
568     );
569
570     return $newtag_loc;
571 }
572
573 sub read_from_loc {
574     my $self = shift;
575     my ($obj, $subloc) = @_;
576
577     my $fh = $obj->_fh;
578
579     ##
580     # Found match -- seek to offset and read signature
581     ##
582     my $signature;
583     seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
584     read( $fh, $signature, SIG_SIZE);
585
586     ##
587     # If value is a hash or array, return new DBM::Deep object with correct offset
588     ##
589     if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
590         my $obj = DBM::Deep->new(
591             type => $signature,
592             base_offset => $subloc,
593             root => $obj->_root,
594         );
595
596         if ($obj->_root->{autobless}) {
597             ##
598             # Skip over value and plain key to see if object needs
599             # to be re-blessed
600             ##
601             seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
602
603             my $size;
604             read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
605             if ($size) { seek($fh, $size, SEEK_CUR); }
606
607             my $bless_bit;
608             read( $fh, $bless_bit, 1);
609             if (ord($bless_bit)) {
610                 ##
611                 # Yes, object needs to be re-blessed
612                 ##
613                 my $class_name;
614                 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
615                 if ($size) { read( $fh, $class_name, $size); }
616                 if ($class_name) { $obj = bless( $obj, $class_name ); }
617             }
618         }
619
620         return $obj;
621     }
622     elsif ( $signature eq SIG_INTERNAL ) {
623         my $size;
624         read( $fh, $size, $self->{data_size});
625         $size = unpack($self->{data_pack}, $size);
626
627         if ( $size ) {
628             my $new_loc;
629             read( $fh, $new_loc, $size );
630             $new_loc = unpack( $self->{long_pack}, $new_loc );
631
632             return $self->read_from_loc( $obj, $new_loc );
633         }
634         else {
635             return;
636         }
637     }
638     ##
639     # Otherwise return actual value
640     ##
641     elsif ($signature eq SIG_DATA) {
642         my $size;
643         read( $fh, $size, $self->{data_size});
644         $size = unpack($self->{data_pack}, $size);
645
646         my $value = '';
647         if ($size) { read( $fh, $value, $size); }
648         return $value;
649     }
650
651     ##
652     # Key exists, but content is null
653     ##
654     return;
655 }
656
657 sub get_bucket_value {
658     ##
659     # Fetch single value given tag and MD5 digested key.
660     ##
661     my $self = shift;
662     my ($obj, $tag, $md5) = @_;
663
664     my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
665     if ( $subloc ) {
666         return $self->read_from_loc( $obj, $subloc );
667     }
668     return;
669 }
670
671 sub delete_bucket {
672     ##
673     # Delete single key/value pair given tag and MD5 digested key.
674     ##
675     my $self = shift;
676     my ($obj, $tag, $md5) = @_;
677
678     my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
679 #XXX This needs _release_space()
680     if ( $subloc ) {
681         my $fh = $obj->_fh;
682         seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
683         print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
684         print( $fh chr(0) x $self->{bucket_size} );
685
686         return 1;
687     }
688     return;
689 }
690
691 sub bucket_exists {
692     ##
693     # Check existence of single key given tag and MD5 digested key.
694     ##
695     my $self = shift;
696     my ($obj, $tag, $md5) = @_;
697
698     my ($subloc, $offset, $size) = $self->_find_in_buckets( $tag, $md5 );
699     return $subloc && 1;
700 }
701
702 sub find_bucket_list {
703     ##
704     # Locate offset for bucket list, given digested key
705     ##
706     my $self = shift;
707     my ($obj, $md5, $args) = @_;
708     $args = {} unless $args;
709
710     ##
711     # Locate offset for bucket list using digest index system
712     ##
713     my $tag = $self->load_tag($obj, $obj->_base_offset)
714         or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
715
716     my $ch = 0;
717     while ($tag->{signature} ne SIG_BLIST) {
718         my $num = ord substr($md5, $ch, 1);
719
720         my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
721         $tag = $self->index_lookup( $obj, $tag, $num );
722
723         if (!$tag) {
724             return if !$args->{create};
725
726             my $loc = $self->_request_space(
727                 $obj, $self->tag_size( $self->{bucket_list_size} ),
728             );
729
730             my $fh = $obj->_fh;
731             seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
732             print( $fh pack($self->{long_pack}, $loc) );
733
734             $tag = $self->write_tag(
735                 $obj, $loc, SIG_BLIST,
736                 chr(0)x$self->{bucket_list_size},
737             );
738
739             $tag->{ref_loc} = $ref_loc;
740             $tag->{ch} = $ch;
741
742             last;
743         }
744
745         $tag->{ch} = $ch++;
746         $tag->{ref_loc} = $ref_loc;
747     }
748
749     return $tag;
750 }
751
752 sub index_lookup {
753     ##
754     # Given index tag, lookup single entry in index and return .
755     ##
756     my $self = shift;
757     my ($obj, $tag, $index) = @_;
758
759     my $location = unpack(
760         $self->{long_pack},
761         substr(
762             $tag->{content},
763             $index * $self->{long_size},
764             $self->{long_size},
765         ),
766     );
767
768     if (!$location) { return; }
769
770     return $self->load_tag( $obj, $location );
771 }
772
773 sub traverse_index {
774     ##
775     # Scan index and recursively step into deeper levels, looking for next key.
776     ##
777     my $self = shift;
778     my ($obj, $offset, $ch, $force_return_next) = @_;
779
780     my $tag = $self->load_tag($obj, $offset );
781
782     my $fh = $obj->_fh;
783
784     if ($tag->{signature} ne SIG_BLIST) {
785         my $content = $tag->{content};
786         my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
787
788         for (my $idx = $start; $idx < (2**8); $idx++) {
789             my $subloc = unpack(
790                 $self->{long_pack},
791                 substr(
792                     $content,
793                     $idx * $self->{long_size},
794                     $self->{long_size},
795                 ),
796             );
797
798             if ($subloc) {
799                 my $result = $self->traverse_index(
800                     $obj, $subloc, $ch + 1, $force_return_next,
801                 );
802
803                 if (defined($result)) { return $result; }
804             }
805         } # index loop
806
807         $obj->{return_next} = 1;
808     } # tag is an index
809
810     else {
811         my $keys = $tag->{content};
812         if ($force_return_next) { $obj->{return_next} = 1; }
813
814         ##
815         # Iterate through buckets, looking for a key match
816         ##
817         for (my $i = 0; $i < $self->{max_buckets}; $i++) {
818             my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
819
820             # End of bucket list -- return to outer loop
821             if (!$subloc) {
822                 $obj->{return_next} = 1;
823                 last;
824             }
825             # Located previous key -- return next one found
826             elsif ($key eq $obj->{prev_md5}) {
827                 $obj->{return_next} = 1;
828                 next;
829             }
830             # Seek to bucket location and skip over signature
831             elsif ($obj->{return_next}) {
832                 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
833
834                 # Skip over value to get to plain key
835                 my $sig;
836                 read( $fh, $sig, SIG_SIZE );
837
838                 my $size;
839                 read( $fh, $size, $self->{data_size});
840                 $size = unpack($self->{data_pack}, $size);
841                 if ($size) { seek($fh, $size, SEEK_CUR); }
842
843                 # Read in plain key and return as scalar
844                 my $plain_key;
845                 read( $fh, $size, $self->{data_size});
846                 $size = unpack($self->{data_pack}, $size);
847                 if ($size) { read( $fh, $plain_key, $size); }
848
849                 return $plain_key;
850             }
851         }
852
853         $obj->{return_next} = 1;
854     } # tag is a bucket list
855
856     return;
857 }
858
859 sub get_next_key {
860     ##
861     # Locate next key, given digested previous one
862     ##
863     my $self = shift;
864     my ($obj) = @_;
865
866     $obj->{prev_md5} = $_[1] ? $_[1] : undef;
867     $obj->{return_next} = 0;
868
869     ##
870     # If the previous key was not specifed, start at the top and
871     # return the first one found.
872     ##
873     if (!$obj->{prev_md5}) {
874         $obj->{prev_md5} = chr(0) x $self->{hash_size};
875         $obj->{return_next} = 1;
876     }
877
878     return $self->traverse_index( $obj, $obj->_base_offset, 0 );
879 }
880
881 # Utilities
882
883 sub _get_key_subloc {
884     my $self = shift;
885     my ($keys, $idx) = @_;
886
887     my ($key, $subloc, $size) = unpack(
888         "a$self->{hash_size} $self->{long_pack} $self->{long_pack}",
889         substr(
890             $keys,
891             ($idx * $self->{bucket_size}),
892             $self->{bucket_size},
893         ),
894     );
895
896     return ($key, $subloc, $size);
897 }
898
899 sub _find_in_buckets {
900     my $self = shift;
901     my ($tag, $md5) = @_;
902
903     BUCKET:
904     for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
905         my ($key, $subloc, $size) = $self->_get_key_subloc(
906             $tag->{content}, $i,
907         );
908
909         return ($subloc, $i * $self->{bucket_size}, $size) unless $subloc;
910
911         next BUCKET if $key ne $md5;
912
913         return ($subloc, $i * $self->{bucket_size}, $size);
914     }
915
916     return;
917 }
918
919 #sub _print_at {
920 #    my $self = shift;
921 #    my ($obj, $spot, $data) = @_;
922 #
923 #    my $fh = $obj->_fh;
924 #    seek( $fh, $spot, SEEK_SET );
925 #    print( $fh $data );
926 #
927 #    return;
928 #}
929
930 sub _request_space {
931     my $self = shift;
932     my ($obj, $size) = @_;
933
934     my $loc = $obj->_root->{end};
935     $obj->_root->{end} += $size;
936
937     return $loc;
938 }
939
940 sub _release_space {
941     my $self = shift;
942     my ($obj, $size, $loc) = @_;
943
944     my $next_loc = 0;
945
946     my $fh = $obj->_fh;
947     seek( $fh, $loc + $obj->_root->{file_offset}, SEEK_SET );
948     print( $fh SIG_FREE
949         . pack($self->{long_pack}, $size )
950         . pack($self->{long_pack}, $next_loc )
951     );
952
953     return;
954 }
955
956 1;
957 __END__
958
959 # This will be added in later, after more refactoring is done. This is an early
960 # attempt at refactoring on the physical level instead of the virtual level.
961 sub _read_at {
962     my $self = shift;
963     my ($obj, $spot, $amount, $unpack) = @_;
964
965     my $fh = $obj->_fh;
966     seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
967
968     my $buffer;
969     my $bytes_read = read( $fh, $buffer, $amount );
970
971     if ( $unpack ) {
972         $buffer = unpack( $unpack, $buffer );
973     }
974
975     if ( wantarray ) {
976         return ($buffer, $bytes_read);
977     }
978     else {
979         return $buffer;
980     }
981 }