723c029881747378edadda0d8f13d64c40568503
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep / Engine.pm
1 package DBM::Deep::Engine;
2
3 use 5.6.0;
4
5 use strict;
6 use warnings;
7
8 our $VERSION = q(0.99_03);
9
10 use Fcntl qw( :DEFAULT :flock );
11 use Scalar::Util ();
12
13 # File-wide notes:
14 # * To add to bucket_size, make sure you modify the following:
15 #   - calculate_sizes()
16 #   - _get_key_subloc()
17 #   - add_bucket() - where the buckets are printed
18 #
19 # * Every method in here assumes that the _fileobj has been appropriately
20 #   safeguarded. This can be anything from flock() to some sort of manual
21 #   mutex. But, it's the caller's responsability to make sure that this has
22 #   been done.
23
24 ##
25 # Setup file and tag signatures.  These should never change.
26 ##
27 sub SIG_FILE     () { 'DPDB' }
28 sub SIG_HEADER   () { 'h'    }
29 sub SIG_INTERNAL () { 'i'    }
30 sub SIG_HASH     () { 'H'    }
31 sub SIG_ARRAY    () { 'A'    }
32 sub SIG_NULL     () { 'N'    }
33 sub SIG_DATA     () { 'D'    }
34 sub SIG_INDEX    () { 'I'    }
35 sub SIG_BLIST    () { 'B'    }
36 sub SIG_FREE     () { 'F'    }
37 sub SIG_KEYS     () { 'K'    }
38 sub SIG_SIZE     () {  1     }
39
40 ################################################################################
41 #
42 # This is new code. It is a complete rewrite of the engine based on a new API
43 #
44 ################################################################################
45
46 sub write_value {
47     my $self = shift;
48     my ($offset, $key, $value, $orig_key) = @_;
49
50     my $dig_key = $self->apply_digest( $key );
51     my $tag = $self->find_blist( $offset, $dig_key, { create => 1 } );
52     return $self->add_bucket( $tag, $dig_key, $key, $value, undef, $orig_key );
53 }
54
55 sub read_value {
56     my $self = shift;
57     my ($offset, $key, $orig_key) = @_;
58
59     my $dig_key = $self->apply_digest( $key );
60     my $tag = $self->find_blist( $offset, $dig_key ) or return;
61     return $self->get_bucket_value( $tag, $dig_key, $orig_key );
62 }
63
64 sub delete_key {
65     my $self = shift;
66     my ($offset, $key, $orig_key) = @_;
67
68     my $dig_key = $self->apply_digest( $key );
69     my $tag = $self->find_blist( $offset, $dig_key ) or return;
70     my $value = $self->get_bucket_value( $tag, $dig_key, $orig_key );
71     $self->delete_bucket( $tag, $dig_key, $orig_key );
72     return $value;
73 }
74
75 sub key_exists {
76     my $self = shift;
77     my ($offset, $key) = @_;
78
79     my $dig_key = $self->apply_digest( $key );
80     # exists() returns the empty string, not undef
81     my $tag = $self->find_blist( $offset, $dig_key ) or return '';
82     return $self->bucket_exists( $tag, $dig_key, $key );
83 }
84
85 sub get_next_key {
86     my $self = shift;
87     my ($offset) = @_;
88
89     # If the previous key was not specifed, start at the top and
90     # return the first one found.
91     my $temp;
92     if ( @_ > 1 ) {
93         $temp = {
94             prev_md5    => $self->apply_digest($_[1]),
95             return_next => 0,
96         };
97     }
98     else {
99         $temp = {
100             prev_md5    => chr(0) x $self->{hash_size},
101             return_next => 1,
102         };
103     }
104
105     return $self->traverse_index( $temp, $offset, 0 );
106 }
107
108 ################################################################################
109 #
110 # Below here is the old code. It will be folded into the code above as it can.
111 #
112 ################################################################################
113
114 sub new {
115     my $class = shift;
116     my ($args) = @_;
117
118     my $self = bless {
119         long_size => 4,
120         long_pack => 'N',
121         data_size => 4,
122         data_pack => 'N',
123
124         digest    => \&Digest::MD5::md5,
125         hash_size => 16, # In bytes
126
127         ##
128         # Number of buckets per blist before another level of indexing is
129         # done. Increase this value for slightly greater speed, but larger database
130         # files. DO NOT decrease this value below 16, due to risk of recursive
131         # reindex overrun.
132         ##
133         max_buckets => 16,
134
135         fileobj => undef,
136         obj     => undef,
137     }, $class;
138
139     if ( defined $args->{pack_size} ) {
140         if ( lc $args->{pack_size} eq 'small' ) {
141             $args->{long_size} = 2;
142             $args->{long_pack} = 'n';
143         }
144         elsif ( lc $args->{pack_size} eq 'medium' ) {
145             $args->{long_size} = 4;
146             $args->{long_pack} = 'N';
147         }
148         elsif ( lc $args->{pack_size} eq 'large' ) {
149             $args->{long_size} = 8;
150             $args->{long_pack} = 'Q';
151         }
152         else {
153             die "Unknown pack_size value: '$args->{pack_size}'\n";
154         }
155     }
156
157     # Grab the parameters we want to use
158     foreach my $param ( keys %$self ) {
159         next unless exists $args->{$param};
160         $self->{$param} = $args->{$param};
161     }
162     Scalar::Util::weaken( $self->{obj} ) if $self->{obj};
163
164     if ( $self->{max_buckets} < 16 ) {
165         warn "Floor of max_buckets is 16. Setting it to 16 from '$self->{max_buckets}'\n";
166         $self->{max_buckets} = 16;
167     }
168
169     return $self;
170 }
171
172 sub _fileobj { return $_[0]{fileobj} }
173
174 sub apply_digest {
175     my $self = shift;
176     return $self->{digest}->(@_);
177 }
178
179 sub calculate_sizes {
180     my $self = shift;
181
182     # The 2**8 here indicates the number of different characters in the
183     # current hashing algorithm
184     #XXX Does this need to be updated with different hashing algorithms?
185     $self->{hash_chars_used}  = (2**8);
186     $self->{index_size}       = $self->{hash_chars_used} * $self->{long_size};
187
188     $self->{bucket_size}      = $self->{hash_size} + $self->{long_size} * 2;
189     $self->{bucket_list_size} = $self->{max_buckets} * $self->{bucket_size};
190
191     $self->{key_size}         = $self->{long_size} * 2;
192     $self->{keyloc_size}      = $self->{max_buckets} * $self->{key_size};
193
194     return;
195 }
196
197 sub write_file_header {
198     my $self = shift;
199
200     my $loc = $self->_fileobj->request_space( length( SIG_FILE ) + 33 );
201
202     $self->_fileobj->print_at( $loc,
203         SIG_FILE,
204         SIG_HEADER,
205         pack('N', 1),  # header version
206         pack('N', 24), # header size
207         pack('N4', 0, 0, 0, 0),  # currently running transaction IDs
208         pack('n', $self->{long_size}),
209         pack('A', $self->{long_pack}),
210         pack('n', $self->{data_size}),
211         pack('A', $self->{data_pack}),
212         pack('n', $self->{max_buckets}),
213     );
214
215     $self->_fileobj->set_transaction_offset( 13 );
216
217     return;
218 }
219
220 sub read_file_header {
221     my $self = shift;
222
223     my $buffer = $self->_fileobj->read_at( 0, length(SIG_FILE) + 9 );
224     return unless length($buffer);
225
226     my ($file_signature, $sig_header, $header_version, $size) = unpack(
227         'A4 A N N', $buffer
228     );
229
230     unless ( $file_signature eq SIG_FILE ) {
231         $self->_fileobj->close;
232         $self->_throw_error( "Signature not found -- file is not a Deep DB" );
233     }
234
235     unless ( $sig_header eq SIG_HEADER ) {
236         $self->_fileobj->close;
237         $self->_throw_error( "Old file version found." );
238     }
239
240     my $buffer2 = $self->_fileobj->read_at( undef, $size );
241     my ($a1, $a2, $a3, $a4, @values) = unpack( 'N4 n A n A n', $buffer2 );
242
243     $self->_fileobj->set_transaction_offset( 13 );
244
245     if ( @values < 5 || grep { !defined } @values ) {
246         $self->_fileobj->close;
247         $self->_throw_error("Corrupted file - bad header");
248     }
249
250     #XXX Add warnings if values weren't set right
251     @{$self}{qw(long_size long_pack data_size data_pack max_buckets)} = @values;
252
253     return length($buffer) + length($buffer2);
254 }
255
256 sub setup_fh {
257     my $self = shift;
258     my ($obj) = @_;
259
260     # Need to remove use of $fh here
261     my $fh = $self->_fileobj->{fh};
262     flock $fh, LOCK_EX;
263
264     #XXX The duplication of calculate_sizes needs to go away
265     unless ( $obj->{base_offset} ) {
266         my $bytes_read = $self->read_file_header;
267
268         $self->calculate_sizes;
269
270         ##
271         # File is empty -- write header and master index
272         ##
273         if (!$bytes_read) {
274             $self->_fileobj->audit( "# Database created on" );
275
276             $self->write_file_header;
277
278             $obj->{base_offset} = $self->_fileobj->request_space(
279                 $self->tag_size( $self->{index_size} ),
280             );
281
282             $self->write_tag(
283                 $obj->_base_offset, $obj->_type,
284                 chr(0)x$self->{index_size},
285             );
286
287             # Flush the filehandle
288             my $old_fh = select $fh;
289             my $old_af = $|; $| = 1; $| = $old_af;
290             select $old_fh;
291         }
292         else {
293             $obj->{base_offset} = $bytes_read;
294
295             ##
296             # Get our type from master index header
297             ##
298             my $tag = $self->load_tag($obj->_base_offset);
299             unless ( $tag ) {
300                 flock $fh, LOCK_UN;
301                 $self->_throw_error("Corrupted file, no master index record");
302             }
303
304             unless ($obj->_type eq $tag->{signature}) {
305                 flock $fh, LOCK_UN;
306                 $self->_throw_error("File type mismatch");
307             }
308         }
309     }
310     else {
311         $self->calculate_sizes;
312     }
313
314     #XXX We have to make sure we don't mess up when autoflush isn't turned on
315     $self->_fileobj->set_inode;
316
317     flock $fh, LOCK_UN;
318
319     return 1;
320 }
321
322 sub tag_size {
323     my $self = shift;
324     my ($size) = @_;
325     return SIG_SIZE + $self->{data_size} + $size;
326 }
327
328 sub write_tag {
329     ##
330     # Given offset, signature and content, create tag and write to disk
331     ##
332     my $self = shift;
333     my ($offset, $sig, $content) = @_;
334     my $size = length( $content );
335
336     $self->_fileobj->print_at(
337         $offset, 
338         $sig, pack($self->{data_pack}, $size), $content,
339     );
340
341     return unless defined $offset;
342
343     return {
344         signature => $sig,
345         #XXX Is this even used?
346         size      => $size,
347         offset    => $offset + SIG_SIZE + $self->{data_size},
348         content   => $content
349     };
350 }
351
352 sub load_tag {
353     ##
354     # Given offset, load single tag and return signature, size and data
355     ##
356     my $self = shift;
357     my ($offset) = @_;
358
359     my $fileobj = $self->_fileobj;
360
361     my ($sig, $size) = unpack(
362         "A $self->{data_pack}",
363         $fileobj->read_at( $offset, SIG_SIZE + $self->{data_size} ),
364     );
365
366     return {
367         signature => $sig,
368         size      => $size,   #XXX Is this even used?
369         offset    => $offset + SIG_SIZE + $self->{data_size},
370         content   => $fileobj->read_at( undef, $size ),
371     };
372 }
373
374 sub find_keyloc {
375     my $self = shift;
376     my ($tag, $transaction_id) = @_;
377     $transaction_id = $self->_fileobj->transaction_id
378         unless defined $transaction_id;
379
380     for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
381         my ($loc, $trans_id, $is_deleted) = unpack(
382             "$self->{long_pack} C C",
383             substr( $tag->{content}, $i * $self->{key_size}, $self->{key_size} ),
384         );
385
386         if ( $loc == 0 ) {
387             return ( $loc, $is_deleted, $i * $self->{key_size} );
388         }
389
390         next if $transaction_id != $trans_id;
391
392         return ( $loc, $is_deleted, $i * $self->{key_size} );
393     }
394
395     return;
396 }
397
398 sub add_bucket {
399     ##
400     # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
401     # plain (undigested) key and value.
402     ##
403     my $self = shift;
404     my ($tag, $md5, $plain_key, $value, $deleted, $orig_key) = @_;
405
406     # This verifies that only supported values will be stored.
407     {
408         my $r = Scalar::Util::reftype( $value );
409
410         last if !defined $r;
411         last if $r eq 'HASH';
412         last if $r eq 'ARRAY';
413
414         $self->_throw_error(
415             "Storage of references of type '$r' is not supported."
416         );
417     }
418
419     my $fileobj = $self->_fileobj;
420
421     #ACID - This is a mutation. Must only find the exact transaction
422     my ($keyloc, $offset) = $self->_find_in_buckets( $tag, $md5, 1 );
423
424     my @transactions;
425     if ( $fileobj->transaction_id == 0 ) {
426         @transactions = $fileobj->current_transactions;
427     }
428
429 #    $self->_release_space( $size, $subloc );
430 #XXX This needs updating to use _release_space
431
432     my $location;
433     my $size = $self->_length_needed( $value, $plain_key );
434
435     # Updating a known md5
436     if ( $keyloc ) {
437         my $keytag = $self->load_tag( $keyloc );
438         my ($subloc, $is_deleted, $offset) = $self->find_keyloc( $keytag );
439
440         if ( $subloc && !$is_deleted && @transactions ) {
441             my $old_value = $self->read_from_loc( $subloc, $orig_key );
442             my $old_size = $self->_length_needed( $old_value, $plain_key );
443
444             for my $trans_id ( @transactions ) {
445                 my ($loc, $is_deleted, $offset2) = $self->find_keyloc( $keytag, $trans_id );
446                 unless ($loc) {
447                     my $location2 = $fileobj->request_space( $old_size );
448                     $fileobj->print_at( $keytag->{offset} + $offset2,
449                         pack($self->{long_pack}, $location2 ),
450                         pack( 'C C', $trans_id, 0 ),
451                     );
452                     $self->_write_value( $location2, $plain_key, $old_value, $orig_key );
453                 }
454             }
455         }
456
457         $location = $self->_fileobj->request_space( $size );
458         #XXX This needs to be transactionally-aware in terms of which keytag->{offset} to use
459         $fileobj->print_at( $keytag->{offset} + $offset,
460             pack($self->{long_pack}, $location ),
461             pack( 'C C', $fileobj->transaction_id, 0 ),
462         );
463     }
464     # Adding a new md5
465     else {
466         my $keyloc = $fileobj->request_space( $self->tag_size( $self->{keyloc_size} ) );
467
468         # The bucket fit into list
469         if ( defined $offset ) {
470             $fileobj->print_at( $tag->{offset} + $offset,
471                 $md5, pack( $self->{long_pack}, $keyloc ),
472             );
473         }
474         # If bucket didn't fit into list, split into a new index level
475         else {
476             $self->split_index( $tag, $md5, $keyloc );
477         }
478
479         my $keytag = $self->write_tag(
480             $keyloc, SIG_KEYS, chr(0)x$self->{keyloc_size},
481         );
482
483         $location = $self->_fileobj->request_space( $size );
484         $fileobj->print_at( $keytag->{offset},
485             pack( $self->{long_pack}, $location ),
486             pack( 'C C', $fileobj->transaction_id, 0 ),
487         );
488
489         my $offset = 1;
490         for my $trans_id ( @transactions ) {
491             $fileobj->print_at( $keytag->{offset} + $self->{key_size} * $offset++,
492                 pack( $self->{long_pack}, 0 ),
493                 pack( 'C C', $trans_id, 1 ),
494             );
495         }
496     }
497
498     $self->_write_value( $location, $plain_key, $value, $orig_key );
499
500     return 1;
501 }
502
503 sub _write_value {
504     my $self = shift;
505     my ($location, $key, $value, $orig_key) = @_;
506
507     my $fileobj = $self->_fileobj;
508
509     my $dbm_deep_obj = _get_dbm_object( $value );
510     if ( $dbm_deep_obj && $dbm_deep_obj->_fileobj ne $fileobj ) {
511         $self->_throw_error( "Cannot cross-reference. Use export() instead" );
512     }
513
514     ##
515     # Write signature based on content type, set content length and write
516     # actual value.
517     ##
518     my $r = Scalar::Util::reftype( $value ) || '';
519     if ( $dbm_deep_obj ) {
520         $self->write_tag( $location, SIG_INTERNAL,pack($self->{long_pack}, $dbm_deep_obj->_base_offset) );
521     }
522     elsif ($r eq 'HASH') {
523         if ( !$dbm_deep_obj && tied %{$value} ) {
524             $self->_throw_error( "Cannot store something that is tied" );
525         }
526         $self->write_tag( $location, SIG_HASH, chr(0)x$self->{index_size} );
527     }
528     elsif ($r eq 'ARRAY') {
529         if ( !$dbm_deep_obj && tied @{$value} ) {
530             $self->_throw_error( "Cannot store something that is tied" );
531         }
532         $self->write_tag( $location, SIG_ARRAY, chr(0)x$self->{index_size} );
533     }
534     elsif (!defined($value)) {
535         $self->write_tag( $location, SIG_NULL, '' );
536     }
537     else {
538         $self->write_tag( $location, SIG_DATA, $value );
539     }
540
541     ##
542     # Plain key is stored AFTER value, as keys are typically fetched less often.
543     ##
544     $fileobj->print_at( undef, pack($self->{data_pack}, length($key)) . $key );
545
546     # Internal references don't care about autobless
547     return 1 if $dbm_deep_obj;
548
549     ##
550     # If value is blessed, preserve class name
551     ##
552     if ( $fileobj->{autobless} ) {
553         if ( defined( my $c = Scalar::Util::blessed($value) ) ) {
554             $fileobj->print_at( undef, chr(1), pack($self->{data_pack}, length($c)) . $c );
555         }
556         else {
557             $fileobj->print_at( undef, chr(0) );
558         }
559     }
560
561     ##
562     # Tie the passed in reference so that changes to it are reflected in the
563     # datafile. The use of $location as the base_offset will act as the
564     # the linkage between parent and child.
565     #
566     # The overall assignment is a hack around the fact that just tying doesn't
567     # store the values. This may not be the wrong thing to do.
568     ##
569     if ($r eq 'HASH') {
570         my %x = %$value;
571         tie %$value, 'DBM::Deep', {
572             base_offset => $location,
573             fileobj     => $fileobj,
574             parent      => $self->{obj},
575             parent_key  => $orig_key,
576         };
577         %$value = %x;
578     }
579     elsif ($r eq 'ARRAY') {
580         my @x = @$value;
581         tie @$value, 'DBM::Deep', {
582             base_offset => $location,
583             fileobj     => $fileobj,
584             parent      => $self->{obj},
585             parent_key  => $orig_key,
586         };
587         @$value = @x;
588     }
589
590     return 1;
591 }
592
593 sub split_index {
594     my $self = shift;
595     my ($tag, $md5, $keyloc) = @_;
596
597     my $fileobj = $self->_fileobj;
598
599     my $loc = $fileobj->request_space(
600         $self->tag_size( $self->{index_size} ),
601     );
602
603     $fileobj->print_at( $tag->{ref_loc}, pack($self->{long_pack}, $loc) );
604
605     my $index_tag = $self->write_tag(
606         $loc, SIG_INDEX,
607         chr(0)x$self->{index_size},
608     );
609
610     my $keys = $tag->{content}
611              . $md5 . pack($self->{long_pack}, $keyloc);
612
613     my @newloc = ();
614     BUCKET:
615     # The <= here is deliberate - we have max_buckets+1 keys to iterate
616     # through, unlike every other loop that uses max_buckets as a stop.
617     for (my $i = 0; $i <= $self->{max_buckets}; $i++) {
618         my ($key, $old_subloc) = $self->_get_key_subloc( $keys, $i );
619
620         die "[INTERNAL ERROR]: No key in split_index()\n" unless $key;
621         die "[INTERNAL ERROR]: No subloc in split_index()\n" unless $old_subloc;
622
623         my $num = ord(substr($key, $tag->{ch} + 1, 1));
624
625         if ($newloc[$num]) {
626             my $subkeys = $fileobj->read_at( $newloc[$num], $self->{bucket_list_size} );
627
628             # This is looking for the first empty spot
629             my ($subloc, $offset) = $self->_find_in_buckets(
630                 { content => $subkeys }, '',
631             );
632
633             $fileobj->print_at(
634                 $newloc[$num] + $offset,
635                 $key, pack($self->{long_pack}, $old_subloc),
636             );
637
638             next;
639         }
640
641         my $loc = $fileobj->request_space(
642             $self->tag_size( $self->{bucket_list_size} ),
643         );
644
645         $fileobj->print_at(
646             $index_tag->{offset} + ($num * $self->{long_size}),
647             pack($self->{long_pack}, $loc),
648         );
649
650         my $blist_tag = $self->write_tag(
651             $loc, SIG_BLIST,
652             chr(0)x$self->{bucket_list_size},
653         );
654
655         $fileobj->print_at( $blist_tag->{offset}, $key . pack($self->{long_pack}, $old_subloc) );
656
657         $newloc[$num] = $blist_tag->{offset};
658     }
659
660     $self->_release_space(
661         $self->tag_size( $self->{bucket_list_size} ),
662         $tag->{offset} - SIG_SIZE - $self->{data_size},
663     );
664
665     return 1;
666 }
667
668 sub read_from_loc {
669     my $self = shift;
670     my ($subloc, $orig_key) = @_;
671
672     my $fileobj = $self->_fileobj;
673
674     my $signature = $fileobj->read_at( $subloc, SIG_SIZE );
675
676     ##
677     # If value is a hash or array, return new DBM::Deep object with correct offset
678     ##
679     if (($signature eq SIG_HASH) || ($signature eq SIG_ARRAY)) {
680         #XXX This needs to be a singleton
681         my $new_obj = DBM::Deep->new({
682             type        => $signature,
683             base_offset => $subloc,
684             fileobj     => $self->_fileobj,
685             parent      => $self->{obj},
686             parent_key  => $orig_key,
687         });
688
689         if ($new_obj->_fileobj->{autobless}) {
690             ##
691             # Skip over value and plain key to see if object needs
692             # to be re-blessed
693             ##
694             $fileobj->increment_pointer( $self->{data_size} + $self->{index_size} );
695
696             my $size = $fileobj->read_at( undef, $self->{data_size} );
697             $size = unpack($self->{data_pack}, $size);
698             if ($size) { $fileobj->increment_pointer( $size ); }
699
700             my $bless_bit = $fileobj->read_at( undef, 1 );
701             if ( ord($bless_bit) ) {
702                 my $size = unpack(
703                     $self->{data_pack},
704                     $fileobj->read_at( undef, $self->{data_size} ),
705                 );
706
707                 if ( $size ) {
708                     $new_obj = bless $new_obj, $fileobj->read_at( undef, $size );
709                 }
710             }
711         }
712
713         return $new_obj;
714     }
715     elsif ( $signature eq SIG_INTERNAL ) {
716         my $size = $fileobj->read_at( undef, $self->{data_size} );
717         $size = unpack($self->{data_pack}, $size);
718
719         if ( $size ) {
720             my $new_loc = $fileobj->read_at( undef, $size );
721             $new_loc = unpack( $self->{long_pack}, $new_loc ); 
722             return $self->read_from_loc( $new_loc, $orig_key );
723         }
724         else {
725             return;
726         }
727     }
728     ##
729     # Otherwise return actual value
730     ##
731     elsif ( $signature eq SIG_DATA ) {
732         my $size = $fileobj->read_at( undef, $self->{data_size} );
733         $size = unpack($self->{data_pack}, $size);
734
735         my $value = $size ? $fileobj->read_at( undef, $size ) : '';
736         return $value;
737     }
738
739     ##
740     # Key exists, but content is null
741     ##
742     return;
743 }
744
745 sub get_bucket_value {
746     ##
747     # Fetch single value given tag and MD5 digested key.
748     ##
749     my $self = shift;
750     my ($tag, $md5, $orig_key) = @_;
751
752     #ACID - This is a read. Can find exact or HEAD
753     my ($keyloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
754
755     if ( !$keyloc ) {
756         #XXX Need to use real key
757 #        $self->add_bucket( $tag, $md5, $orig_key, undef, $orig_key );
758 #        return;
759     }
760 #    elsif ( !$is_deleted ) {
761     else {
762         my $keytag = $self->load_tag( $keyloc );
763         my ($subloc, $is_deleted) = $self->find_keyloc( $keytag );
764         if (!$subloc && !$is_deleted) {
765             ($subloc, $is_deleted) = $self->find_keyloc( $keytag, 0 );
766         }
767         if ( $subloc && !$is_deleted ) {
768             return $self->read_from_loc( $subloc, $orig_key );
769         }
770     }
771
772     return;
773 }
774
775 sub delete_bucket {
776     ##
777     # Delete single key/value pair given tag and MD5 digested key.
778     ##
779     my $self = shift;
780     my ($tag, $md5, $orig_key) = @_;
781
782     #ACID - Although this is a mutation, we must find any transaction.
783     # This is because we need to mark something as deleted that is in the HEAD.
784     my ($keyloc, $offset) = $self->_find_in_buckets( $tag, $md5 );
785
786     return if !$keyloc;
787
788     my $fileobj = $self->_fileobj;
789
790     my @transactions;
791     if ( $fileobj->transaction_id == 0 ) {
792         @transactions = $fileobj->current_transactions;
793     }
794
795     if ( $fileobj->transaction_id == 0 ) {
796         my $keytag = $self->load_tag( $keyloc );
797
798         my ($subloc, $is_deleted, $offset) = $self->find_keyloc( $keytag );
799         return if !$subloc || $is_deleted;
800
801         my $value = $self->read_from_loc( $subloc, $orig_key );
802
803         my $size = $self->_length_needed( $value, $orig_key );
804
805         for my $trans_id ( @transactions ) {
806             my ($loc, $is_deleted, $offset2) = $self->find_keyloc( $keytag, $trans_id );
807             unless ($loc) {
808                 my $location2 = $fileobj->request_space( $size );
809                 $fileobj->print_at( $keytag->{offset} + $offset2,
810                     pack($self->{long_pack}, $location2 ),
811                     pack( 'C C', $trans_id, 0 ),
812                 );
813                 $self->_write_value( $location2, $orig_key, $value, $orig_key );
814             }
815         }
816
817         $keytag = $self->load_tag( $keyloc );
818         ($subloc, $is_deleted, $offset) = $self->find_keyloc( $keytag );
819         $fileobj->print_at( $keytag->{offset} + $offset,
820             substr( $keytag->{content}, $offset + $self->{key_size} ),
821             chr(0) x $self->{key_size},
822         );
823     }
824     else {
825         my $keytag = $self->load_tag( $keyloc );
826
827         my ($subloc, $is_deleted, $offset) = $self->find_keyloc( $keytag );
828
829         $fileobj->print_at( $keytag->{offset} + $offset,
830             pack($self->{long_pack}, 0 ),
831             pack( 'C C', $fileobj->transaction_id, 1 ),
832         );
833     }
834
835     return 1;
836 }
837
838 sub bucket_exists {
839     ##
840     # Check existence of single key given tag and MD5 digested key.
841     ##
842     my $self = shift;
843     my ($tag, $md5) = @_;
844
845     #ACID - This is a read. Can find exact or HEAD
846     my ($keyloc) = $self->_find_in_buckets( $tag, $md5 );
847     my $keytag = $self->load_tag( $keyloc );
848     my ($subloc, $is_deleted, $offset) = $self->find_keyloc( $keytag );
849     if ( !$subloc && !$is_deleted ) {
850         ($subloc, $is_deleted, $offset) = $self->find_keyloc( $keytag, 0 );
851     }
852     return ($subloc && !$is_deleted) && 1;
853 }
854
855 sub find_blist {
856     ##
857     # Locate offset for bucket list, given digested key
858     ##
859     my $self = shift;
860     my ($offset, $md5, $args) = @_;
861     $args = {} unless $args;
862
863     ##
864     # Locate offset for bucket list using digest index system
865     ##
866     my $tag = $self->load_tag( $offset )
867         or $self->_throw_error( "INTERNAL ERROR - Cannot find tag" );
868
869     my $ch = 0;
870     while ($tag->{signature} ne SIG_BLIST) {
871         my $num = ord substr($md5, $ch, 1);
872
873         my $ref_loc = $tag->{offset} + ($num * $self->{long_size});
874         $tag = $self->index_lookup( $tag, $num );
875
876         if (!$tag) {
877             return if !$args->{create};
878
879             my $loc = $self->_fileobj->request_space(
880                 $self->tag_size( $self->{bucket_list_size} ),
881             );
882
883             $self->_fileobj->print_at( $ref_loc, pack($self->{long_pack}, $loc) );
884
885             $tag = $self->write_tag(
886                 $loc, SIG_BLIST,
887                 chr(0)x$self->{bucket_list_size},
888             );
889
890             $tag->{ref_loc} = $ref_loc;
891             $tag->{ch} = $ch;
892
893             last;
894         }
895
896         $tag->{ch} = $ch++;
897         $tag->{ref_loc} = $ref_loc;
898     }
899
900     return $tag;
901 }
902
903 sub index_lookup {
904     ##
905     # Given index tag, lookup single entry in index and return .
906     ##
907     my $self = shift;
908     my ($tag, $index) = @_;
909
910     my $location = unpack(
911         $self->{long_pack},
912         substr(
913             $tag->{content},
914             $index * $self->{long_size},
915             $self->{long_size},
916         ),
917     );
918
919     if (!$location) { return; }
920
921     return $self->load_tag( $location );
922 }
923
924 sub traverse_index {
925     ##
926     # Scan index and recursively step into deeper levels, looking for next key.
927     ##
928     my $self = shift;
929     my ($xxxx, $offset, $ch, $force_return_next) = @_;
930
931     my $tag = $self->load_tag( $offset );
932
933     if ($tag->{signature} ne SIG_BLIST) {
934         my $start = $xxxx->{return_next} ? 0 : ord(substr($xxxx->{prev_md5}, $ch, 1));
935
936         for (my $idx = $start; $idx < $self->{hash_chars_used}; $idx++) {
937             my $subloc = unpack(
938                 $self->{long_pack},
939                 substr(
940                     $tag->{content},
941                     $idx * $self->{long_size},
942                     $self->{long_size},
943                 ),
944             );
945
946             if ($subloc) {
947                 my $result = $self->traverse_index(
948                     $xxxx, $subloc, $ch + 1, $force_return_next,
949                 );
950
951                 if (defined $result) { return $result; }
952             }
953         } # index loop
954
955         $xxxx->{return_next} = 1;
956     }
957     # This is the bucket list
958     else {
959         my $keys = $tag->{content};
960         if ($force_return_next) { $xxxx->{return_next} = 1; }
961
962         ##
963         # Iterate through buckets, looking for a key match
964         ##
965         my $transaction_id = $self->_fileobj->transaction_id;
966         for (my $i = 0; $i < $self->{max_buckets}; $i++) {
967             my ($key, $keyloc) = $self->_get_key_subloc( $keys, $i );
968
969             # End of bucket list -- return to outer loop
970             if (!$keyloc) {
971                 $xxxx->{return_next} = 1;
972                 last;
973             }
974             # Located previous key -- return next one found
975             elsif ($key eq $xxxx->{prev_md5}) {
976                 $xxxx->{return_next} = 1;
977                 next;
978             }
979             # Seek to bucket location and skip over signature
980             elsif ($xxxx->{return_next}) {
981                 my $fileobj = $self->_fileobj;
982
983                 my $keytag = $self->load_tag( $keyloc );
984                 my ($subloc, $is_deleted) = $self->find_keyloc( $keytag );
985                 if ( $subloc == 0 && !$is_deleted ) {
986                     ($subloc, $is_deleted) = $self->find_keyloc( $keytag, 0 );
987                 }
988                 next if $is_deleted;
989
990                 # Skip over value to get to plain key
991                 my $sig = $fileobj->read_at( $subloc, SIG_SIZE );
992
993                 my $size = $fileobj->read_at( undef, $self->{data_size} );
994                 $size = unpack($self->{data_pack}, $size);
995                 if ($size) { $fileobj->increment_pointer( $size ); }
996
997                 # Read in plain key and return as scalar
998                 $size = $fileobj->read_at( undef, $self->{data_size} );
999                 $size = unpack($self->{data_pack}, $size);
1000
1001                 my $plain_key;
1002                 if ($size) { $plain_key = $fileobj->read_at( undef, $size); }
1003                 return $plain_key;
1004             }
1005         }
1006
1007         $xxxx->{return_next} = 1;
1008     }
1009
1010     return;
1011 }
1012
1013 # Utilities
1014
1015 sub _get_key_subloc {
1016     my $self = shift;
1017     my ($keys, $idx) = @_;
1018
1019     return unpack(
1020         # This is 'a', not 'A'. Please read the pack() documentation for the
1021         # difference between the two and why it's important.
1022         "a$self->{hash_size} $self->{long_pack}",
1023         substr(
1024             $keys,
1025             ($idx * $self->{bucket_size}),
1026             $self->{bucket_size},
1027         ),
1028     );
1029 }
1030
1031 sub _find_in_buckets {
1032     my $self = shift;
1033     my ($tag, $md5) = @_;
1034
1035     BUCKET:
1036     for ( my $i = 0; $i < $self->{max_buckets}; $i++ ) {
1037         my ($key, $subloc) = $self->_get_key_subloc(
1038             $tag->{content}, $i,
1039         );
1040
1041         my @rv = ($subloc, $i * $self->{bucket_size});
1042
1043         unless ( $subloc ) {
1044             return @rv;
1045         }
1046
1047         next BUCKET if $key ne $md5;
1048
1049         return @rv;
1050     }
1051
1052     return;
1053 }
1054
1055 sub _release_space {
1056     my $self = shift;
1057     my ($size, $loc) = @_;
1058
1059     my $next_loc = 0;
1060
1061     $self->_fileobj->print_at( $loc,
1062         SIG_FREE, 
1063         pack($self->{long_pack}, $size ),
1064         pack($self->{long_pack}, $next_loc ),
1065     );
1066
1067     return;
1068 }
1069
1070 sub _throw_error {
1071     die "DBM::Deep: $_[1]\n";
1072 }
1073
1074 sub _get_dbm_object {
1075     my $item = shift;
1076
1077     my $obj = eval {
1078         local $SIG{__DIE__};
1079         if ($item->isa( 'DBM::Deep' )) {
1080             return $item;
1081         }
1082         return;
1083     };
1084     return $obj if $obj;
1085
1086     my $r = Scalar::Util::reftype( $item ) || '';
1087     if ( $r eq 'HASH' ) {
1088         my $obj = eval {
1089             local $SIG{__DIE__};
1090             my $obj = tied(%$item);
1091             if ($obj->isa( 'DBM::Deep' )) {
1092                 return $obj;
1093             }
1094             return;
1095         };
1096         return $obj if $obj;
1097     }
1098     elsif ( $r eq 'ARRAY' ) {
1099         my $obj = eval {
1100             local $SIG{__DIE__};
1101             my $obj = tied(@$item);
1102             if ($obj->isa( 'DBM::Deep' )) {
1103                 return $obj;
1104             }
1105             return;
1106         };
1107         return $obj if $obj;
1108     }
1109
1110     return;
1111 }
1112
1113 sub _length_needed {
1114     my $self = shift;
1115     my ($value, $key) = @_;
1116
1117     my $is_dbm_deep = eval {
1118         local $SIG{'__DIE__'};
1119         $value->isa( 'DBM::Deep' );
1120     };
1121
1122     my $len = SIG_SIZE
1123             + $self->{data_size} # size for value
1124             + $self->{data_size} # size for key
1125             + length( $key );    # length of key
1126
1127     if ( $is_dbm_deep && $value->_fileobj eq $self->_fileobj ) {
1128         # long_size is for the internal reference
1129         return $len + $self->{long_size};
1130     }
1131
1132     if ( $self->_fileobj->{autobless} ) {
1133         # This is for the bit saying whether or not this thing is blessed.
1134         $len += 1;
1135     }
1136
1137     my $r = Scalar::Util::reftype( $value ) || '';
1138     unless ( $r eq 'HASH' || $r eq 'ARRAY' ) {
1139         if ( defined $value ) {
1140             $len += length( $value );
1141         }
1142         return $len;
1143     }
1144
1145     $len += $self->{index_size};
1146
1147     # if autobless is enabled, must also take into consideration
1148     # the class name as it is stored after the key.
1149     if ( $self->_fileobj->{autobless} ) {
1150         my $c = Scalar::Util::blessed($value);
1151         if ( defined $c && !$is_dbm_deep ) {
1152             $len += $self->{data_size} + length($c);
1153         }
1154     }
1155
1156     return $len;
1157 }
1158
1159 1;
1160 __END__