Improved $| handling
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep.pm
1 package DBM::Deep;
2
3 ##
4 # DBM::Deep
5 #
6 # Description:
7 #       Multi-level database module for storing hash trees, arrays and simple
8 #       key/value pairs into FTP-able, cross-platform binary database files.
9 #
10 #       Type `perldoc DBM::Deep` for complete documentation.
11 #
12 # Usage Examples:
13 #       my %db;
14 #       tie %db, 'DBM::Deep', 'my_database.db'; # standard tie() method
15 #       
16 #       my $db = new DBM::Deep( 'my_database.db' ); # preferred OO method
17 #
18 #       $db->{my_scalar} = 'hello world';
19 #       $db->{my_hash} = { larry => 'genius', hashes => 'fast' };
20 #       $db->{my_array} = [ 1, 2, 3, time() ];
21 #       $db->{my_complex} = [ 'hello', { perl => 'rules' }, 42, 99 ];
22 #       push @{$db->{my_array}}, 'another value';
23 #       my @key_list = keys %{$db->{my_hash}};
24 #       print "This module " . $db->{my_complex}->[1]->{perl} . "!\n";
25 #
26 # Copyright:
27 #       (c) 2002-2005 Joseph Huckaby.  All Rights Reserved.
28 #       This program is free software; you can redistribute it and/or 
29 #       modify it under the same terms as Perl itself.
30 ##
31
32 use strict;
33
34 use FileHandle;
35 use Fcntl qw/:flock/;
36 use Digest::MD5 ();
37 use Scalar::Util ();
38 use vars qw/$VERSION/;
39
40 $VERSION = "0.96";
41
42 ##
43 # Set to 4 and 'N' for 32-bit offset tags (default).  Theoretical limit of 4 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 #my $LONG_SIZE = 4;
50 #my $LONG_PACK = 'N';
51
52 ##
53 # Set to 4 and 'N' for 32-bit data length prefixes.  Limit of 4 GB for each key/value.
54 # Upgrading this is possible (see above) but probably not necessary.  If you need
55 # more than 4 GB for a single key or value, this module is really not for you :-)
56 ##
57 #my $DATA_LENGTH_SIZE = 4;
58 #my $DATA_LENGTH_PACK = 'N';
59 my ($LONG_SIZE, $LONG_PACK, $DATA_LENGTH_SIZE, $DATA_LENGTH_PACK);
60
61 ##
62 # Maximum number of buckets per list before another level of indexing is done.
63 # Increase this value for slightly greater speed, but larger database files.
64 # DO NOT decrease this value below 16, due to risk of recursive reindex overrun.
65 ##
66 my $MAX_BUCKETS = 16;
67
68 ##
69 # Better not adjust anything below here, unless you're me :-)
70 ##
71
72 ##
73 # Setup digest function for keys
74 ##
75 my ($DIGEST_FUNC, $HASH_SIZE);
76 #my $DIGEST_FUNC = \&Digest::MD5::md5;
77
78 ##
79 # Precalculate index and bucket sizes based on values above.
80 ##
81 #my $HASH_SIZE = 16;
82 my ($INDEX_SIZE, $BUCKET_SIZE, $BUCKET_LIST_SIZE);
83
84 set_digest();
85 #set_pack();
86 #precalc_sizes();
87
88 ##
89 # Setup file and tag signatures.  These should never change.
90 ##
91 sub SIG_FILE  () { 'DPDB' }
92 sub SIG_HASH  () { 'H' }
93 sub SIG_ARRAY () { 'A' }
94 sub SIG_NULL  () { 'N' }
95 sub SIG_DATA  () { 'D' }
96 sub SIG_INDEX () { 'I' }
97 sub SIG_BLIST () { 'B' }
98 sub SIG_SIZE  () {  1  }
99
100 ##
101 # Setup constants for users to pass to new()
102 ##
103 sub TYPE_HASH  () { return SIG_HASH; }
104 sub TYPE_ARRAY () { return SIG_ARRAY; }
105
106 sub new {
107         ##
108         # Class constructor method for Perl OO interface.
109         # Calls tie() and returns blessed reference to tied hash or array,
110         # providing a hybrid OO/tie interface.
111         ##
112         my $class = shift;
113         my $args;
114         if (scalar(@_) > 1) { $args = {@_}; }
115         else { $args = { file => shift }; }
116         
117         ##
118         # Check if we want a tied hash or array.
119         ##
120         my $self;
121         if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
122                 tie @$self, $class, %$args;
123         }
124         else {
125                 tie %$self, $class, %$args;
126         }
127
128         return bless $self, $class;
129 }
130
131 {
132     my @outer_params = qw( type base_offset );
133     sub _init {
134         ##
135         # Setup $self and bless into this class.
136         ##
137         my $class = shift;
138         my $args = shift;
139
140         my $self = {
141             type => TYPE_HASH,
142             base_offset => length(SIG_FILE),
143             root => {
144                 file => undef,
145                 fh => undef,
146                 end => 0,
147                 links => 0,
148                 autoflush => undef,
149                 locking => undef,
150                 volatile => undef,
151                 debug => undef,
152                 mode => 'r+',
153                 filter_store_key => undef,
154                 filter_store_value => undef,
155                 filter_fetch_key => undef,
156                 filter_fetch_value => undef,
157                 autobless => undef,
158                 locked => 0,
159                 %$args,
160             },
161         };
162
163         bless $self, $class;
164
165         foreach my $outer_parm ( @outer_params ) {
166             next unless exists $args->{$outer_parm};
167             $self->{$outer_parm} = $args->{$outer_parm}
168         }
169         
170         if ( exists $args->{root} ) {
171             $self->{root} = $args->{root};
172         }
173         else {
174             # This is cleanup based on the fact that the $args
175             # coming in is for both the root and non-root items
176             delete $self->root->{$_} for @outer_params;
177         }
178         $self->root->{links}++;
179
180         if (!defined($self->fh)) { $self->_open(); }
181
182         return $self;
183     }
184 }
185
186 sub _get_self { tied( %{$_[0]} ) || $_[0] }
187
188 sub TIEHASH {
189     ##
190     # Tied hash constructor method, called by Perl's tie() function.
191     ##
192     my $class = shift;
193     my $args;
194     if (scalar(@_) > 1) { $args = {@_}; }
195     #XXX This use of ref() is bad and is a bug
196     elsif (ref($_[0])) { $args = $_[0]; }
197     else { $args = { file => shift }; }
198     
199     $args->{type} = TYPE_HASH;
200
201     return $class->_init($args);
202 }
203
204 sub TIEARRAY {
205 ##
206 # Tied array constructor method, called by Perl's tie() function.
207 ##
208     my $class = shift;
209     my $args;
210     if (scalar(@_) > 1) { $args = {@_}; }
211     #XXX This use of ref() is bad and is a bug
212         elsif (ref($_[0])) { $args = $_[0]; }
213         else { $args = { file => shift }; }
214         
215         $args->{type} = TYPE_ARRAY;
216         
217         return $class->_init($args);
218 }
219
220 sub DESTROY {
221         ##
222         # Class deconstructor.  Close file handle if there are no more refs.
223         ##
224     my $self = _get_self($_[0]);
225     return unless $self;
226         
227         $self->root->{links}--;
228         
229         if (!$self->root->{links}) {
230                 $self->_close();
231         }
232 }
233
234 sub _open {
235         ##
236         # Open a FileHandle to the database, create if nonexistent.
237         # Make sure file signature matches DeepDB spec.
238         ##
239     my $self = _get_self($_[0]);
240
241         if (defined($self->fh)) { $self->_close(); }
242         
243 #    eval {
244         if (!(-e $self->root->{file}) && $self->root->{mode} eq 'r+') {
245             my $temp = FileHandle->new( $self->root->{file}, 'w' );
246         }
247         
248         #XXX Convert to set_fh()
249         $self->root->{fh} = FileHandle->new( $self->root->{file}, $self->root->{mode} );
250 #    }; if ($@ ) { $self->_throw_error( "Received error: $@\n" ); }
251         if (! defined($self->fh)) {
252                 return $self->_throw_error("Cannot open file: " . $self->root->{file} . ": $!");
253         }
254
255     my $fh = $self->fh;
256
257     #XXX Can we remove this by using the right sysopen() flags?
258     binmode $fh; # for win32
259
260     if ($self->root->{autoflush}) {
261 #        $self->fh->autoflush();
262         my $old = select $fh;
263         $|=1;
264         select $old;
265     }
266     
267     my $signature;
268     seek($fh, 0, 0);
269     my $bytes_read = read( $fh, $signature, length(SIG_FILE));
270     
271     ##
272     # File is empty -- write signature and master index
273     ##
274     if (!$bytes_read) {
275         seek($fh, 0, 0);
276         $fh->print(SIG_FILE);
277         $self->root->{end} = length(SIG_FILE);
278         $self->_create_tag($self->base_offset, $self->type, chr(0) x $INDEX_SIZE);
279
280         my $plain_key = "[base]";
281         $fh->print( pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
282         $self->root->{end} += $DATA_LENGTH_SIZE + length($plain_key);
283
284 #        $fh->flush();
285         my $old_fh = select $fh;
286         my $old_af = $|;
287         $| = 1;
288         $| = $old_af;
289         select $old_fh;
290
291         return 1;
292     }
293     
294     ##
295     # Check signature was valid
296     ##
297     unless ($signature eq SIG_FILE) {
298         $self->_close();
299         return $self->_throw_error("Signature not found -- file is not a Deep DB");
300     }
301
302     $self->root->{end} = (stat($fh))[7];
303         
304     ##
305     # Get our type from master index signature
306     ##
307     my $tag = $self->_load_tag($self->base_offset);
308 #XXX We probably also want to store the hash algorithm name and not assume anything
309     if (!$tag) {
310         return $self->_throw_error("Corrupted file, no master index record");
311     }
312     if ($self->{type} ne $tag->{signature}) {
313         return $self->_throw_error("File type mismatch");
314     }
315     
316     return 1;
317 }
318
319 sub _close {
320         ##
321         # Close database FileHandle
322         ##
323     my $self = _get_self($_[0]);
324         undef $self->root->{fh};
325 }
326
327 sub _create_tag {
328         ##
329         # Given offset, signature and content, create tag and write to disk
330         ##
331         my ($self, $offset, $sig, $content) = @_;
332         my $size = length($content);
333         
334     my $fh = $self->fh;
335
336         seek($fh, $offset, 0);
337         $fh->print( $sig . pack($DATA_LENGTH_PACK, $size) . $content );
338         
339         if ($offset == $self->root->{end}) {
340                 $self->root->{end} += SIG_SIZE + $DATA_LENGTH_SIZE + $size;
341         }
342         
343         return {
344                 signature => $sig,
345                 size => $size,
346                 offset => $offset + SIG_SIZE + $DATA_LENGTH_SIZE,
347                 content => $content
348         };
349 }
350
351 sub _load_tag {
352         ##
353         # Given offset, load single tag and return signature, size and data
354         ##
355         my $self = shift;
356         my $offset = shift;
357         
358     my $fh = $self->fh;
359
360         seek($fh, $offset, 0);
361         if (eof $fh) { return undef; }
362         
363         my $sig;
364         read( $fh, $sig, SIG_SIZE);
365         
366         my $size;
367         read( $fh, $size, $DATA_LENGTH_SIZE);
368         $size = unpack($DATA_LENGTH_PACK, $size);
369         
370         my $buffer;
371         read( $fh, $buffer, $size);
372         
373         return {
374                 signature => $sig,
375                 size => $size,
376                 offset => $offset + SIG_SIZE + $DATA_LENGTH_SIZE,
377                 content => $buffer
378         };
379 }
380
381 sub _index_lookup {
382         ##
383         # Given index tag, lookup single entry in index and return .
384         ##
385         my $self = shift;
386         my ($tag, $index) = @_;
387
388         my $location = unpack($LONG_PACK, substr($tag->{content}, $index * $LONG_SIZE, $LONG_SIZE) );
389         if (!$location) { return; }
390         
391         return $self->_load_tag( $location );
392 }
393
394 sub _add_bucket {
395         ##
396         # Adds one key/value pair to bucket list, given offset, MD5 digest of key,
397         # plain (undigested) key and value.
398         ##
399         my $self = shift;
400         my ($tag, $md5, $plain_key, $value) = @_;
401         my $keys = $tag->{content};
402         my $location = 0;
403         my $result = 2;
404
405     my $is_dbm_deep = eval { $value->isa( 'DBM::Deep' ) };
406         my $internal_ref = $is_dbm_deep && ($value->root eq $self->root);
407
408     my $fh = $self->fh;
409
410         ##
411         # Iterate through buckets, seeing if this is a new entry or a replace.
412         ##
413         for (my $i=0; $i<$MAX_BUCKETS; $i++) {
414                 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
415                 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
416                 if (!$subloc) {
417                         ##
418                         # Found empty bucket (end of list).  Populate and exit loop.
419                         ##
420                         $result = 2;
421                         
422             $location = $internal_ref
423                 ? $value->base_offset
424                 : $self->root->{end};
425                         
426                         seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE), 0);
427                         $fh->print( $md5 . pack($LONG_PACK, $location) );
428                         last;
429                 }
430                 elsif ($md5 eq $key) {
431                         ##
432                         # Found existing bucket with same key.  Replace with new value.
433                         ##
434                         $result = 1;
435                         
436                         if ($internal_ref) {
437                                 $location = $value->base_offset;
438                                 seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE), 0);
439                                 $fh->print( $md5 . pack($LONG_PACK, $location) );
440                         }
441                         else {
442                                 seek($fh, $subloc + SIG_SIZE, 0);
443                                 my $size;
444                                 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
445                                 
446                                 ##
447                                 # If value is a hash, array, or raw value with equal or less size, we can
448                                 # reuse the same content area of the database.  Otherwise, we have to create
449                                 # a new content area at the EOF.
450                                 ##
451                                 my $actual_length;
452                 my $r = Scalar::Util::reftype( $value ) || '';
453                 if ( $r eq 'HASH' || $r eq 'ARRAY' ) { $actual_length = $INDEX_SIZE; }
454                                 else { $actual_length = length($value); }
455                                 
456                                 if ($actual_length <= $size) {
457                                         $location = $subloc;
458                                 }
459                                 else {
460                                         $location = $self->root->{end};
461                                         seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE) + $HASH_SIZE, 0);
462                                         $fh->print( pack($LONG_PACK, $location) );
463                                 }
464                         }
465                         last;
466                 }
467         } # i loop
468         
469         ##
470         # If this is an internal reference, return now.
471         # No need to write value or plain key
472         ##
473         if ($internal_ref) {
474         return $result;
475     }
476         
477         ##
478         # If bucket didn't fit into list, split into a new index level
479         ##
480         if (!$location) {
481                 seek($fh, $tag->{ref_loc}, 0);
482                 $fh->print( pack($LONG_PACK, $self->root->{end}) );
483                 
484                 my $index_tag = $self->_create_tag($self->root->{end}, SIG_INDEX, chr(0) x $INDEX_SIZE);
485                 my @offsets = ();
486                 
487                 $keys .= $md5 . pack($LONG_PACK, 0);
488                 
489                 for (my $i=0; $i<=$MAX_BUCKETS; $i++) {
490                         my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
491                         if ($key) {
492                                 my $old_subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
493                                 my $num = ord(substr($key, $tag->{ch} + 1, 1));
494                                 
495                                 if ($offsets[$num]) {
496                                         my $offset = $offsets[$num] + SIG_SIZE + $DATA_LENGTH_SIZE;
497                                         seek($fh, $offset, 0);
498                                         my $subkeys;
499                                         read( $fh, $subkeys, $BUCKET_LIST_SIZE);
500                                         
501                                         for (my $k=0; $k<$MAX_BUCKETS; $k++) {
502                                                 my $subloc = unpack($LONG_PACK, substr($subkeys, ($k * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
503                                                 if (!$subloc) {
504                                                         seek($fh, $offset + ($k * $BUCKET_SIZE), 0);
505                                                         $fh->print( $key . pack($LONG_PACK, $old_subloc || $self->root->{end}) );
506                                                         last;
507                                                 }
508                                         } # k loop
509                                 }
510                                 else {
511                                         $offsets[$num] = $self->root->{end};
512                                         seek($fh, $index_tag->{offset} + ($num * $LONG_SIZE), 0);
513                                         $fh->print( pack($LONG_PACK, $self->root->{end}) );
514                                         
515                                         my $blist_tag = $self->_create_tag($self->root->{end}, SIG_BLIST, chr(0) x $BUCKET_LIST_SIZE);
516                                         
517                                         seek($fh, $blist_tag->{offset}, 0);
518                                         $fh->print( $key . pack($LONG_PACK, $old_subloc || $self->root->{end}) );
519                                 }
520                         } # key is real
521                 } # i loop
522                 
523                 $location ||= $self->root->{end};
524         } # re-index bucket list
525         
526         ##
527         # Seek to content area and store signature, value and plaintext key
528         ##
529         if ($location) {
530                 my $content_length;
531                 seek($fh, $location, 0);
532                 
533                 ##
534                 # Write signature based on content type, set content length and write actual value.
535                 ##
536         my $r = Scalar::Util::reftype($value) || '';
537                 if ($r eq 'HASH') {
538                         $fh->print( TYPE_HASH );
539                         $fh->print( pack($DATA_LENGTH_PACK, $INDEX_SIZE) . chr(0) x $INDEX_SIZE );
540                         $content_length = $INDEX_SIZE;
541                 }
542                 elsif ($r eq 'ARRAY') {
543                         $fh->print( TYPE_ARRAY );
544                         $fh->print( pack($DATA_LENGTH_PACK, $INDEX_SIZE) . chr(0) x $INDEX_SIZE );
545                         $content_length = $INDEX_SIZE;
546                 }
547                 elsif (!defined($value)) {
548                         $fh->print( SIG_NULL );
549                         $fh->print( pack($DATA_LENGTH_PACK, 0) );
550                         $content_length = 0;
551                 }
552                 else {
553                         $fh->print( SIG_DATA );
554                         $fh->print( pack($DATA_LENGTH_PACK, length($value)) . $value );
555                         $content_length = length($value);
556                 }
557                 
558                 ##
559                 # Plain key is stored AFTER value, as keys are typically fetched less often.
560                 ##
561                 $fh->print( pack($DATA_LENGTH_PACK, length($plain_key)) . $plain_key );
562                 
563                 ##
564                 # If value is blessed, preserve class name
565                 ##
566                 if ( $self->root->{autobless} ) {
567             my $value_class = Scalar::Util::blessed($value);
568             if ( defined $value_class && $value_class ne 'DBM::Deep' ) {
569                 ##
570                 # Blessed ref -- will restore later
571                 ##
572                 $fh->print( chr(1) );
573                 $fh->print( pack($DATA_LENGTH_PACK, length($value_class)) . $value_class );
574                 $content_length += 1;
575                 $content_length += $DATA_LENGTH_SIZE + length($value_class);
576             }
577             else {
578                 $fh->print( chr(0) );
579                 $content_length += 1;
580             }
581         }
582             
583                 ##
584                 # If this is a new content area, advance EOF counter
585                 ##
586                 if ($location == $self->root->{end}) {
587                         $self->root->{end} += SIG_SIZE;
588                         $self->root->{end} += $DATA_LENGTH_SIZE + $content_length;
589                         $self->root->{end} += $DATA_LENGTH_SIZE + length($plain_key);
590                 }
591                 
592                 ##
593                 # If content is a hash or array, create new child DeepDB object and
594                 # pass each key or element to it.
595                 ##
596                 if ($r eq 'HASH') {
597                         my $branch = DBM::Deep->new(
598                                 type => TYPE_HASH,
599                                 base_offset => $location,
600                                 root => $self->root,
601                         );
602                         foreach my $key (keys %{$value}) {
603                                 $branch->{$key} = $value->{$key};
604                         }
605                 }
606                 elsif ($r eq 'ARRAY') {
607                         my $branch = DBM::Deep->new(
608                                 type => TYPE_ARRAY,
609                                 base_offset => $location,
610                                 root => $self->root,
611                         );
612                         my $index = 0;
613                         foreach my $element (@{$value}) {
614                                 $branch->[$index] = $element;
615                                 $index++;
616                         }
617                 }
618                 
619                 return $result;
620         }
621         
622         return $self->_throw_error("Fatal error: indexing failed -- possibly due to corruption in file");
623 }
624
625 sub _get_bucket_value {
626         ##
627         # Fetch single value given tag and MD5 digested key.
628         ##
629         my $self = shift;
630         my ($tag, $md5) = @_;
631         my $keys = $tag->{content};
632
633     my $fh = $self->fh;
634         
635         ##
636         # Iterate through buckets, looking for a key match
637         ##
638     BUCKET:
639         for (my $i=0; $i<$MAX_BUCKETS; $i++) {
640                 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
641                 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
642
643                 if (!$subloc) {
644                         ##
645                         # Hit end of list, no match
646                         ##
647                         return;
648                 }
649
650         if ( $md5 ne $key ) {
651             next BUCKET;
652         }
653
654         ##
655         # Found match -- seek to offset and read signature
656         ##
657         my $signature;
658         seek($fh, $subloc, 0);
659         read( $fh, $signature, SIG_SIZE);
660         
661         ##
662         # If value is a hash or array, return new DeepDB object with correct offset
663         ##
664         if (($signature eq TYPE_HASH) || ($signature eq TYPE_ARRAY)) {
665             my $obj = DBM::Deep->new(
666                 type => $signature,
667                 base_offset => $subloc,
668                 root => $self->root
669             );
670             
671             if ($self->root->{autobless}) {
672                 ##
673                 # Skip over value and plain key to see if object needs
674                 # to be re-blessed
675                 ##
676                 seek($fh, $DATA_LENGTH_SIZE + $INDEX_SIZE, 1);
677                 
678                 my $size;
679                 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
680                 if ($size) { seek($fh, $size, 1); }
681                 
682                 my $bless_bit;
683                 read( $fh, $bless_bit, 1);
684                 if (ord($bless_bit)) {
685                     ##
686                     # Yes, object needs to be re-blessed
687                     ##
688                     my $class_name;
689                     read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
690                     if ($size) { read( $fh, $class_name, $size); }
691                     if ($class_name) { $obj = bless( $obj, $class_name ); }
692                 }
693             }
694             
695             return $obj;
696         }
697         
698         ##
699         # Otherwise return actual value
700         ##
701         elsif ($signature eq SIG_DATA) {
702             my $size;
703             my $value = '';
704             read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
705             if ($size) { read( $fh, $value, $size); }
706             return $value;
707         }
708         
709         ##
710         # Key exists, but content is null
711         ##
712         else { return; }
713         } # i loop
714
715         return;
716 }
717
718 sub _delete_bucket {
719         ##
720         # Delete single key/value pair given tag and MD5 digested key.
721         ##
722         my $self = shift;
723         my ($tag, $md5) = @_;
724         my $keys = $tag->{content};
725
726     my $fh = $self->fh;
727         
728         ##
729         # Iterate through buckets, looking for a key match
730         ##
731     BUCKET:
732         for (my $i=0; $i<$MAX_BUCKETS; $i++) {
733                 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
734                 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
735
736                 if (!$subloc) {
737                         ##
738                         # Hit end of list, no match
739                         ##
740                         return;
741                 }
742
743         if ( $md5 ne $key ) {
744             next BUCKET;
745         }
746
747         ##
748         # Matched key -- delete bucket and return
749         ##
750         seek($fh, $tag->{offset} + ($i * $BUCKET_SIZE), 0);
751         $fh->print( substr($keys, ($i+1) * $BUCKET_SIZE ) );
752         $fh->print( chr(0) x $BUCKET_SIZE );
753         
754         return 1;
755         } # i loop
756
757         return;
758 }
759
760 sub _bucket_exists {
761         ##
762         # Check existence of single key given tag and MD5 digested key.
763         ##
764         my $self = shift;
765         my ($tag, $md5) = @_;
766         my $keys = $tag->{content};
767         
768         ##
769         # Iterate through buckets, looking for a key match
770         ##
771     BUCKET:
772         for (my $i=0; $i<$MAX_BUCKETS; $i++) {
773                 my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
774                 my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
775
776                 if (!$subloc) {
777                         ##
778                         # Hit end of list, no match
779                         ##
780                         return;
781                 }
782
783         if ( $md5 ne $key ) {
784             next BUCKET;
785         }
786
787         ##
788         # Matched key -- return true
789         ##
790         return 1;
791         } # i loop
792
793         return;
794 }
795
796 sub _find_bucket_list {
797         ##
798         # Locate offset for bucket list, given digested key
799         ##
800         my $self = shift;
801         my $md5 = shift;
802         
803         ##
804         # Locate offset for bucket list using digest index system
805         ##
806         my $ch = 0;
807         my $tag = $self->_load_tag($self->base_offset);
808         if (!$tag) { return; }
809         
810         while ($tag->{signature} ne SIG_BLIST) {
811                 $tag = $self->_index_lookup($tag, ord(substr($md5, $ch, 1)));
812                 if (!$tag) { return; }
813                 $ch++;
814         }
815         
816         return $tag;
817 }
818
819 sub _traverse_index {
820         ##
821         # Scan index and recursively step into deeper levels, looking for next key.
822         ##
823     my ($self, $offset, $ch, $force_return_next) = @_;
824     $force_return_next = undef unless $force_return_next;
825         
826         my $tag = $self->_load_tag( $offset );
827
828     my $fh = $self->fh;
829         
830         if ($tag->{signature} ne SIG_BLIST) {
831                 my $content = $tag->{content};
832                 my $start;
833                 if ($self->{return_next}) { $start = 0; }
834                 else { $start = ord(substr($self->{prev_md5}, $ch, 1)); }
835                 
836                 for (my $index = $start; $index < 256; $index++) {
837                         my $subloc = unpack($LONG_PACK, substr($content, $index * $LONG_SIZE, $LONG_SIZE) );
838                         if ($subloc) {
839                                 my $result = $self->_traverse_index( $subloc, $ch + 1, $force_return_next );
840                                 if (defined($result)) { return $result; }
841                         }
842                 } # index loop
843                 
844                 $self->{return_next} = 1;
845         } # tag is an index
846         
847         elsif ($tag->{signature} eq SIG_BLIST) {
848                 my $keys = $tag->{content};
849                 if ($force_return_next) { $self->{return_next} = 1; }
850                 
851                 ##
852                 # Iterate through buckets, looking for a key match
853                 ##
854                 for (my $i=0; $i<$MAX_BUCKETS; $i++) {
855                         my $key = substr($keys, $i * $BUCKET_SIZE, $HASH_SIZE);
856                         my $subloc = unpack($LONG_PACK, substr($keys, ($i * $BUCKET_SIZE) + $HASH_SIZE, $LONG_SIZE));
857         
858                         if (!$subloc) {
859                                 ##
860                                 # End of bucket list -- return to outer loop
861                                 ##
862                                 $self->{return_next} = 1;
863                                 last;
864                         }
865                         elsif ($key eq $self->{prev_md5}) {
866                                 ##
867                                 # Located previous key -- return next one found
868                                 ##
869                                 $self->{return_next} = 1;
870                                 next;
871                         }
872                         elsif ($self->{return_next}) {
873                                 ##
874                                 # Seek to bucket location and skip over signature
875                                 ##
876                                 seek($fh, $subloc + SIG_SIZE, 0);
877                                 
878                                 ##
879                                 # Skip over value to get to plain key
880                                 ##
881                                 my $size;
882                                 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
883                                 if ($size) { seek($fh, $size, 1); }
884                                 
885                                 ##
886                                 # Read in plain key and return as scalar
887                                 ##
888                                 my $plain_key;
889                                 read( $fh, $size, $DATA_LENGTH_SIZE); $size = unpack($DATA_LENGTH_PACK, $size);
890                                 if ($size) { read( $fh, $plain_key, $size); }
891                                 
892                                 return $plain_key;
893                         }
894                 } # bucket loop
895                 
896                 $self->{return_next} = 1;
897         } # tag is a bucket list
898         
899         return;
900 }
901
902 sub _get_next_key {
903         ##
904         # Locate next key, given digested previous one
905         ##
906     my $self = _get_self($_[0]);
907         
908         $self->{prev_md5} = $_[1] ? $_[1] : undef;
909         $self->{return_next} = 0;
910         
911         ##
912         # If the previous key was not specifed, start at the top and
913         # return the first one found.
914         ##
915         if (!$self->{prev_md5}) {
916                 $self->{prev_md5} = chr(0) x $HASH_SIZE;
917                 $self->{return_next} = 1;
918         }
919         
920         return $self->_traverse_index( $self->base_offset, 0 );
921 }
922
923 sub lock {
924         ##
925         # If db locking is set, flock() the db file.  If called multiple
926         # times before unlock(), then the same number of unlocks() must
927         # be called before the lock is released.
928         ##
929     my $self = _get_self($_[0]);
930         my $type = $_[1];
931     $type = LOCK_EX unless defined $type;
932         
933         if ($self->root->{locking}) {
934                 if (!$self->root->{locked}) { flock($self->fh, $type); }
935                 $self->root->{locked}++;
936         }
937 }
938
939 sub unlock {
940         ##
941         # If db locking is set, unlock the db file.  See note in lock()
942         # regarding calling lock() multiple times.
943         ##
944     my $self = _get_self($_[0]);
945         
946         if ($self->root->{locking} && $self->root->{locked} > 0) {
947                 $self->root->{locked}--;
948                 if (!$self->root->{locked}) { flock($self->fh, LOCK_UN); }
949         }
950 }
951
952 #XXX These uses of ref() need verified
953 sub _copy_node {
954         ##
955         # Copy single level of keys or elements to new DB handle.
956         # Recurse for nested structures
957         ##
958     my $self = _get_self($_[0]);
959         my $db_temp = $_[1];
960
961         if ($self->type eq TYPE_HASH) {
962                 my $key = $self->first_key();
963                 while ($key) {
964                         my $value = $self->get($key);
965 #XXX This doesn't work with autobless
966                         if (!ref($value)) { $db_temp->{$key} = $value; }
967                         else {
968                                 my $type = $value->type;
969                                 if ($type eq TYPE_HASH) { $db_temp->{$key} = {}; }
970                                 else { $db_temp->{$key} = []; }
971                                 $value->_copy_node( $db_temp->{$key} );
972                         }
973                         $key = $self->next_key($key);
974                 }
975         }
976         else {
977                 my $length = $self->length();
978                 for (my $index = 0; $index < $length; $index++) {
979                         my $value = $self->get($index);
980                         if (!ref($value)) { $db_temp->[$index] = $value; }
981             #XXX NO tests for this code
982                         else {
983                                 my $type = $value->type;
984                                 if ($type eq TYPE_HASH) { $db_temp->[$index] = {}; }
985                                 else { $db_temp->[$index] = []; }
986                                 $value->_copy_node( $db_temp->[$index] );
987                         }
988                 }
989         }
990 }
991
992 sub export {
993         ##
994         # Recursively export into standard Perl hashes and arrays.
995         ##
996     my $self = _get_self($_[0]);
997         
998         my $temp;
999         if ($self->type eq TYPE_HASH) { $temp = {}; }
1000         elsif ($self->type eq TYPE_ARRAY) { $temp = []; }
1001         
1002         $self->lock();
1003         $self->_copy_node( $temp );
1004         $self->unlock();
1005         
1006         return $temp;
1007 }
1008
1009 sub import {
1010         ##
1011         # Recursively import Perl hash/array structure
1012         ##
1013     #XXX This use of ref() seems to be ok
1014         if (!ref($_[0])) { return; } # Perl calls import() on use -- ignore
1015         
1016     my $self = _get_self($_[0]);
1017         my $struct = $_[1];
1018         
1019     #XXX This use of ref() seems to be ok
1020         if (!ref($struct)) {
1021                 ##
1022                 # struct is not a reference, so just import based on our type
1023                 ##
1024                 shift @_;
1025                 
1026                 if ($self->type eq TYPE_HASH) { $struct = {@_}; }
1027                 elsif ($self->type eq TYPE_ARRAY) { $struct = [@_]; }
1028         }
1029         
1030     my $r = Scalar::Util::reftype($struct) || '';
1031         if ($r eq "HASH" && $self->type eq TYPE_HASH) {
1032                 foreach my $key (keys %$struct) { $self->put($key, $struct->{$key}); }
1033         }
1034         elsif ($r eq "ARRAY" && $self->type eq TYPE_ARRAY) {
1035                 $self->push( @$struct );
1036         }
1037         else {
1038                 return $self->_throw_error("Cannot import: type mismatch");
1039         }
1040         
1041         return 1;
1042 }
1043
1044 sub optimize {
1045         ##
1046         # Rebuild entire database into new file, then move
1047         # it back on top of original.
1048         ##
1049     my $self = _get_self($_[0]);
1050         if ($self->root->{links} > 1) {
1051                 return $self->_throw_error("Cannot optimize: reference count is greater than 1");
1052         }
1053         
1054         my $db_temp = DBM::Deep->new(
1055                 file => $self->root->{file} . '.tmp',
1056                 type => $self->type
1057         );
1058         if (!$db_temp) {
1059                 return $self->_throw_error("Cannot optimize: failed to open temp file: $!");
1060         }
1061         
1062         $self->lock();
1063         $self->_copy_node( $db_temp );
1064         undef $db_temp;
1065         
1066         ##
1067         # Attempt to copy user, group and permissions over to new file
1068         ##
1069         my @stats = stat($self->fh);
1070         my $perms = $stats[2] & 07777;
1071         my $uid = $stats[4];
1072         my $gid = $stats[5];
1073         chown( $uid, $gid, $self->root->{file} . '.tmp' );
1074         chmod( $perms, $self->root->{file} . '.tmp' );
1075         
1076     # q.v. perlport for more information on this variable
1077     if ( $^O eq 'MSWin32' ) {
1078                 ##
1079                 # Potential race condition when optmizing on Win32 with locking.
1080                 # The Windows filesystem requires that the filehandle be closed 
1081                 # before it is overwritten with rename().  This could be redone
1082                 # with a soft copy.
1083                 ##
1084                 $self->unlock();
1085                 $self->_close();
1086         }
1087         
1088         if (!rename $self->root->{file} . '.tmp', $self->root->{file}) {
1089                 unlink $self->root->{file} . '.tmp';
1090                 $self->unlock();
1091                 return $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
1092         }
1093         
1094         $self->unlock();
1095         $self->_close();
1096         $self->_open();
1097         
1098         return 1;
1099 }
1100
1101 sub clone {
1102         ##
1103         # Make copy of object and return
1104         ##
1105     my $self = _get_self($_[0]);
1106         
1107         return DBM::Deep->new(
1108                 type => $self->type,
1109                 base_offset => $self->base_offset,
1110                 root => $self->root
1111         );
1112 }
1113
1114 {
1115     my %is_legal_filter = map {
1116         $_ => ~~1,
1117     } qw(
1118         store_key store_value
1119         fetch_key fetch_value
1120     );
1121
1122     sub set_filter {
1123         ##
1124         # Setup filter function for storing or fetching the key or value
1125         ##
1126         my $self = _get_self($_[0]);
1127         my $type = lc $_[1];
1128         my $func = $_[2] ? $_[2] : undef;
1129         
1130         if ( $is_legal_filter{$type} ) {
1131             $self->root->{"filter_$type"} = $func;
1132             return 1;
1133         }
1134
1135         return;
1136     }
1137 }
1138
1139 ##
1140 # Accessor methods
1141 ##
1142
1143 sub root {
1144         ##
1145         # Get access to the root structure
1146         ##
1147     my $self = _get_self($_[0]);
1148         return $self->{root};
1149 }
1150
1151 sub fh {
1152         ##
1153         # Get access to the raw FileHandle
1154         ##
1155     #XXX It will be useful, though, when we split out HASH and ARRAY
1156     my $self = _get_self($_[0]);
1157         return $self->root->{fh};
1158 }
1159
1160 sub type {
1161         ##
1162         # Get type of current node (TYPE_HASH or TYPE_ARRAY)
1163         ##
1164     my $self = _get_self($_[0]);
1165         return $self->{type};
1166 }
1167
1168 sub base_offset {
1169         ##
1170         # Get base_offset of current node (TYPE_HASH or TYPE_ARRAY)
1171         ##
1172     my $self = _get_self($_[0]);
1173         return $self->{base_offset};
1174 }
1175
1176 sub error {
1177         ##
1178         # Get last error string, or undef if no error
1179         ##
1180         return $_[0]
1181         ? ( _get_self($_[0])->{root}->{error} or undef )
1182         : $@;
1183 }
1184
1185 ##
1186 # Utility methods
1187 ##
1188
1189 sub _throw_error {
1190         ##
1191         # Store error string in self
1192         ##
1193     my $self = _get_self($_[0]);
1194         my $error_text = $_[1];
1195         
1196         $self->root->{error} = $error_text;
1197         
1198         unless ($self->root->{debug}) {
1199         die "DBM::Deep: $error_text\n";
1200     }
1201
1202     warn "DBM::Deep: $error_text\n";
1203         return;
1204 }
1205
1206 sub clear_error {
1207         ##
1208         # Clear error state
1209         ##
1210     my $self = _get_self($_[0]);
1211         
1212         undef $self->root->{error};
1213 }
1214
1215 sub precalc_sizes {
1216         ##
1217         # Precalculate index, bucket and bucket list sizes
1218         ##
1219
1220     #XXX I don't like this ...
1221     set_pack() unless defined $LONG_SIZE;
1222
1223         $INDEX_SIZE = 256 * $LONG_SIZE;
1224         $BUCKET_SIZE = $HASH_SIZE + $LONG_SIZE;
1225         $BUCKET_LIST_SIZE = $MAX_BUCKETS * $BUCKET_SIZE;
1226 }
1227
1228 sub set_pack {
1229         ##
1230         # Set pack/unpack modes (see file header for more)
1231         ##
1232     my ($long_s, $long_p, $data_s, $data_p) = @_;
1233
1234     $LONG_SIZE = $long_s ? $long_s : 4;
1235     $LONG_PACK = $long_p ? $long_p : 'N';
1236
1237     $DATA_LENGTH_SIZE = $data_s ? $data_s : 4;
1238     $DATA_LENGTH_PACK = $data_p ? $data_p : 'N';
1239
1240         precalc_sizes();
1241 }
1242
1243 sub set_digest {
1244         ##
1245         # Set key digest function (default is MD5)
1246         ##
1247     my ($digest_func, $hash_size) = @_;
1248
1249     $DIGEST_FUNC = $digest_func ? $digest_func : \&Digest::MD5::md5;
1250     $HASH_SIZE = $hash_size ? $hash_size : 16;
1251
1252         precalc_sizes();
1253 }
1254
1255 ##
1256 # tie() methods (hashes and arrays)
1257 ##
1258
1259 sub STORE {
1260         ##
1261         # Store single hash key/value or array element in database.
1262         ##
1263     my $self = _get_self($_[0]);
1264         my $key = ($self->root->{filter_store_key} && $self->type eq TYPE_HASH) ? $self->root->{filter_store_key}->($_[1]) : $_[1];
1265     #XXX What is ref() checking here?
1266     #YYY User may be storing a hash, in which case we do not want it run 
1267     #YYY through the filtering system
1268         my $value = ($self->root->{filter_store_value} && !ref($_[2])) ? $self->root->{filter_store_value}->($_[2]) : $_[2];
1269         
1270         my $unpacked_key = $key;
1271         if (($self->type eq TYPE_ARRAY) && ($key =~ /^\d+$/)) { $key = pack($LONG_PACK, $key); }
1272         my $md5 = $DIGEST_FUNC->($key);
1273         
1274         ##
1275         # Make sure file is open
1276         ##
1277         if (!defined($self->fh) && !$self->_open()) {
1278                 return;
1279         }
1280
1281     my $fh = $self->fh;
1282         
1283         ##
1284         # Request exclusive lock for writing
1285         ##
1286         $self->lock( LOCK_EX );
1287
1288         ##
1289         # If locking is enabled, set 'end' parameter again, in case another
1290         # DB instance appended to our file while we were unlocked.
1291         ##
1292         if ($self->root->{locking} || $self->root->{volatile}) {
1293                 $self->root->{end} = (stat($fh))[7];
1294         }
1295         
1296         ##
1297         # Locate offset for bucket list using digest index system
1298         ##
1299         my $tag = $self->_load_tag($self->base_offset);
1300         if (!$tag) {
1301                 $tag = $self->_create_tag($self->base_offset, SIG_INDEX, chr(0) x $INDEX_SIZE);
1302         }
1303         
1304         my $ch = 0;
1305         while ($tag->{signature} ne SIG_BLIST) {
1306                 my $num = ord(substr($md5, $ch, 1));
1307                 my $new_tag = $self->_index_lookup($tag, $num);
1308                 if (!$new_tag) {
1309                         my $ref_loc = $tag->{offset} + ($num * $LONG_SIZE);
1310                         seek($fh, $ref_loc, 0);
1311                         $fh->print( pack($LONG_PACK, $self->root->{end}) );
1312                         
1313                         $tag = $self->_create_tag($self->root->{end}, SIG_BLIST, chr(0) x $BUCKET_LIST_SIZE);
1314                         $tag->{ref_loc} = $ref_loc;
1315                         $tag->{ch} = $ch;
1316                         last;
1317                 }
1318                 else {
1319                         my $ref_loc = $tag->{offset} + ($num * $LONG_SIZE);
1320                         $tag = $new_tag;
1321                         $tag->{ref_loc} = $ref_loc;
1322                         $tag->{ch} = $ch;
1323                 }
1324                 $ch++;
1325         }
1326         
1327         ##
1328         # Add key/value to bucket list
1329         ##
1330         my $result = $self->_add_bucket( $tag, $md5, $key, $value );
1331         
1332         ##
1333         # If this object is an array, and bucket was not a replace, and key is numerical,
1334         # and index is equal or greater than current length, advance length variable.
1335         ##
1336         if (($result == 2) && ($self->type eq TYPE_ARRAY) && ($unpacked_key =~ /^\d+$/) && ($unpacked_key >= $self->FETCHSIZE())) {
1337                 $self->STORESIZE( $unpacked_key + 1 );
1338         }
1339         
1340         $self->unlock();
1341
1342         return $result;
1343 }
1344
1345 sub FETCH {
1346         ##
1347         # Fetch single value or element given plain key or array index
1348         ##
1349     my $self = _get_self($_[0]);
1350
1351     my $key = $_[1];
1352     if ( $self->type eq TYPE_HASH ) {
1353         if ( my $filter = $self->root->{filter_store_key} ) {
1354             $key = $filter->( $key );
1355         }
1356     }
1357     elsif ( $self->type eq TYPE_ARRAY ) { 
1358         if ( $key =~ /^\d+$/ ) {
1359             $key = pack($LONG_PACK, $key);
1360         }
1361     }
1362
1363         my $md5 = $DIGEST_FUNC->($key);
1364
1365         ##
1366         # Make sure file is open
1367         ##
1368         if (!defined($self->fh)) { $self->_open(); }
1369         
1370         ##
1371         # Request shared lock for reading
1372         ##
1373         $self->lock( LOCK_SH );
1374         
1375         my $tag = $self->_find_bucket_list( $md5 );
1376         if (!$tag) {
1377                 $self->unlock();
1378                 return;
1379         }
1380         
1381         ##
1382         # Get value from bucket list
1383         ##
1384         my $result = $self->_get_bucket_value( $tag, $md5 );
1385         
1386         $self->unlock();
1387         
1388     #XXX What is ref() checking here?
1389         return ($result && !ref($result) && $self->root->{filter_fetch_value}) ? $self->root->{filter_fetch_value}->($result) : $result;
1390 }
1391
1392 sub DELETE {
1393         ##
1394         # Delete single key/value pair or element given plain key or array index
1395         ##
1396     my $self = _get_self($_[0]);
1397         my $key = ($self->root->{filter_store_key} && $self->type eq TYPE_HASH) ? $self->root->{filter_store_key}->($_[1]) : $_[1];
1398         
1399         my $unpacked_key = $key;
1400         if (($self->type eq TYPE_ARRAY) && ($key =~ /^\d+$/)) { $key = pack($LONG_PACK, $key); }
1401         my $md5 = $DIGEST_FUNC->($key);
1402
1403         ##
1404         # Make sure file is open
1405         ##
1406         if (!defined($self->fh)) { $self->_open(); }
1407         
1408         ##
1409         # Request exclusive lock for writing
1410         ##
1411         $self->lock( LOCK_EX );
1412         
1413         my $tag = $self->_find_bucket_list( $md5 );
1414         if (!$tag) {
1415                 $self->unlock();
1416                 return;
1417         }
1418         
1419         ##
1420         # Delete bucket
1421         ##
1422         my $result = $self->_delete_bucket( $tag, $md5 );
1423         
1424         ##
1425         # If this object is an array and the key deleted was on the end of the stack,
1426         # decrement the length variable.
1427         ##
1428         if ($result && ($self->type eq TYPE_ARRAY) && ($unpacked_key == $self->FETCHSIZE() - 1)) {
1429                 $self->STORESIZE( $unpacked_key );
1430         }
1431         
1432         $self->unlock();
1433         
1434         return $result;
1435 }
1436
1437 sub EXISTS {
1438         ##
1439         # Check if a single key or element exists given plain key or array index
1440         ##
1441     my $self = _get_self($_[0]);
1442         my $key = ($self->root->{filter_store_key} && $self->type eq TYPE_HASH) ? $self->root->{filter_store_key}->($_[1]) : $_[1];
1443         
1444         if (($self->type eq TYPE_ARRAY) && ($key =~ /^\d+$/)) { $key = pack($LONG_PACK, $key); }
1445         my $md5 = $DIGEST_FUNC->($key);
1446
1447         ##
1448         # Make sure file is open
1449         ##
1450         if (!defined($self->fh)) { $self->_open(); }
1451         
1452         ##
1453         # Request shared lock for reading
1454         ##
1455         $self->lock( LOCK_SH );
1456         
1457         my $tag = $self->_find_bucket_list( $md5 );
1458         
1459         ##
1460         # For some reason, the built-in exists() function returns '' for false
1461         ##
1462         if (!$tag) {
1463                 $self->unlock();
1464                 return '';
1465         }
1466         
1467         ##
1468         # Check if bucket exists and return 1 or ''
1469         ##
1470         my $result = $self->_bucket_exists( $tag, $md5 ) || '';
1471         
1472         $self->unlock();
1473         
1474         return $result;
1475 }
1476
1477 sub CLEAR {
1478         ##
1479         # Clear all keys from hash, or all elements from array.
1480         ##
1481     my $self = _get_self($_[0]);
1482
1483         ##
1484         # Make sure file is open
1485         ##
1486         if (!defined($self->fh)) { $self->_open(); }
1487         
1488         ##
1489         # Request exclusive lock for writing
1490         ##
1491         $self->lock( LOCK_EX );
1492         
1493     my $fh = $self->fh;
1494
1495         seek($fh, $self->base_offset, 0);
1496         if (eof $fh) {
1497                 $self->unlock();
1498                 return;
1499         }
1500         
1501         $self->_create_tag($self->base_offset, $self->type, chr(0) x $INDEX_SIZE);
1502         
1503         $self->unlock();
1504         
1505         return 1;
1506 }
1507
1508 sub FIRSTKEY {
1509         ##
1510         # Locate and return first key (in no particular order)
1511         ##
1512     my $self = _get_self($_[0]);
1513         if ($self->type ne TYPE_HASH) {
1514                 return $self->_throw_error("FIRSTKEY method only supported for hashes");
1515         }
1516
1517         ##
1518         # Make sure file is open
1519         ##
1520         if (!defined($self->fh)) { $self->_open(); }
1521         
1522         ##
1523         # Request shared lock for reading
1524         ##
1525         $self->lock( LOCK_SH );
1526         
1527         my $result = $self->_get_next_key();
1528         
1529         $self->unlock();
1530         
1531         return ($result && $self->root->{filter_fetch_key}) ? $self->root->{filter_fetch_key}->($result) : $result;
1532 }
1533
1534 sub NEXTKEY {
1535         ##
1536         # Return next key (in no particular order), given previous one
1537         ##
1538     my $self = _get_self($_[0]);
1539         if ($self->type ne TYPE_HASH) {
1540                 return $self->_throw_error("NEXTKEY method only supported for hashes");
1541         }
1542         my $prev_key = ($self->root->{filter_store_key} && $self->type eq TYPE_HASH) ? $self->root->{filter_store_key}->($_[1]) : $_[1];
1543         my $prev_md5 = $DIGEST_FUNC->($prev_key);
1544
1545         ##
1546         # Make sure file is open
1547         ##
1548         if (!defined($self->fh)) { $self->_open(); }
1549         
1550         ##
1551         # Request shared lock for reading
1552         ##
1553         $self->lock( LOCK_SH );
1554         
1555         my $result = $self->_get_next_key( $prev_md5 );
1556         
1557         $self->unlock();
1558         
1559         return ($result && $self->root->{filter_fetch_key}) ? $self->root->{filter_fetch_key}->($result) : $result;
1560 }
1561
1562 ##
1563 # The following methods are for arrays only
1564 ##
1565
1566 sub FETCHSIZE {
1567         ##
1568         # Return the length of the array
1569         ##
1570     my $self = _get_self($_[0]);
1571         if ($self->type ne TYPE_ARRAY) {
1572                 return $self->_throw_error("FETCHSIZE method only supported for arrays");
1573         }
1574         
1575         my $SAVE_FILTER = $self->root->{filter_fetch_value};
1576         $self->root->{filter_fetch_value} = undef;
1577         
1578         my $packed_size = $self->FETCH('length');
1579         
1580         $self->root->{filter_fetch_value} = $SAVE_FILTER;
1581         
1582         if ($packed_size) { return int(unpack($LONG_PACK, $packed_size)); }
1583         else { return 0; } 
1584 }
1585
1586 sub STORESIZE {
1587         ##
1588         # Set the length of the array
1589         ##
1590     my $self = _get_self($_[0]);
1591         if ($self->type ne TYPE_ARRAY) {
1592                 return $self->_throw_error("STORESIZE method only supported for arrays");
1593         }
1594         my $new_length = $_[1];
1595         
1596         my $SAVE_FILTER = $self->root->{filter_store_value};
1597         $self->root->{filter_store_value} = undef;
1598         
1599         my $result = $self->STORE('length', pack($LONG_PACK, $new_length));
1600         
1601         $self->root->{filter_store_value} = $SAVE_FILTER;
1602         
1603         return $result;
1604 }
1605
1606 sub POP {
1607         ##
1608         # Remove and return the last element on the array
1609         ##
1610     my $self = _get_self($_[0]);
1611         if ($self->type ne TYPE_ARRAY) {
1612                 return $self->_throw_error("POP method only supported for arrays");
1613         }
1614         my $length = $self->FETCHSIZE();
1615         
1616         if ($length) {
1617                 my $content = $self->FETCH( $length - 1 );
1618                 $self->DELETE( $length - 1 );
1619                 return $content;
1620         }
1621         else {
1622                 return;
1623         }
1624 }
1625
1626 sub PUSH {
1627         ##
1628         # Add new element(s) to the end of the array
1629         ##
1630     my $self = _get_self(shift);
1631         if ($self->type ne TYPE_ARRAY) {
1632                 return $self->_throw_error("PUSH method only supported for arrays");
1633         }
1634         my $length = $self->FETCHSIZE();
1635         
1636         while (my $content = shift @_) {
1637                 $self->STORE( $length, $content );
1638                 $length++;
1639         }
1640 }
1641
1642 sub SHIFT {
1643         ##
1644         # Remove and return first element on the array.
1645         # Shift over remaining elements to take up space.
1646         ##
1647     my $self = _get_self($_[0]);
1648         if ($self->type ne TYPE_ARRAY) {
1649                 return $self->_throw_error("SHIFT method only supported for arrays");
1650         }
1651         my $length = $self->FETCHSIZE();
1652         
1653         if ($length) {
1654                 my $content = $self->FETCH( 0 );
1655                 
1656                 ##
1657                 # Shift elements over and remove last one.
1658                 ##
1659                 for (my $i = 0; $i < $length - 1; $i++) {
1660                         $self->STORE( $i, $self->FETCH($i + 1) );
1661                 }
1662                 $self->DELETE( $length - 1 );
1663                 
1664                 return $content;
1665         }
1666         else {
1667                 return;
1668         }
1669 }
1670
1671 sub UNSHIFT {
1672         ##
1673         # Insert new element(s) at beginning of array.
1674         # Shift over other elements to make space.
1675         ##
1676     my $self = _get_self($_[0]);shift @_;
1677         if ($self->type ne TYPE_ARRAY) {
1678                 return $self->_throw_error("UNSHIFT method only supported for arrays");
1679         }
1680         my @new_elements = @_;
1681         my $length = $self->FETCHSIZE();
1682         my $new_size = scalar @new_elements;
1683         
1684         if ($length) {
1685                 for (my $i = $length - 1; $i >= 0; $i--) {
1686                         $self->STORE( $i + $new_size, $self->FETCH($i) );
1687                 }
1688         }
1689         
1690         for (my $i = 0; $i < $new_size; $i++) {
1691                 $self->STORE( $i, $new_elements[$i] );
1692         }
1693 }
1694
1695 sub SPLICE {
1696         ##
1697         # Splices section of array with optional new section.
1698         # Returns deleted section, or last element deleted in scalar context.
1699         ##
1700     my $self = _get_self($_[0]);shift @_;
1701         if ($self->type ne TYPE_ARRAY) {
1702                 return $self->_throw_error("SPLICE method only supported for arrays");
1703         }
1704         my $length = $self->FETCHSIZE();
1705         
1706         ##
1707         # Calculate offset and length of splice
1708         ##
1709         my $offset = shift || 0;
1710         if ($offset < 0) { $offset += $length; }
1711         
1712         my $splice_length;
1713         if (scalar @_) { $splice_length = shift; }
1714         else { $splice_length = $length - $offset; }
1715         if ($splice_length < 0) { $splice_length += ($length - $offset); }
1716         
1717         ##
1718         # Setup array with new elements, and copy out old elements for return
1719         ##
1720         my @new_elements = @_;
1721         my $new_size = scalar @new_elements;
1722         
1723         my @old_elements = ();
1724         for (my $i = $offset; $i < $offset + $splice_length; $i++) {
1725                 push @old_elements, $self->FETCH( $i );
1726         }
1727         
1728         ##
1729         # Adjust array length, and shift elements to accomodate new section.
1730         ##
1731     if ( $new_size != $splice_length ) {
1732         if ($new_size > $splice_length) {
1733             for (my $i = $length - 1; $i >= $offset + $splice_length; $i--) {
1734                 $self->STORE( $i + ($new_size - $splice_length), $self->FETCH($i) );
1735             }
1736         }
1737         else {
1738             for (my $i = $offset + $splice_length; $i < $length; $i++) {
1739                 $self->STORE( $i + ($new_size - $splice_length), $self->FETCH($i) );
1740             }
1741             for (my $i = 0; $i < $splice_length - $new_size; $i++) {
1742                 $self->DELETE( $length - 1 );
1743                 $length--;
1744             }
1745         }
1746         }
1747         
1748         ##
1749         # Insert new elements into array
1750         ##
1751         for (my $i = $offset; $i < $offset + $new_size; $i++) {
1752                 $self->STORE( $i, shift @new_elements );
1753         }
1754         
1755         ##
1756         # Return deleted section, or last element in scalar context.
1757         ##
1758         return wantarray ? @old_elements : $old_elements[-1];
1759 }
1760
1761 #XXX We don't need to define it.
1762 #XXX It will be useful, though, when we split out HASH and ARRAY
1763 #sub EXTEND {
1764         ##
1765         # Perl will call EXTEND() when the array is likely to grow.
1766         # We don't care, but include it for compatibility.
1767         ##
1768 #}
1769
1770 ##
1771 # Public method aliases
1772 ##
1773 *put = *store = *STORE;
1774 *get = *fetch = *FETCH;
1775 *delete = *DELETE;
1776 *exists = *EXISTS;
1777 *clear = *CLEAR;
1778 *first_key = *FIRSTKEY;
1779 *next_key = *NEXTKEY;
1780 *length = *FETCHSIZE;
1781 *pop = *POP;
1782 *push = *PUSH;
1783 *shift = *SHIFT;
1784 *unshift = *UNSHIFT;
1785 *splice = *SPLICE;
1786
1787 1;
1788
1789 __END__
1790
1791 =head1 NAME
1792
1793 DBM::Deep - A pure perl multi-level hash/array DBM
1794
1795 =head1 SYNOPSIS
1796
1797   use DBM::Deep;
1798   my $db = DBM::Deep->new( "foo.db" );
1799   
1800   $db->{key} = 'value'; # tie() style
1801   print $db->{key};
1802   
1803   $db->put('key', 'value'); # OO style
1804   print $db->get('key');
1805   
1806   # true multi-level support
1807   $db->{my_complex} = [
1808         'hello', { perl => 'rules' }, 
1809         42, 99 ];
1810
1811 =head1 DESCRIPTION
1812
1813 A unique flat-file database module, written in pure perl.  True 
1814 multi-level hash/array support (unlike MLDBM, which is faked), hybrid 
1815 OO / tie() interface, cross-platform FTPable files, and quite fast.  Can 
1816 handle millions of keys and unlimited hash levels without significant 
1817 slow-down.  Written from the ground-up in pure perl -- this is NOT a 
1818 wrapper around a C-based DBM.  Out-of-the-box compatibility with Unix, 
1819 Mac OS X and Windows.
1820
1821 =head1 INSTALLATION
1822
1823 Hopefully you are using CPAN's excellent Perl module, which will download
1824 and install the module for you.  If not, get the tarball, and run these 
1825 commands:
1826
1827         tar zxf DBM-Deep-*
1828         cd DBM-Deep-*
1829         perl Makefile.PL
1830         make
1831         make test
1832         make install
1833
1834 =head1 SETUP
1835
1836 Construction can be done OO-style (which is the recommended way), or using 
1837 Perl's tie() function.  Both are examined here.
1838
1839 =head2 OO CONSTRUCTION
1840
1841 The recommended way to construct a DBM::Deep object is to use the new()
1842 method, which gets you a blessed, tied hash or array reference.
1843
1844         my $db = DBM::Deep->new( "foo.db" );
1845
1846 This opens a new database handle, mapped to the file "foo.db".  If this
1847 file does not exist, it will automatically be created.  DB files are 
1848 opened in "r+" (read/write) mode, and the type of object returned is a
1849 hash, unless otherwise specified (see L<OPTIONS> below).
1850
1851
1852
1853 You can pass a number of options to the constructor to specify things like
1854 locking, autoflush, etc.  This is done by passing an inline hash:
1855
1856         my $db = DBM::Deep->new(
1857                 file => "foo.db",
1858                 locking => 1,
1859                 autoflush => 1
1860         );
1861
1862 Notice that the filename is now specified I<inside> the hash with
1863 the "file" parameter, as opposed to being the sole argument to the 
1864 constructor.  This is required if any options are specified.
1865 See L<OPTIONS> below for the complete list.
1866
1867
1868
1869 You can also start with an array instead of a hash.  For this, you must
1870 specify the C<type> parameter:
1871
1872         my $db = DBM::Deep->new(
1873                 file => "foo.db",
1874                 type => DBM::Deep->TYPE_ARRAY
1875         );
1876
1877 B<Note:> Specifing the C<type> parameter only takes effect when beginning
1878 a new DB file.  If you create a DBM::Deep object with an existing file, the
1879 C<type> will be loaded from the file header, and ignored if it is passed
1880 to the constructor.
1881
1882 =head2 TIE CONSTRUCTION
1883
1884 Alternatively, you can create a DBM::Deep handle by using Perl's built-in
1885 tie() function.  This is not ideal, because you get only a basic, tied hash 
1886 (or array) which is not blessed, so you can't call any functions on it.
1887
1888         my %hash;
1889         tie %hash, "DBM::Deep", "foo.db";
1890         
1891         my @array;
1892         tie @array, "DBM::Deep", "bar.db";
1893
1894 As with the OO constructor, you can replace the DB filename parameter with
1895 a hash containing one or more options (see L<OPTIONS> just below for the
1896 complete list).
1897
1898         tie %hash, "DBM::Deep", {
1899                 file => "foo.db",
1900                 locking => 1,
1901                 autoflush => 1
1902         };
1903
1904 =head2 OPTIONS
1905
1906 There are a number of options that can be passed in when constructing your
1907 DBM::Deep objects.  These apply to both the OO- and tie- based approaches.
1908
1909 =over
1910
1911 =item * file
1912
1913 Filename of the DB file to link the handle to.  You can pass a full absolute
1914 filesystem path, partial path, or a plain filename if the file is in the 
1915 current working directory.  This is a required parameter.
1916
1917 =item * mode
1918
1919 File open mode (read-only, read-write, etc.) string passed to Perl's FileHandle
1920 module.  This is an optional parameter, and defaults to "r+" (read/write).
1921 B<Note:> If the default (r+) mode is selected, the file will also be auto-
1922 created if it doesn't exist.
1923
1924 =item * type
1925
1926 This parameter specifies what type of object to create, a hash or array.  Use
1927 one of these two constants: C<DBM::Deep-E<gt>TYPE_HASH> or C<DBM::Deep-E<gt>TYPE_ARRAY>.
1928 This only takes effect when beginning a new file.  This is an optional 
1929 parameter, and defaults to C<DBM::Deep-E<gt>TYPE_HASH>.
1930
1931 =item * locking
1932
1933 Specifies whether locking is to be enabled.  DBM::Deep uses Perl's Fnctl flock()
1934 function to lock the database in exclusive mode for writes, and shared mode for
1935 reads.  Pass any true value to enable.  This affects the base DB handle I<and 
1936 any child hashes or arrays> that use the same DB file.  This is an optional 
1937 parameter, and defaults to 0 (disabled).  See L<LOCKING> below for more.
1938
1939 =item * autoflush
1940
1941 Specifies whether autoflush is to be enabled on the underlying FileHandle.  
1942 This obviously slows down write operations, but is required if you may have 
1943 multiple processes accessing the same DB file (also consider enable I<locking> 
1944 or at least I<volatile>).  Pass any true value to enable.  This is an optional 
1945 parameter, and defaults to 0 (disabled).
1946
1947 =item * volatile
1948
1949 If I<volatile> mode is enabled, DBM::Deep will stat() the DB file before each
1950 STORE() operation.  This is required if an outside force may change the size of
1951 the file between transactions.  Locking also implicitly enables volatile.  This
1952 is useful if you want to use a different locking system or write your own.  Pass
1953 any true value to enable.  This is an optional parameter, and defaults to 0 
1954 (disabled).
1955
1956 =item * autobless
1957
1958 If I<autobless> mode is enabled, DBM::Deep will preserve blessed hashes, and
1959 restore them when fetched.  This is an B<experimental> feature, and does have
1960 side-effects.  Basically, when hashes are re-blessed into their original
1961 classes, they are no longer blessed into the DBM::Deep class!  So you won't be
1962 able to call any DBM::Deep methods on them.  You have been warned.
1963 This is an optional parameter, and defaults to 0 (disabled).
1964
1965 =item * filter_*
1966
1967 See L<FILTERS> below.
1968
1969 =item * debug
1970
1971 Setting I<debug> mode will make all errors non-fatal, dump them out to
1972 STDERR, and continue on.  This is for debugging purposes only, and probably
1973 not what you want.  This is an optional parameter, and defaults to 0 (disabled).
1974
1975 =item * fh
1976
1977 Instead of passing a file path, you can instead pass a handle to an pre-opened
1978 filehandle.  Note: Beware of using the magick *DATA handle, as this actually 
1979 contains your entire Perl script, as well as the data following the __DATA__
1980 marker.  This will not work, because DBM::Deep uses absolute seek()s into the
1981 file.  Instead, consider reading *DATA into an IO::Scalar handle, then passing
1982 in that.
1983
1984 =back
1985
1986 =head1 TIE INTERFACE
1987
1988 With DBM::Deep you can access your databases using Perl's standard hash/array
1989 syntax.  Because all DBM::Deep objects are I<tied> to hashes or arrays, you can treat
1990 them as such.  DBM::Deep will intercept all reads/writes and direct them to the right
1991 place -- the DB file.  This has nothing to do with the L<TIE CONSTRUCTION> 
1992 section above.  This simply tells you how to use DBM::Deep using regular hashes 
1993 and arrays, rather than calling functions like C<get()> and C<put()> (although those 
1994 work too).  It is entirely up to you how to want to access your databases.
1995
1996 =head2 HASHES
1997
1998 You can treat any DBM::Deep object like a normal Perl hash reference.  Add keys,
1999 or even nested hashes (or arrays) using standard Perl syntax:
2000
2001         my $db = DBM::Deep->new( "foo.db" );
2002         
2003         $db->{mykey} = "myvalue";
2004         $db->{myhash} = {};
2005         $db->{myhash}->{subkey} = "subvalue";
2006
2007         print $db->{myhash}->{subkey} . "\n";
2008
2009 You can even step through hash keys using the normal Perl C<keys()> function:
2010
2011         foreach my $key (keys %$db) {
2012                 print "$key: " . $db->{$key} . "\n";
2013         }
2014
2015 Remember that Perl's C<keys()> function extracts I<every> key from the hash and
2016 pushes them onto an array, all before the loop even begins.  If you have an 
2017 extra large hash, this may exhaust Perl's memory.  Instead, consider using 
2018 Perl's C<each()> function, which pulls keys/values one at a time, using very 
2019 little memory:
2020
2021         while (my ($key, $value) = each %$db) {
2022                 print "$key: $value\n";
2023         }
2024
2025 Please note that when using C<each()>, you should always pass a direct
2026 hash reference, not a lookup.  Meaning, you should B<never> do this:
2027
2028         # NEVER DO THIS
2029         while (my ($key, $value) = each %{$db->{foo}}) { # BAD
2030
2031 This causes an infinite loop, because for each iteration, Perl is calling
2032 FETCH() on the $db handle, resulting in a "new" hash for foo every time, so
2033 it effectively keeps returning the first key over and over again. Instead, 
2034 assign a temporary variable to C<$db->{foo}>, then pass that to each().
2035
2036 =head2 ARRAYS
2037
2038 As with hashes, you can treat any DBM::Deep object like a normal Perl array
2039 reference.  This includes inserting, removing and manipulating elements, 
2040 and the C<push()>, C<pop()>, C<shift()>, C<unshift()> and C<splice()> functions.
2041 The object must have first been created using type C<DBM::Deep-E<gt>TYPE_ARRAY>, 
2042 or simply be a nested array reference inside a hash.  Example:
2043
2044         my $db = DBM::Deep->new(
2045                 file => "foo-array.db",
2046                 type => DBM::Deep->TYPE_ARRAY
2047         );
2048         
2049         $db->[0] = "foo";
2050         push @$db, "bar", "baz";
2051         unshift @$db, "bah";
2052         
2053         my $last_elem = pop @$db; # baz
2054         my $first_elem = shift @$db; # bah
2055         my $second_elem = $db->[1]; # bar
2056         
2057         my $num_elements = scalar @$db;
2058
2059 =head1 OO INTERFACE
2060
2061 In addition to the I<tie()> interface, you can also use a standard OO interface
2062 to manipulate all aspects of DBM::Deep databases.  Each type of object (hash or
2063 array) has its own methods, but both types share the following common methods: 
2064 C<put()>, C<get()>, C<exists()>, C<delete()> and C<clear()>.
2065
2066 =over
2067
2068 =item * put()
2069
2070 Stores a new hash key/value pair, or sets an array element value.  Takes two
2071 arguments, the hash key or array index, and the new value.  The value can be
2072 a scalar, hash ref or array ref.  Returns true on success, false on failure.
2073
2074         $db->put("foo", "bar"); # for hashes
2075         $db->put(1, "bar"); # for arrays
2076
2077 =item * get()
2078
2079 Fetches the value of a hash key or array element.  Takes one argument: the hash
2080 key or array index.  Returns a scalar, hash ref or array ref, depending on the 
2081 data type stored.
2082
2083         my $value = $db->get("foo"); # for hashes
2084         my $value = $db->get(1); # for arrays
2085
2086 =item * exists()
2087
2088 Checks if a hash key or array index exists.  Takes one argument: the hash key 
2089 or array index.  Returns true if it exists, false if not.
2090
2091         if ($db->exists("foo")) { print "yay!\n"; } # for hashes
2092         if ($db->exists(1)) { print "yay!\n"; } # for arrays
2093
2094 =item * delete()
2095
2096 Deletes one hash key/value pair or array element.  Takes one argument: the hash
2097 key or array index.  Returns true on success, false if not found.  For arrays,
2098 the remaining elements located after the deleted element are NOT moved over.
2099 The deleted element is essentially just undefined, which is exactly how Perl's
2100 internal arrays work.  Please note that the space occupied by the deleted 
2101 key/value or element is B<not> reused again -- see L<UNUSED SPACE RECOVERY> 
2102 below for details and workarounds.
2103
2104         $db->delete("foo"); # for hashes
2105         $db->delete(1); # for arrays
2106
2107 =item * clear()
2108
2109 Deletes B<all> hash keys or array elements.  Takes no arguments.  No return 
2110 value.  Please note that the space occupied by the deleted keys/values or 
2111 elements is B<not> reused again -- see L<UNUSED SPACE RECOVERY> below for 
2112 details and workarounds.
2113
2114         $db->clear(); # hashes or arrays
2115
2116 =back
2117
2118 =head2 HASHES
2119
2120 For hashes, DBM::Deep supports all the common methods described above, and the 
2121 following additional methods: C<first_key()> and C<next_key()>.
2122
2123 =over
2124
2125 =item * first_key()
2126
2127 Returns the "first" key in the hash.  As with built-in Perl hashes, keys are 
2128 fetched in an undefined order (which appears random).  Takes no arguments, 
2129 returns the key as a scalar value.
2130
2131         my $key = $db->first_key();
2132
2133 =item * next_key()
2134
2135 Returns the "next" key in the hash, given the previous one as the sole argument.
2136 Returns undef if there are no more keys to be fetched.
2137
2138         $key = $db->next_key($key);
2139
2140 =back
2141
2142 Here are some examples of using hashes:
2143
2144         my $db = DBM::Deep->new( "foo.db" );
2145         
2146         $db->put("foo", "bar");
2147         print "foo: " . $db->get("foo") . "\n";
2148         
2149         $db->put("baz", {}); # new child hash ref
2150         $db->get("baz")->put("buz", "biz");
2151         print "buz: " . $db->get("baz")->get("buz") . "\n";
2152         
2153         my $key = $db->first_key();
2154         while ($key) {
2155                 print "$key: " . $db->get($key) . "\n";
2156                 $key = $db->next_key($key);     
2157         }
2158         
2159         if ($db->exists("foo")) { $db->delete("foo"); }
2160
2161 =head2 ARRAYS
2162
2163 For arrays, DBM::Deep supports all the common methods described above, and the 
2164 following additional methods: C<length()>, C<push()>, C<pop()>, C<shift()>, 
2165 C<unshift()> and C<splice()>.
2166
2167 =over
2168
2169 =item * length()
2170
2171 Returns the number of elements in the array.  Takes no arguments.
2172
2173         my $len = $db->length();
2174
2175 =item * push()
2176
2177 Adds one or more elements onto the end of the array.  Accepts scalars, hash 
2178 refs or array refs.  No return value.
2179
2180         $db->push("foo", "bar", {});
2181
2182 =item * pop()
2183
2184 Fetches the last element in the array, and deletes it.  Takes no arguments.
2185 Returns undef if array is empty.  Returns the element value.
2186
2187         my $elem = $db->pop();
2188
2189 =item * shift()
2190
2191 Fetches the first element in the array, deletes it, then shifts all the 
2192 remaining elements over to take up the space.  Returns the element value.  This 
2193 method is not recommended with large arrays -- see L<LARGE ARRAYS> below for 
2194 details.
2195
2196         my $elem = $db->shift();
2197
2198 =item * unshift()
2199
2200 Inserts one or more elements onto the beginning of the array, shifting all 
2201 existing elements over to make room.  Accepts scalars, hash refs or array refs.  
2202 No return value.  This method is not recommended with large arrays -- see 
2203 <LARGE ARRAYS> below for details.
2204
2205         $db->unshift("foo", "bar", {});
2206
2207 =item * splice()
2208
2209 Performs exactly like Perl's built-in function of the same name.  See L<perldoc 
2210 -f splice> for usage -- it is too complicated to document here.  This method is
2211 not recommended with large arrays -- see L<LARGE ARRAYS> below for details.
2212
2213 =back
2214
2215 Here are some examples of using arrays:
2216
2217         my $db = DBM::Deep->new(
2218                 file => "foo.db",
2219                 type => DBM::Deep->TYPE_ARRAY
2220         );
2221         
2222         $db->push("bar", "baz");
2223         $db->unshift("foo");
2224         $db->put(3, "buz");
2225         
2226         my $len = $db->length();
2227         print "length: $len\n"; # 4
2228         
2229         for (my $k=0; $k<$len; $k++) {
2230                 print "$k: " . $db->get($k) . "\n";
2231         }
2232         
2233         $db->splice(1, 2, "biz", "baf");
2234         
2235         while (my $elem = shift @$db) {
2236                 print "shifted: $elem\n";
2237         }
2238
2239 =head1 LOCKING
2240
2241 Enable automatic file locking by passing a true value to the C<locking> 
2242 parameter when constructing your DBM::Deep object (see L<SETUP> above).
2243
2244         my $db = DBM::Deep->new(
2245                 file => "foo.db",
2246                 locking => 1
2247         );
2248
2249 This causes DBM::Deep to C<flock()> the underlying FileHandle object with exclusive 
2250 mode for writes, and shared mode for reads.  This is required if you have 
2251 multiple processes accessing the same database file, to avoid file corruption.  
2252 Please note that C<flock()> does NOT work for files over NFS.  See L<DB OVER 
2253 NFS> below for more.
2254
2255 =head2 EXPLICIT LOCKING
2256
2257 You can explicitly lock a database, so it remains locked for multiple 
2258 transactions.  This is done by calling the C<lock()> method, and passing an 
2259 optional lock mode argument (defaults to exclusive mode).  This is particularly 
2260 useful for things like counters, where the current value needs to be fetched, 
2261 then incremented, then stored again.
2262
2263         $db->lock();
2264         my $counter = $db->get("counter");
2265         $counter++;
2266         $db->put("counter", $counter);
2267         $db->unlock();
2268
2269         # or...
2270         
2271         $db->lock();
2272         $db->{counter}++;
2273         $db->unlock();
2274
2275 You can pass C<lock()> an optional argument, which specifies which mode to use
2276 (exclusive or shared).  Use one of these two constants: C<DBM::Deep-E<gt>LOCK_EX> 
2277 or C<DBM::Deep-E<gt>LOCK_SH>.  These are passed directly to C<flock()>, and are the 
2278 same as the constants defined in Perl's C<Fcntl> module.
2279
2280         $db->lock( DBM::Deep->LOCK_SH );
2281         # something here
2282         $db->unlock();
2283
2284 If you want to implement your own file locking scheme, be sure to create your
2285 DBM::Deep objects setting the C<volatile> option to true.  This hints to DBM::Deep
2286 that the DB file may change between transactions.  See L<LOW-LEVEL ACCESS> 
2287 below for more.
2288
2289 =head1 IMPORTING/EXPORTING
2290
2291 You can import existing complex structures by calling the C<import()> method,
2292 and export an entire database into an in-memory structure using the C<export()>
2293 method.  Both are examined here.
2294
2295 =head2 IMPORTING
2296
2297 Say you have an existing hash with nested hashes/arrays inside it.  Instead of
2298 walking the structure and adding keys/elements to the database as you go, 
2299 simply pass a reference to the C<import()> method.  This recursively adds 
2300 everything to an existing DBM::Deep object for you.  Here is an example:
2301
2302         my $struct = {
2303                 key1 => "value1",
2304                 key2 => "value2",
2305                 array1 => [ "elem0", "elem1", "elem2" ],
2306                 hash1 => {
2307                         subkey1 => "subvalue1",
2308                         subkey2 => "subvalue2"
2309                 }
2310         };
2311         
2312         my $db = DBM::Deep->new( "foo.db" );
2313         $db->import( $struct );
2314         
2315         print $db->{key1} . "\n"; # prints "value1"
2316
2317 This recursively imports the entire C<$struct> object into C<$db>, including 
2318 all nested hashes and arrays.  If the DBM::Deep object contains exsiting data,
2319 keys are merged with the existing ones, replacing if they already exist.  
2320 The C<import()> method can be called on any database level (not just the base 
2321 level), and works with both hash and array DB types.
2322
2323
2324
2325 B<Note:> Make sure your existing structure has no circular references in it.
2326 These will cause an infinite loop when importing.
2327
2328 =head2 EXPORTING
2329
2330 Calling the C<export()> method on an existing DBM::Deep object will return 
2331 a reference to a new in-memory copy of the database.  The export is done 
2332 recursively, so all nested hashes/arrays are all exported to standard Perl
2333 objects.  Here is an example:
2334
2335         my $db = DBM::Deep->new( "foo.db" );
2336         
2337         $db->{key1} = "value1";
2338         $db->{key2} = "value2";
2339         $db->{hash1} = {};
2340         $db->{hash1}->{subkey1} = "subvalue1";
2341         $db->{hash1}->{subkey2} = "subvalue2";
2342         
2343         my $struct = $db->export();
2344         
2345         print $struct->{key1} . "\n"; # prints "value1"
2346
2347 This makes a complete copy of the database in memory, and returns a reference
2348 to it.  The C<export()> method can be called on any database level (not just 
2349 the base level), and works with both hash and array DB types.  Be careful of 
2350 large databases -- you can store a lot more data in a DBM::Deep object than an 
2351 in-memory Perl structure.
2352
2353
2354
2355 B<Note:> Make sure your database has no circular references in it.
2356 These will cause an infinite loop when exporting.
2357
2358 =head1 FILTERS
2359
2360 DBM::Deep has a number of hooks where you can specify your own Perl function
2361 to perform filtering on incoming or outgoing data.  This is a perfect
2362 way to extend the engine, and implement things like real-time compression or
2363 encryption.  Filtering applies to the base DB level, and all child hashes / 
2364 arrays.  Filter hooks can be specified when your DBM::Deep object is first 
2365 constructed, or by calling the C<set_filter()> method at any time.  There are 
2366 four available filter hooks, described below:
2367
2368 =over
2369
2370 =item * filter_store_key
2371
2372 This filter is called whenever a hash key is stored.  It 
2373 is passed the incoming key, and expected to return a transformed key.
2374
2375 =item * filter_store_value
2376
2377 This filter is called whenever a hash key or array element is stored.  It 
2378 is passed the incoming value, and expected to return a transformed value.
2379
2380 =item * filter_fetch_key
2381
2382 This filter is called whenever a hash key is fetched (i.e. via 
2383 C<first_key()> or C<next_key()>).  It is passed the transformed key,
2384 and expected to return the plain key.
2385
2386 =item * filter_fetch_value
2387
2388 This filter is called whenever a hash key or array element is fetched.  
2389 It is passed the transformed value, and expected to return the plain value.
2390
2391 =back
2392
2393 Here are the two ways to setup a filter hook:
2394
2395         my $db = DBM::Deep->new(
2396                 file => "foo.db",
2397                 filter_store_value => \&my_filter_store,
2398                 filter_fetch_value => \&my_filter_fetch
2399         );
2400         
2401         # or...
2402         
2403         $db->set_filter( "filter_store_value", \&my_filter_store );
2404         $db->set_filter( "filter_fetch_value", \&my_filter_fetch );
2405
2406 Your filter function will be called only when dealing with SCALAR keys or
2407 values.  When nested hashes and arrays are being stored/fetched, filtering
2408 is bypassed.  Filters are called as static functions, passed a single SCALAR 
2409 argument, and expected to return a single SCALAR value.  If you want to
2410 remove a filter, set the function reference to C<undef>:
2411
2412         $db->set_filter( "filter_store_value", undef );
2413
2414 =head2 REAL-TIME ENCRYPTION EXAMPLE
2415
2416 Here is a working example that uses the I<Crypt::Blowfish> module to 
2417 do real-time encryption / decryption of keys & values with DBM::Deep Filters.
2418 Please visit L<http://search.cpan.org/search?module=Crypt::Blowfish> for more 
2419 on I<Crypt::Blowfish>.  You'll also need the I<Crypt::CBC> module.
2420
2421         use DBM::Deep;
2422         use Crypt::Blowfish;
2423         use Crypt::CBC;
2424         
2425         my $cipher = Crypt::CBC->new({
2426                 'key'             => 'my secret key',
2427                 'cipher'          => 'Blowfish',
2428                 'iv'              => '$KJh#(}q',
2429                 'regenerate_key'  => 0,
2430                 'padding'         => 'space',
2431                 'prepend_iv'      => 0
2432         });
2433         
2434         my $db = DBM::Deep->new(
2435                 file => "foo-encrypt.db",
2436                 filter_store_key => \&my_encrypt,
2437                 filter_store_value => \&my_encrypt,
2438                 filter_fetch_key => \&my_decrypt,
2439                 filter_fetch_value => \&my_decrypt,
2440         );
2441         
2442         $db->{key1} = "value1";
2443         $db->{key2} = "value2";
2444         print "key1: " . $db->{key1} . "\n";
2445         print "key2: " . $db->{key2} . "\n";
2446         
2447         undef $db;
2448         exit;
2449         
2450         sub my_encrypt {
2451                 return $cipher->encrypt( $_[0] );
2452         }
2453         sub my_decrypt {
2454                 return $cipher->decrypt( $_[0] );
2455         }
2456
2457 =head2 REAL-TIME COMPRESSION EXAMPLE
2458
2459 Here is a working example that uses the I<Compress::Zlib> module to do real-time
2460 compression / decompression of keys & values with DBM::Deep Filters.
2461 Please visit L<http://search.cpan.org/search?module=Compress::Zlib> for 
2462 more on I<Compress::Zlib>.
2463
2464         use DBM::Deep;
2465         use Compress::Zlib;
2466         
2467         my $db = DBM::Deep->new(
2468                 file => "foo-compress.db",
2469                 filter_store_key => \&my_compress,
2470                 filter_store_value => \&my_compress,
2471                 filter_fetch_key => \&my_decompress,
2472                 filter_fetch_value => \&my_decompress,
2473         );
2474         
2475         $db->{key1} = "value1";
2476         $db->{key2} = "value2";
2477         print "key1: " . $db->{key1} . "\n";
2478         print "key2: " . $db->{key2} . "\n";
2479         
2480         undef $db;
2481         exit;
2482         
2483         sub my_compress {
2484                 return Compress::Zlib::memGzip( $_[0] ) ;
2485         }
2486         sub my_decompress {
2487                 return Compress::Zlib::memGunzip( $_[0] ) ;
2488         }
2489
2490 B<Note:> Filtering of keys only applies to hashes.  Array "keys" are
2491 actually numerical index numbers, and are not filtered.
2492
2493 =head1 ERROR HANDLING
2494
2495 Most DBM::Deep methods return a true value for success, and call die() on
2496 failure.  You can wrap calls in an eval block to catch the die.  Also, the 
2497 actual error message is stored in an internal scalar, which can be fetched by 
2498 calling the C<error()> method.
2499
2500         my $db = DBM::Deep->new( "foo.db" ); # create hash
2501         eval { $db->push("foo"); }; # ILLEGAL -- push is array-only call
2502         
2503         print $db->error(); # prints error message
2504
2505 You can then call C<clear_error()> to clear the current error state.
2506
2507         $db->clear_error();
2508
2509 If you set the C<debug> option to true when creating your DBM::Deep object,
2510 all errors are considered NON-FATAL, and dumped to STDERR.  This is only
2511 for debugging purposes.
2512
2513 =head1 LARGEFILE SUPPORT
2514
2515 If you have a 64-bit system, and your Perl is compiled with both LARGEFILE
2516 and 64-bit support, you I<may> be able to create databases larger than 2 GB.
2517 DBM::Deep by default uses 32-bit file offset tags, but these can be changed
2518 by calling the static C<set_pack()> method before you do anything else.
2519
2520         DBM::Deep::set_pack(8, 'Q');
2521
2522 This tells DBM::Deep to pack all file offsets with 8-byte (64-bit) quad words 
2523 instead of 32-bit longs.  After setting these values your DB files have a 
2524 theoretical maximum size of 16 XB (exabytes).
2525
2526
2527
2528 B<Note:> Changing these values will B<NOT> work for existing database files.
2529 Only change this for new files, and make sure it stays set consistently 
2530 throughout the file's life.  If you do set these values, you can no longer 
2531 access 32-bit DB files.  You can, however, call C<set_pack(4, 'N')> to change 
2532 back to 32-bit mode.
2533
2534
2535
2536 B<Note:> I have not personally tested files > 2 GB -- all my systems have 
2537 only a 32-bit Perl.  However, I have received user reports that this does 
2538 indeed work!
2539
2540 =head1 LOW-LEVEL ACCESS
2541
2542 If you require low-level access to the underlying FileHandle that DBM::Deep uses,
2543 you can call the C<fh()> method, which returns the handle:
2544
2545         my $fh = $db->fh();
2546
2547 This method can be called on the root level of the datbase, or any child
2548 hashes or arrays.  All levels share a I<root> structure, which contains things
2549 like the FileHandle, a reference counter, and all your options you specified
2550 when you created the object.  You can get access to this root structure by 
2551 calling the C<root()> method.
2552
2553         my $root = $db->root();
2554
2555 This is useful for changing options after the object has already been created,
2556 such as enabling/disabling locking, volatile or debug modes.  You can also
2557 store your own temporary user data in this structure (be wary of name 
2558 collision), which is then accessible from any child hash or array.
2559
2560 =head1 CUSTOM DIGEST ALGORITHM
2561
2562 DBM::Deep by default uses the I<Message Digest 5> (MD5) algorithm for hashing
2563 keys.  However you can override this, and use another algorithm (such as SHA-256)
2564 or even write your own.  But please note that DBM::Deep currently expects zero 
2565 collisions, so your algorithm has to be I<perfect>, so to speak.
2566 Collision detection may be introduced in a later version.
2567
2568
2569
2570 You can specify a custom digest algorithm by calling the static C<set_digest()> 
2571 function, passing a reference to a subroutine, and the length of the algorithm's 
2572 hashes (in bytes).  This is a global static function, which affects ALL DBM::Deep 
2573 objects.  Here is a working example that uses a 256-bit hash from the 
2574 I<Digest::SHA256> module.  Please see 
2575 L<http://search.cpan.org/search?module=Digest::SHA256> for more.
2576
2577         use DBM::Deep;
2578         use Digest::SHA256;
2579         
2580         my $context = Digest::SHA256::new(256);
2581         
2582         DBM::Deep::set_digest( \&my_digest, 32 );
2583         
2584         my $db = DBM::Deep->new( "foo-sha.db" );
2585         
2586         $db->{key1} = "value1";
2587         $db->{key2} = "value2";
2588         print "key1: " . $db->{key1} . "\n";
2589         print "key2: " . $db->{key2} . "\n";
2590         
2591         undef $db;
2592         exit;
2593         
2594         sub my_digest {
2595                 return substr( $context->hash($_[0]), 0, 32 );
2596         }
2597
2598 B<Note:> Your returned digest strings must be B<EXACTLY> the number
2599 of bytes you specify in the C<set_digest()> function (in this case 32).
2600
2601 =head1 CIRCULAR REFERENCES
2602
2603 DBM::Deep has B<experimental> support for circular references.  Meaning you
2604 can have a nested hash key or array element that points to a parent object.
2605 This relationship is stored in the DB file, and is preserved between sessions.
2606 Here is an example:
2607
2608         my $db = DBM::Deep->new( "foo.db" );
2609         
2610         $db->{foo} = "bar";
2611         $db->{circle} = $db; # ref to self
2612         
2613         print $db->{foo} . "\n"; # prints "foo"
2614         print $db->{circle}->{foo} . "\n"; # prints "foo" again
2615
2616 One catch is, passing the object to a function that recursively walks the
2617 object tree (such as I<Data::Dumper> or even the built-in C<optimize()> or
2618 C<export()> methods) will result in an infinite loop.  The other catch is, 
2619 if you fetch the I<key> of a circular reference (i.e. using the C<first_key()> 
2620 or C<next_key()> methods), you will get the I<target object's key>, not the 
2621 ref's key.  This gets even more interesting with the above example, where 
2622 the I<circle> key points to the base DB object, which technically doesn't 
2623 have a key.  So I made DBM::Deep return "[base]" as the key name in that 
2624 special case.
2625
2626 =head1 CAVEATS / ISSUES / BUGS
2627
2628 This section describes all the known issues with DBM::Deep.  It you have found
2629 something that is not listed here, please send e-mail to L<jhuckaby@cpan.org>.
2630
2631 =head2 UNUSED SPACE RECOVERY
2632
2633 One major caveat with DBM::Deep is that space occupied by existing keys and
2634 values is not recovered when they are deleted.  Meaning if you keep deleting
2635 and adding new keys, your file will continuously grow.  I am working on this,
2636 but in the meantime you can call the built-in C<optimize()> method from time to 
2637 time (perhaps in a crontab or something) to recover all your unused space.
2638
2639         $db->optimize(); # returns true on success
2640
2641 This rebuilds the ENTIRE database into a new file, then moves it on top of
2642 the original.  The new file will have no unused space, thus it will take up as
2643 little disk space as possible.  Please note that this operation can take 
2644 a long time for large files, and you need enough disk space to temporarily hold 
2645 2 copies of your DB file.  The temporary file is created in the same directory 
2646 as the original, named with a ".tmp" extension, and is deleted when the 
2647 operation completes.  Oh, and if locking is enabled, the DB is automatically 
2648 locked for the entire duration of the copy.
2649
2650
2651
2652 B<WARNING:> Only call optimize() on the top-level node of the database, and 
2653 make sure there are no child references lying around.  DBM::Deep keeps a reference 
2654 counter, and if it is greater than 1, optimize() will abort and return undef.
2655
2656 =head2 AUTOVIVIFICATION
2657
2658 Unfortunately, autovivification doesn't work with tied hashes.  This appears to 
2659 be a bug in Perl's tie() system, as I<Jakob Schmidt> encountered the very same 
2660 issue with his I<DWH_FIle> module (see L<http://search.cpan.org/search?module=DWH_File>),
2661 and it is also mentioned in the BUGS section for the I<MLDBM> module <see 
2662 L<http://search.cpan.org/search?module=MLDBM>).  Basically, on a new db file,
2663 this does not work:
2664
2665         $db->{foo}->{bar} = "hello";
2666
2667 Since "foo" doesn't exist, you cannot add "bar" to it.  You end up with "foo"
2668 being an empty hash.  Try this instead, which works fine:
2669
2670         $db->{foo} = { bar => "hello" };
2671
2672 As of Perl 5.8.7, this bug still exists.  I have walked very carefully through
2673 the execution path, and Perl indeed passes an empty hash to the STORE() method.
2674 Probably a bug in Perl.
2675
2676 =head2 FILE CORRUPTION
2677
2678 The current level of error handling in DBM::Deep is minimal.  Files I<are> checked
2679 for a 32-bit signature when opened, but other corruption in files can cause
2680 segmentation faults.  DBM::Deep may try to seek() past the end of a file, or get
2681 stuck in an infinite loop depending on the level of corruption.  File write
2682 operations are not checked for failure (for speed), so if you happen to run
2683 out of disk space, DBM::Deep will probably fail in a bad way.  These things will 
2684 be addressed in a later version of DBM::Deep.
2685
2686 =head2 DB OVER NFS
2687
2688 Beware of using DB files over NFS.  DBM::Deep uses flock(), which works well on local
2689 filesystems, but will NOT protect you from file corruption over NFS.  I've heard 
2690 about setting up your NFS server with a locking daemon, then using lockf() to 
2691 lock your files, but your milage may vary there as well.  From what I 
2692 understand, there is no real way to do it.  However, if you need access to the 
2693 underlying FileHandle in DBM::Deep for using some other kind of locking scheme like 
2694 lockf(), see the L<LOW-LEVEL ACCESS> section above.
2695
2696 =head2 COPYING OBJECTS
2697
2698 Beware of copying tied objects in Perl.  Very strange things can happen.  
2699 Instead, use DBM::Deep's C<clone()> method which safely copies the object and 
2700 returns a new, blessed, tied hash or array to the same level in the DB.
2701
2702         my $copy = $db->clone();
2703
2704 =head2 LARGE ARRAYS
2705
2706 Beware of using C<shift()>, C<unshift()> or C<splice()> with large arrays.
2707 These functions cause every element in the array to move, which can be murder
2708 on DBM::Deep, as every element has to be fetched from disk, then stored again in
2709 a different location.  This may be addressed in a later version.
2710
2711 =head1 PERFORMANCE
2712
2713 This section discusses DBM::Deep's speed and memory usage.
2714
2715 =head2 SPEED
2716
2717 Obviously, DBM::Deep isn't going to be as fast as some C-based DBMs, such as 
2718 the almighty I<BerkeleyDB>.  But it makes up for it in features like true
2719 multi-level hash/array support, and cross-platform FTPable files.  Even so,
2720 DBM::Deep is still pretty fast, and the speed stays fairly consistent, even
2721 with huge databases.  Here is some test data:
2722         
2723         Adding 1,000,000 keys to new DB file...
2724         
2725         At 100 keys, avg. speed is 2,703 keys/sec
2726         At 200 keys, avg. speed is 2,642 keys/sec
2727         At 300 keys, avg. speed is 2,598 keys/sec
2728         At 400 keys, avg. speed is 2,578 keys/sec
2729         At 500 keys, avg. speed is 2,722 keys/sec
2730         At 600 keys, avg. speed is 2,628 keys/sec
2731         At 700 keys, avg. speed is 2,700 keys/sec
2732         At 800 keys, avg. speed is 2,607 keys/sec
2733         At 900 keys, avg. speed is 2,190 keys/sec
2734         At 1,000 keys, avg. speed is 2,570 keys/sec
2735         At 2,000 keys, avg. speed is 2,417 keys/sec
2736         At 3,000 keys, avg. speed is 1,982 keys/sec
2737         At 4,000 keys, avg. speed is 1,568 keys/sec
2738         At 5,000 keys, avg. speed is 1,533 keys/sec
2739         At 6,000 keys, avg. speed is 1,787 keys/sec
2740         At 7,000 keys, avg. speed is 1,977 keys/sec
2741         At 8,000 keys, avg. speed is 2,028 keys/sec
2742         At 9,000 keys, avg. speed is 2,077 keys/sec
2743         At 10,000 keys, avg. speed is 2,031 keys/sec
2744         At 20,000 keys, avg. speed is 1,970 keys/sec
2745         At 30,000 keys, avg. speed is 2,050 keys/sec
2746         At 40,000 keys, avg. speed is 2,073 keys/sec
2747         At 50,000 keys, avg. speed is 1,973 keys/sec
2748         At 60,000 keys, avg. speed is 1,914 keys/sec
2749         At 70,000 keys, avg. speed is 2,091 keys/sec
2750         At 80,000 keys, avg. speed is 2,103 keys/sec
2751         At 90,000 keys, avg. speed is 1,886 keys/sec
2752         At 100,000 keys, avg. speed is 1,970 keys/sec
2753         At 200,000 keys, avg. speed is 2,053 keys/sec
2754         At 300,000 keys, avg. speed is 1,697 keys/sec
2755         At 400,000 keys, avg. speed is 1,838 keys/sec
2756         At 500,000 keys, avg. speed is 1,941 keys/sec
2757         At 600,000 keys, avg. speed is 1,930 keys/sec
2758         At 700,000 keys, avg. speed is 1,735 keys/sec
2759         At 800,000 keys, avg. speed is 1,795 keys/sec
2760         At 900,000 keys, avg. speed is 1,221 keys/sec
2761         At 1,000,000 keys, avg. speed is 1,077 keys/sec
2762
2763 This test was performed on a PowerMac G4 1gHz running Mac OS X 10.3.2 & Perl 
2764 5.8.1, with an 80GB Ultra ATA/100 HD spinning at 7200RPM.  The hash keys and 
2765 values were between 6 - 12 chars in length.  The DB file ended up at 210MB.  
2766 Run time was 12 min 3 sec.
2767
2768 =head2 MEMORY USAGE
2769
2770 One of the great things about DBM::Deep is that it uses very little memory.
2771 Even with huge databases (1,000,000+ keys) you will not see much increased
2772 memory on your process.  DBM::Deep relies solely on the filesystem for storing
2773 and fetching data.  Here is output from I</usr/bin/top> before even opening a
2774 database handle:
2775
2776           PID USER     PRI  NI  SIZE  RSS SHARE STAT %CPU %MEM   TIME COMMAND
2777         22831 root      11   0  2716 2716  1296 R     0.0  0.2   0:07 perl
2778
2779 Basically the process is taking 2,716K of memory.  And here is the same 
2780 process after storing and fetching 1,000,000 keys:
2781
2782           PID USER     PRI  NI  SIZE  RSS SHARE STAT %CPU %MEM   TIME COMMAND
2783         22831 root      14   0  2772 2772  1328 R     0.0  0.2  13:32 perl
2784
2785 Notice the memory usage increased by only 56K.  Test was performed on a 700mHz 
2786 x86 box running Linux RedHat 7.2 & Perl 5.6.1.
2787
2788 =head1 DB FILE FORMAT
2789
2790 In case you were interested in the underlying DB file format, it is documented
2791 here in this section.  You don't need to know this to use the module, it's just 
2792 included for reference.
2793
2794 =head2 SIGNATURE
2795
2796 DBM::Deep files always start with a 32-bit signature to identify the file type.
2797 This is at offset 0.  The signature is "DPDB" in network byte order.  This is
2798 checked when the file is opened.
2799
2800 =head2 TAG
2801
2802 The DBM::Deep file is in a I<tagged format>, meaning each section of the file
2803 has a standard header containing the type of data, the length of data, and then 
2804 the data itself.  The type is a single character (1 byte), the length is a 
2805 32-bit unsigned long in network byte order, and the data is, well, the data.
2806 Here is how it unfolds:
2807
2808 =head2 MASTER INDEX
2809
2810 Immediately after the 32-bit file signature is the I<Master Index> record.  
2811 This is a standard tag header followed by 1024 bytes (in 32-bit mode) or 2048 
2812 bytes (in 64-bit mode) of data.  The type is I<H> for hash or I<A> for array, 
2813 depending on how the DBM::Deep object was constructed.
2814
2815
2816
2817 The index works by looking at a I<MD5 Hash> of the hash key (or array index 
2818 number).  The first 8-bit char of the MD5 signature is the offset into the 
2819 index, multipled by 4 in 32-bit mode, or 8 in 64-bit mode.  The value of the 
2820 index element is a file offset of the next tag for the key/element in question,
2821 which is usually a I<Bucket List> tag (see below).
2822
2823
2824
2825 The next tag I<could> be another index, depending on how many keys/elements
2826 exist.  See L<RE-INDEXING> below for details.
2827
2828 =head2 BUCKET LIST
2829
2830 A I<Bucket List> is a collection of 16 MD5 hashes for keys/elements, plus 
2831 file offsets to where the actual data is stored.  It starts with a standard 
2832 tag header, with type I<B>, and a data size of 320 bytes in 32-bit mode, or 
2833 384 bytes in 64-bit mode.  Each MD5 hash is stored in full (16 bytes), plus
2834 the 32-bit or 64-bit file offset for the I<Bucket> containing the actual data.
2835 When the list fills up, a I<Re-Index> operation is performed (See 
2836 L<RE-INDEXING> below).
2837
2838 =head2 BUCKET
2839
2840 A I<Bucket> is a tag containing a key/value pair (in hash mode), or a
2841 index/value pair (in array mode).  It starts with a standard tag header with
2842 type I<D> for scalar data (string, binary, etc.), or it could be a nested
2843 hash (type I<H>) or array (type I<A>).  The value comes just after the tag
2844 header.  The size reported in the tag header is only for the value, but then,
2845 just after the value is another size (32-bit unsigned long) and then the plain 
2846 key itself.  Since the value is likely to be fetched more often than the plain 
2847 key, I figured it would be I<slightly> faster to store the value first.
2848
2849
2850
2851 If the type is I<H> (hash) or I<A> (array), the value is another I<Master Index>
2852 record for the nested structure, where the process begins all over again.
2853
2854 =head2 RE-INDEXING
2855
2856 After a I<Bucket List> grows to 16 records, its allocated space in the file is
2857 exhausted.  Then, when another key/element comes in, the list is converted to a 
2858 new index record.  However, this index will look at the next char in the MD5 
2859 hash, and arrange new Bucket List pointers accordingly.  This process is called 
2860 I<Re-Indexing>.  Basically, a new index tag is created at the file EOF, and all 
2861 17 (16 + new one) keys/elements are removed from the old Bucket List and 
2862 inserted into the new index.  Several new Bucket Lists are created in the 
2863 process, as a new MD5 char from the key is being examined (it is unlikely that 
2864 the keys will all share the same next char of their MD5s).
2865
2866
2867
2868 Because of the way the I<MD5> algorithm works, it is impossible to tell exactly
2869 when the Bucket Lists will turn into indexes, but the first round tends to 
2870 happen right around 4,000 keys.  You will see a I<slight> decrease in 
2871 performance here, but it picks back up pretty quick (see L<SPEED> above).  Then 
2872 it takes B<a lot> more keys to exhaust the next level of Bucket Lists.  It's 
2873 right around 900,000 keys.  This process can continue nearly indefinitely -- 
2874 right up until the point the I<MD5> signatures start colliding with each other, 
2875 and this is B<EXTREMELY> rare -- like winning the lottery 5 times in a row AND 
2876 getting struck by lightning while you are walking to cash in your tickets.  
2877 Theoretically, since I<MD5> hashes are 128-bit values, you I<could> have up to 
2878 340,282,366,921,000,000,000,000,000,000,000,000,000 keys/elements (I believe 
2879 this is 340 unodecillion, but don't quote me).
2880
2881 =head2 STORING
2882
2883 When a new key/element is stored, the key (or index number) is first ran through 
2884 I<Digest::MD5> to get a 128-bit signature (example, in hex: 
2885 b05783b0773d894396d475ced9d2f4f6).  Then, the I<Master Index> record is checked
2886 for the first char of the signature (in this case I<b>).  If it does not exist,
2887 a new I<Bucket List> is created for our key (and the next 15 future keys that 
2888 happen to also have I<b> as their first MD5 char).  The entire MD5 is written 
2889 to the I<Bucket List> along with the offset of the new I<Bucket> record (EOF at
2890 this point, unless we are replacing an existing I<Bucket>), where the actual 
2891 data will be stored.
2892
2893 =head2 FETCHING
2894
2895 Fetching an existing key/element involves getting a I<Digest::MD5> of the key 
2896 (or index number), then walking along the indexes.  If there are enough 
2897 keys/elements in this DB level, there might be nested indexes, each linked to 
2898 a particular char of the MD5.  Finally, a I<Bucket List> is pointed to, which 
2899 contains up to 16 full MD5 hashes.  Each is checked for equality to the key in 
2900 question.  If we found a match, the I<Bucket> tag is loaded, where the value and 
2901 plain key are stored.
2902
2903
2904
2905 Fetching the plain key occurs when calling the I<first_key()> and I<next_key()>
2906 methods.  In this process the indexes are walked systematically, and each key
2907 fetched in increasing MD5 order (which is why it appears random).   Once the
2908 I<Bucket> is found, the value is skipped the plain key returned instead.  
2909 B<Note:> Do not count on keys being fetched as if the MD5 hashes were 
2910 alphabetically sorted.  This only happens on an index-level -- as soon as the 
2911 I<Bucket Lists> are hit, the keys will come out in the order they went in -- 
2912 so it's pretty much undefined how the keys will come out -- just like Perl's 
2913 built-in hashes.
2914
2915 =head1 CODE COVERAGE
2916
2917 I use B<Devel::Cover> to test the code coverage of my tests, below is the B<Devel::Cover> report on this 
2918 module's test suite.
2919
2920   ---------------------------- ------ ------ ------ ------ ------ ------ ------
2921   File                           stmt   bran   cond    sub    pod   time  total
2922   ---------------------------- ------ ------ ------ ------ ------ ------ ------
2923   blib/lib/DBM/Deep.pm           94.9   84.5   77.8  100.0   11.1  100.0   89.7
2924   Total                          94.9   84.5   77.8  100.0   11.1  100.0   89.7
2925   ---------------------------- ------ ------ ------ ------ ------ ------ ------
2926
2927 =head1 AUTHOR
2928
2929 Joseph Huckaby, L<jhuckaby@cpan.org>
2930
2931 Special thanks to Adam Sah and Rich Gaushell!  You know why :-)
2932
2933 =head1 SEE ALSO
2934
2935 perltie(1), Tie::Hash(3), Digest::MD5(3), Fcntl(3), flock(2), lockf(3), nfs(5),
2936 Digest::SHA256(3), Crypt::Blowfish(3), Compress::Zlib(3)
2937
2938 =head1 LICENSE
2939
2940 Copyright (c) 2002-2005 Joseph Huckaby.  All Rights Reserved.
2941 This is free software, you may use it and distribute it under the
2942 same terms as Perl itself.
2943
2944 =cut