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