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