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