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