3bf57c0ba2dba967a50bde99a7f16eb34f5d1be4
[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->{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 create_tag {
219     ##
220     # Given offset, signature and content, create tag and write to disk
221     ##
222     my $self = shift;
223     my ($obj, $offset, $sig, $content) = @_;
224     my $size = length($content);
225
226     my $fh = $obj->_fh;
227
228     seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
229     print( $fh $sig . pack($self->{data_pack}, $size) . $content );
230
231     if ($offset == $obj->_root->{end}) {
232         $obj->_root->{end} += SIG_SIZE + $self->{data_size} + $size;
233     }
234
235     return {
236         signature => $sig,
237         size => $size,
238         offset => $offset + SIG_SIZE + $self->{data_size},
239         content => $content
240     };
241 }
242
243 sub load_tag {
244     ##
245     # Given offset, load single tag and return signature, size and data
246     ##
247     my $self = shift;
248     my ($obj, $offset) = @_;
249
250 #    print join(':',map{$_||''}caller(1)), $/;
251
252     my $fh = $obj->_fh;
253
254     seek($fh, $offset + $obj->_root->{file_offset}, SEEK_SET);
255
256     #XXX I'm not sure this check will work if autoflush isn't enabled ...
257     return if eof $fh;
258
259     my $b;
260     read( $fh, $b, SIG_SIZE + $self->{data_size} );
261     my ($sig, $size) = unpack( "A $self->{data_pack}", $b );
262
263     my $buffer;
264     read( $fh, $buffer, $size);
265
266     return {
267         signature => $sig,
268         size => $size,
269         offset => $offset + SIG_SIZE + $self->{data_size},
270         content => $buffer
271     };
272 }
273
274 sub _length_needed {
275     my $self = shift;
276     my ($obj, $value) = @_;
277
278     my $is_dbm_deep = eval {
279         local $SIG{'__DIE__'};
280         $value->isa( 'DBM::Deep' );
281     };
282
283     my $internal_ref = $is_dbm_deep && ($value->_root eq $obj->_root);
284
285     if ( $internal_ref ) {
286         return $self->{long_size};
287     }
288
289     my $r = Scalar::Util::reftype( $value ) || '';
290     unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
291         return length( $value );
292     }
293
294     my $actual_length = $self->{index_size};
295
296     # if autobless is enabled, must also take into consideration
297     # the class name, as it is stored along with key/value.
298     if ( $obj->_root->{autobless} ) {
299         my $value_class = Scalar::Util::blessed($value);
300         if ( defined $value_class && !$value->isa('DBM::Deep') ) {
301             $actual_length += length($value_class);
302         }
303     }
304
305     return $actual_length;
306 }
307
308 sub add_bucket {
309     ##
310     # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
311     # plain (undigested) key and value.
312     ##
313     my $self = shift;
314     my ($obj, $tag, $md5, $plain_key, $value) = @_;
315
316     # This verifies that only supported values will be stored.
317     {
318         my $r = Scalar::Util::reftype( $value );
319         last if !defined $r;
320
321         last if $r eq 'HASH';
322         last if $r eq 'ARRAY';
323
324         $obj->_throw_error(
325             "Storage of variables of type '$r' is not supported."
326         );
327     }
328
329     my $location = 0;
330     my $result = 2;
331
332     my $root = $obj->_root;
333
334     my $fh = $obj->_fh;
335
336     my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
337
338     # Updating a known md5
339     if ( $subloc ) {
340         $result = 1;
341
342         seek($fh, $subloc + SIG_SIZE + $root->{file_offset}, SEEK_SET);
343         my $size;
344         read( $fh, $size, $self->{data_size});
345         $size = unpack($self->{data_pack}, $size);
346
347         my $actual_length = $self->_length_needed( $obj, $value );
348
349         if ($actual_length <= $size) {
350             $location = $subloc;
351         }
352         else {
353             $location = $root->{end};
354             seek(
355                 $fh,
356                 $tag->{offset} + $offset + $self->{hash_size} + $root->{file_offset},
357                 SEEK_SET,
358             );
359             print( $fh pack($self->{long_pack}, $location) );
360         }
361     }
362     # Adding a new md5
363     elsif ( defined $offset ) {
364         $location = $root->{end};
365
366         seek( $fh, $tag->{offset} + $offset + $root->{file_offset}, SEEK_SET );
367         print( $fh $md5 . pack($self->{long_pack}, $location) );
368     }
369     # If bucket didn't fit into list, split into a new index level
370     else {
371         $self->split_index( $obj, $md5, $tag );
372
373         $location = $root->{end};
374     }
375
376     $self->write_value( $obj, $location, $plain_key, $value );
377
378     return $result;
379 }
380
381 sub write_value {
382     my $self = shift;
383     my ($obj, $location, $key, $value) = @_;
384
385     my $fh = $obj->_fh;
386     my $root = $obj->_root;
387
388     my $is_dbm_deep = eval {
389         local $SIG{'__DIE__'};
390         $value->isa( 'DBM::Deep' );
391     };
392
393     my $internal_ref = $is_dbm_deep && ($value->_root eq $root);
394
395     seek($fh, $location + $root->{file_offset}, SEEK_SET);
396
397     ##
398     # Write signature based on content type, set content length and write
399     # actual value.
400     ##
401     my $r = Scalar::Util::reftype($value) || '';
402     my $content_length;
403     if ( $internal_ref ) {
404         print( $fh SIG_INTERNAL );
405         print( $fh pack($self->{data_pack}, $self->{long_size}) );
406         print( $fh pack($self->{long_pack}, $value->_base_offset) );
407         $content_length = $self->{long_size};
408     }
409     else {
410         if ($r eq 'HASH') {
411             print( $fh SIG_HASH );
412             print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
413             $content_length = $self->{index_size};
414         }
415         elsif ($r eq 'ARRAY') {
416             print( $fh SIG_ARRAY );
417             print( $fh pack($self->{data_pack}, $self->{index_size}) . chr(0) x $self->{index_size} );
418             $content_length = $self->{index_size};
419         }
420         elsif (!defined($value)) {
421             print( $fh SIG_NULL );
422             print( $fh pack($self->{data_pack}, 0) );
423             $content_length = 0;
424         }
425         else {
426             print( $fh SIG_DATA );
427             print( $fh pack($self->{data_pack}, length($value)) . $value );
428             $content_length = length($value);
429         }
430     }
431
432     ##
433     # Plain key is stored AFTER value, as keys are typically fetched less often.
434     ##
435     print( $fh pack($self->{data_pack}, length($key)) . $key );
436
437     ##
438     # If value is blessed, preserve class name
439     ##
440     if ( $root->{autobless} ) {
441         my $value_class = Scalar::Util::blessed($value);
442         if ( defined $value_class && !$value->isa( 'DBM::Deep' ) ) {
443             ##
444             # Blessed ref -- will restore later
445             ##
446             print( $fh chr(1) );
447             print( $fh pack($self->{data_pack}, length($value_class)) . $value_class );
448             $content_length += 1;
449             $content_length += $self->{data_size} + length($value_class);
450         }
451         else {
452             print( $fh chr(0) );
453             $content_length += 1;
454         }
455     }
456
457     ##
458     # If this is a new content area, advance EOF counter
459     ##
460     if ($location == $root->{end}) {
461         $root->{end} += SIG_SIZE;
462         $root->{end} += $self->{data_size} + $content_length;
463         $root->{end} += $self->{data_size} + length($key);
464     }
465
466     ##
467     # If content is a hash or array, create new child DBM::Deep object and
468     # pass each key or element to it.
469     ##
470     if ( ! $internal_ref ) {
471         if ($r eq 'HASH') {
472             my $branch = DBM::Deep->new(
473                 type => DBM::Deep->TYPE_HASH,
474                 base_offset => $location,
475                 root => $root,
476             );
477             foreach my $key (keys %{$value}) {
478                 $branch->STORE( $key, $value->{$key} );
479             }
480         }
481         elsif ($r eq 'ARRAY') {
482             my $branch = DBM::Deep->new(
483                 type => DBM::Deep->TYPE_ARRAY,
484                 base_offset => $location,
485                 root => $root,
486             );
487             my $index = 0;
488             foreach my $element (@{$value}) {
489                 $branch->STORE( $index, $element );
490                 $index++;
491             }
492         }
493     }
494
495     return 1;
496 }
497
498 sub split_index {
499     my $self = shift;
500     my ($obj, $md5, $tag) = @_;
501
502     my $fh = $obj->_fh;
503     my $root = $obj->_root;
504     my $keys = $tag->{content};
505
506     seek($fh, $tag->{ref_loc} + $root->{file_offset}, SEEK_SET);
507     print( $fh pack($self->{long_pack}, $root->{end}) );
508
509     my $index_tag = $self->create_tag(
510         $obj,
511         $root->{end},
512         SIG_INDEX,
513         chr(0) x $self->{index_size},
514     );
515
516     my @offsets = ();
517
518     $keys .= $md5 . pack($self->{long_pack}, 0);
519
520     BUCKET:
521     for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
522         my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
523
524         next BUCKET unless $key;
525
526         my $num = ord(substr($key, $tag->{ch} + 1, 1));
527
528         if ($offsets[$num]) {
529             my $offset = $offsets[$num] + SIG_SIZE + $self->{data_size};
530             seek($fh, $offset + $root->{file_offset}, SEEK_SET);
531             my $subkeys;
532             read( $fh, $subkeys, $self->{bucket_list_size});
533
534             for (my $k=0; $k<$self->{max_buckets}; $k++) {
535                 my ($temp, $subloc) = $self->_get_key_subloc( $subkeys, $k );
536
537                 if (!$subloc) {
538                     seek($fh, $offset + ($k * $self->{bucket_size}) + $root->{file_offset}, SEEK_SET);
539                     print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
540                     last;
541                 }
542             } # k loop
543         }
544         else {
545             $offsets[$num] = $root->{end};
546             seek($fh, $index_tag->{offset} + ($num * $self->{long_size}) + $root->{file_offset}, SEEK_SET);
547             print( $fh pack($self->{long_pack}, $root->{end}) );
548
549             my $blist_tag = $self->create_tag($obj, $root->{end}, SIG_BLIST, chr(0) x $self->{bucket_list_size});
550
551             seek($fh, $blist_tag->{offset} + $root->{file_offset}, SEEK_SET);
552             print( $fh $key . pack($self->{long_pack}, $old_subloc || $root->{end}) );
553         }
554     } # i loop
555
556     return;
557 }
558
559 sub read_from_loc {
560     my $self = shift;
561     my ($obj, $subloc) = @_;
562
563     my $fh = $obj->_fh;
564
565     ##
566     # Found match -- seek to offset and read signature
567     ##
568     my $signature;
569     seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
570     read( $fh, $signature, SIG_SIZE);
571
572     ##
573     # If value is a hash or array, return new DBM::Deep object with correct offset
574     ##
575     if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
576         my $obj = DBM::Deep->new(
577             type => $signature,
578             base_offset => $subloc,
579             root => $obj->_root,
580         );
581
582         if ($obj->_root->{autobless}) {
583             ##
584             # Skip over value and plain key to see if object needs
585             # to be re-blessed
586             ##
587             seek($fh, $self->{data_size} + $self->{index_size}, SEEK_CUR);
588
589             my $size;
590             read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
591             if ($size) { seek($fh, $size, SEEK_CUR); }
592
593             my $bless_bit;
594             read( $fh, $bless_bit, 1);
595             if (ord($bless_bit)) {
596                 ##
597                 # Yes, object needs to be re-blessed
598                 ##
599                 my $class_name;
600                 read( $fh, $size, $self->{data_size}); $size = unpack($self->{data_pack}, $size);
601                 if ($size) { read( $fh, $class_name, $size); }
602                 if ($class_name) { $obj = bless( $obj, $class_name ); }
603             }
604         }
605
606         return $obj;
607     }
608     elsif ( $signature eq SIG_INTERNAL ) {
609         my $size;
610         read( $fh, $size, $self->{data_size});
611         $size = unpack($self->{data_pack}, $size);
612
613         if ( $size ) {
614             my $new_loc;
615             read( $fh, $new_loc, $size );
616             $new_loc = unpack( $self->{long_pack}, $new_loc );
617
618             return $self->read_from_loc( $obj, $new_loc );
619         }
620         else {
621             return;
622         }
623     }
624     ##
625     # Otherwise return actual value
626     ##
627     elsif ($signature eq SIG_DATA) {
628         my $size;
629         read( $fh, $size, $self->{data_size});
630         $size = unpack($self->{data_pack}, $size);
631
632         my $value = '';
633         if ($size) { read( $fh, $value, $size); }
634         return $value;
635     }
636
637     ##
638     # Key exists, but content is null
639     ##
640     return;
641 }
642
643 sub get_bucket_value {
644     ##
645     # Fetch single value given tag and MD5 digested key.
646     ##
647     my $self = shift;
648     my ($obj, $tag, $md5) = @_;
649
650     my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
651     if ( $subloc ) {
652         return $self->read_from_loc( $obj, $subloc );
653     }
654     return;
655 }
656
657 sub delete_bucket {
658     ##
659     # Delete single key/value pair given tag and MD5 digested key.
660     ##
661     my $self = shift;
662     my ($obj, $tag, $md5) = @_;
663
664     my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
665     if ( $subloc ) {
666         my $fh = $obj->_fh;
667         seek($fh, $tag->{offset} + $offset + $obj->_root->{file_offset}, SEEK_SET);
668         print( $fh substr($tag->{content}, $offset + $self->{bucket_size} ) );
669         print( $fh chr(0) x $self->{bucket_size} );
670
671         return 1;
672     }
673     return;
674 }
675
676 sub bucket_exists {
677     ##
678     # Check existence of single key given tag and MD5 digested key.
679     ##
680     my $self = shift;
681     my ($obj, $tag, $md5) = @_;
682
683     my ($subloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
684     return $subloc && 1;
685 }
686
687 sub find_bucket_list {
688     ##
689     # Locate offset for bucket list, given digested key
690     ##
691     my $self = shift;
692     my ($obj, $md5, $args) = @_;
693     $args = {} unless $args;
694
695     ##
696     # Locate offset for bucket list using digest index system
697     ##
698     my $tag = $self->load_tag($obj, $obj->_base_offset)
699         or $obj->_throw_error( "INTERNAL ERROR - Cannot find tag" );
700
701     my $ch = 0;
702     while ($tag->{signature} ne SIG_BLIST) {
703         my $num = ord substr($md5, $ch, 1);
704
705         my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
706         $tag = $self->index_lookup( $obj, $tag, $num );
707
708         if (!$tag) {
709             return if !$args->{create};
710
711             my $fh = $obj->_fh;
712             seek($fh, $ref_loc + $obj->_root->{file_offset}, SEEK_SET);
713             print( $fh pack($self->{long_pack}, $obj->_root->{end}) );
714
715             $tag = $self->create_tag(
716                 $obj, $obj->_root->{end},
717                 SIG_BLIST,
718                 chr(0) x $self->{bucket_list_size},
719             );
720
721             $tag->{ref_loc} = $ref_loc;
722             $tag->{ch} = $ch;
723
724             last;
725         }
726
727         $tag->{ch} = $ch;
728         $tag->{ref_loc} = $ref_loc;
729
730         $ch++;
731     }
732
733     return $tag;
734 }
735
736 sub index_lookup {
737     ##
738     # Given index tag, lookup single entry in index and return .
739     ##
740     my $self = shift;
741     my ($obj, $tag, $index) = @_;
742
743     my $location = unpack(
744         $self->{long_pack},
745         substr(
746             $tag->{content},
747             $index * $self->{long_size},
748             $self->{long_size},
749         ),
750     );
751
752     if (!$location) { return; }
753
754     return $self->load_tag( $obj, $location );
755 }
756
757 sub traverse_index {
758     ##
759     # Scan index and recursively step into deeper levels, looking for next key.
760     ##
761     my $self = shift;
762     my ($obj, $offset, $ch, $force_return_next) = @_;
763
764     my $tag = $self->load_tag($obj, $offset );
765
766     my $fh = $obj->_fh;
767
768     if ($tag->{signature} ne SIG_BLIST) {
769         my $content = $tag->{content};
770         my $start = $obj->{return_next} ? 0 : ord(substr($obj->{prev_md5}, $ch, 1));
771
772         for (my $idx = $start; $idx < (2**8); $idx++) {
773             my $subloc = unpack(
774                 $self->{long_pack},
775                 substr(
776                     $content,
777                     $idx * $self->{long_size},
778                     $self->{long_size},
779                 ),
780             );
781
782             if ($subloc) {
783                 my $result = $self->traverse_index(
784                     $obj, $subloc, $ch + 1, $force_return_next,
785                 );
786
787                 if (defined($result)) { return $result; }
788             }
789         } # index loop
790
791         $obj->{return_next} = 1;
792     } # tag is an index
793
794     else {
795         my $keys = $tag->{content};
796         if ($force_return_next) { $obj->{return_next} = 1; }
797
798         ##
799         # Iterate through buckets, looking for a key match
800         ##
801         for (my $i = 0; $i < $self->{max_buckets}; $i++) {
802             my ($key, $subloc) = $self->_get_key_subloc( $keys, $i );
803
804             # End of bucket list -- return to outer loop
805             if (!$subloc) {
806                 $obj->{return_next} = 1;
807                 last;
808             }
809             # Located previous key -- return next one found
810             elsif ($key eq $obj->{prev_md5}) {
811                 $obj->{return_next} = 1;
812                 next;
813             }
814             # Seek to bucket location and skip over signature
815             elsif ($obj->{return_next}) {
816                 seek($fh, $subloc + $obj->_root->{file_offset}, SEEK_SET);
817
818                 # Skip over value to get to plain key
819                 my $sig;
820                 read( $fh, $sig, SIG_SIZE );
821
822                 my $size;
823                 read( $fh, $size, $self->{data_size});
824                 $size = unpack($self->{data_pack}, $size);
825                 if ($size) { seek($fh, $size, SEEK_CUR); }
826
827                 # Read in plain key and return as scalar
828                 my $plain_key;
829                 read( $fh, $size, $self->{data_size});
830                 $size = unpack($self->{data_pack}, $size);
831                 if ($size) { read( $fh, $plain_key, $size); }
832
833                 return $plain_key;
834             }
835         }
836
837         $obj->{return_next} = 1;
838     } # tag is a bucket list
839
840     return;
841 }
842
843 sub get_next_key {
844     ##
845     # Locate next key, given digested previous one
846     ##
847     my $self = shift;
848     my ($obj) = @_;
849
850     $obj->{prev_md5} = $_[1] ? $_[1] : undef;
851     $obj->{return_next} = 0;
852
853     ##
854     # If the previous key was not specifed, start at the top and
855     # return the first one found.
856     ##
857     if (!$obj->{prev_md5}) {
858         $obj->{prev_md5} = chr(0) x $self->{hash_size};
859         $obj->{return_next} = 1;
860     }
861
862     return $self->traverse_index( $obj, $obj->_base_offset, 0 );
863 }
864
865 # Utilities
866
867 sub _get_key_subloc {
868     my $self = shift;
869     my ($keys, $idx) = @_;
870
871     my ($key, $subloc) = unpack(
872         "a$self->{hash_size} $self->{long_pack}",
873         substr(
874             $keys,
875             ($idx * $self->{bucket_size}),
876             $self->{bucket_size},
877         ),
878     );
879
880     return ($key, $subloc);
881 }
882
883 sub _find_in_buckets {
884     my $self = shift;
885     my ($tag, $md5) = @_;
886
887     BUCKET:
888     for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
889         my ($key, $subloc) = $self->_get_key_subloc( $tag->{content}, $i );
890
891         return ($subloc, $i * $self->{bucket_size}) unless $subloc;
892
893         next BUCKET if $key ne $md5;
894
895         return ($subloc, $i * $self->{bucket_size});
896     }
897
898     return;
899 }
900
901 sub _request_space {
902     my $self = shift;
903     my ($obj, $size) = @_;
904
905     my $loc = $obj->_root->{end};
906     $obj->_root->{end} += $size;
907
908     return $loc;
909 }
910
911 sub _release_space {
912     my $self = shift;
913     my ($obj, $size, $loc) = @_;
914
915     return;
916 }
917
918 1;
919 __END__
920
921 # This will be added in later, after more refactoring is done. This is an early
922 # attempt at refactoring on the physical level instead of the virtual level.
923 sub _read_at {
924     my $self = shift;
925     my ($obj, $spot, $amount, $unpack) = @_;
926
927     my $fh = $obj->_fh;
928     seek( $fh, $spot + $obj->_root->{file_offset}, SEEK_SET );
929
930     my $buffer;
931     my $bytes_read = read( $fh, $buffer, $amount );
932
933     if ( $unpack ) {
934         $buffer = unpack( $unpack, $buffer );
935     }
936
937     if ( wantarray ) {
938         return ($buffer, $bytes_read);
939     }
940     else {
941         return $buffer;
942     }
943 }