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