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