Compare the wincred helper against its original in compat.
[msysgit.git] / lib / perl5 / 5.8.8 / DBM_Filter.pm
blob7385ddd3a3acb1c5913f39e8fa6e729174eb1d07
1 package DBM_Filter ;
3 use strict;
4 use warnings;
5 our $VERSION = '0.01';
7 package Tie::Hash ;
9 use strict;
10 use warnings;
12 use Carp;
15 our %LayerStack = ();
16 our %origDESTROY = ();
18 our %Filters = map { $_, undef } qw(
19 Fetch_Key
20 Fetch_Value
21 Store_Key
22 Store_Value
25 our %Options = map { $_, 1 } qw(
26 fetch
27 store
30 #sub Filter_Enable
34 #sub Filter_Disable
38 sub Filtered
40 my $this = shift;
41 return defined $LayerStack{$this} ;
44 sub Filter_Pop
46 my $this = shift;
47 my $stack = $LayerStack{$this} || return undef ;
48 my $filter = pop @{ $stack };
50 # remove the filter hooks if this is the last filter to pop
51 if ( @{ $stack } == 0 ) {
52 $this->filter_store_key ( undef );
53 $this->filter_store_value( undef );
54 $this->filter_fetch_key ( undef );
55 $this->filter_fetch_value( undef );
56 delete $LayerStack{$this};
59 return $filter;
62 sub Filter_Key_Push
64 &_do_Filter_Push;
67 sub Filter_Value_Push
69 &_do_Filter_Push;
73 sub Filter_Push
75 &_do_Filter_Push;
78 sub _do_Filter_Push
80 my $this = shift;
81 my %callbacks = ();
82 my $caller = (caller(1))[3];
83 $caller =~ s/^.*:://;
85 croak "$caller: no parameters present" unless @_ ;
87 if ( ! $Options{lc $_[0]} ) {
88 my $class = shift;
89 my @params = @_;
91 # if $class already contains "::", don't prefix "DBM_Filter::"
92 $class = "DBM_Filter::$class" unless $class =~ /::/;
94 # does the "DBM_Filter::$class" exist?
95 if ( ! defined %{ "${class}::"} ) {
96 # Nope, so try to load it.
97 eval " require $class ; " ;
98 croak "$caller: Cannot Load DBM Filter '$class': $@" if $@;
101 no strict 'refs';
102 my $fetch = *{ "${class}::Fetch" }{CODE};
103 my $store = *{ "${class}::Store" }{CODE};
104 my $filter = *{ "${class}::Filter" }{CODE};
105 use strict 'refs';
107 my $count = defined($filter) + defined($store) + defined($fetch) ;
109 if ( $count == 0 )
110 { croak "$caller: No methods (Filter, Fetch or Store) found in class '$class'" }
111 elsif ( $count == 1 && ! defined $filter) {
112 my $need = defined($fetch) ? 'Store' : 'Fetch';
113 croak "$caller: Missing method '$need' in class '$class'" ;
115 elsif ( $count >= 2 && defined $filter)
116 { croak "$caller: Can't mix Filter with Store and Fetch in class '$class'" }
118 if (defined $filter) {
119 my $callbacks = &{ $filter }(@params);
120 croak "$caller: '${class}::Filter' did not return a hash reference"
121 unless ref $callbacks && ref $callbacks eq 'HASH';
122 %callbacks = %{ $callbacks } ;
124 else {
125 $callbacks{Fetch} = $fetch;
126 $callbacks{Store} = $store;
129 else {
130 croak "$caller: not even params" unless @_ % 2 == 0;
131 %callbacks = @_;
134 my %filters = %Filters ;
135 my @got = ();
136 while (my ($k, $v) = each %callbacks )
138 my $key = $k;
139 $k = lc $k;
140 if ($k eq 'fetch') {
141 push @got, 'Fetch';
142 if ($caller eq 'Filter_Push')
143 { $filters{Fetch_Key} = $filters{Fetch_Value} = $v }
144 elsif ($caller eq 'Filter_Key_Push')
145 { $filters{Fetch_Key} = $v }
146 elsif ($caller eq 'Filter_Value_Push')
147 { $filters{Fetch_Value} = $v }
149 elsif ($k eq 'store') {
150 push @got, 'Store';
151 if ($caller eq 'Filter_Push')
152 { $filters{Store_Key} = $filters{Store_Value} = $v }
153 elsif ($caller eq 'Filter_Key_Push')
154 { $filters{Store_Key} = $v }
155 elsif ($caller eq 'Filter_Value_Push')
156 { $filters{Store_Value} = $v }
158 else
159 { croak "$caller: Unknown key '$key'" }
161 croak "$caller: value associated with key '$key' is not a code reference"
162 unless ref $v && ref $v eq 'CODE';
165 if ( @got != 2 ) {
166 push @got, 'neither' if @got == 0 ;
167 croak "$caller: expected both Store & Fetch - got @got";
170 # remember the class
171 push @{ $LayerStack{$this} }, \%filters ;
173 my $str_this = "$this" ; # Avoid a closure with $this in the subs below
175 $this->filter_store_key ( sub { store_hook($str_this, 'Store_Key') });
176 $this->filter_store_value( sub { store_hook($str_this, 'Store_Value') });
177 $this->filter_fetch_key ( sub { fetch_hook($str_this, 'Fetch_Key') });
178 $this->filter_fetch_value( sub { fetch_hook($str_this, 'Fetch_Value') });
180 # Hijack the callers DESTROY method
181 $this =~ /^(.*)=/;
182 my $type = $1 ;
183 no strict 'refs';
184 if ( *{ "${type}::DESTROY" }{CODE} ne \&MyDESTROY )
186 $origDESTROY{$type} = *{ "${type}::DESTROY" }{CODE};
187 no warnings 'redefine';
188 *{ "${type}::DESTROY" } = \&MyDESTROY ;
192 sub store_hook
194 my $this = shift ;
195 my $type = shift ;
196 foreach my $layer (@{ $LayerStack{$this} })
198 &{ $layer->{$type} }() if defined $layer->{$type} ;
202 sub fetch_hook
204 my $this = shift ;
205 my $type = shift ;
206 foreach my $layer (reverse @{ $LayerStack{$this} })
208 &{ $layer->{$type} }() if defined $layer->{$type} ;
212 sub MyDESTROY
214 my $this = shift ;
215 delete $LayerStack{$this} ;
217 # call real DESTROY
218 $this =~ /^(.*)=/;
219 &{ $origDESTROY{$1} }($this);
224 __END__
226 =head1 NAME
228 DBM_Filter -- Filter DBM keys/values
230 =head1 SYNOPSIS
232 use DBM_Filter ;
233 use SDBM_File; # or DB_File, or GDBM_File, or NDBM_File, or ODBM_File
235 $db = tie %hash, ...
237 $db->Filter_Push(Fetch => sub {...},
238 Store => sub {...});
240 $db->Filter_Push('my_filter1');
241 $db->Filter_Push('my_filter2', params...);
243 $db->Filter_Key_Push(...) ;
244 $db->Filter_Value_Push(...) ;
246 $db->Filter_Pop();
247 $db->Filtered();
249 package DBM_Filter::my_filter1;
251 sub Store { ... }
252 sub Fetch { ... }
256 package DBM_Filter::my_filter2;
258 sub Filter
260 my @opts = @_;
262 return (
263 sub Store { ... },
264 sub Fetch { ... } );
269 =head1 DESCRIPTION
271 This module provides an interface that allows filters to be applied
272 to tied Hashes associated with DBM files. It builds on the DBM Filter
273 hooks that are present in all the *DB*_File modules included with the
274 standard Perl source distribution from version 5.6.1 onwards. In addition
275 to the *DB*_File modules distributed with Perl, the BerkeleyDB module,
276 available on CPAN, supports the DBM Filter hooks. See L<perldbmfilter>
277 for more details on the DBM Filter hooks.
279 =head1 What is a DBM Filter?
281 A DBM Filter allows the keys and/or values in a tied hash to be modified
282 by some user-defined code just before it is written to the DBM file and
283 just after it is read back from the DBM file. For example, this snippet
284 of code
286 $some_hash{"abc"} = 42;
288 could potentially trigger two filters, one for the writing of the key
289 "abc" and another for writing the value 42. Similarly, this snippet
291 my ($key, $value) = each %some_hash
293 will trigger two filters, one for the reading of the key and one for
294 the reading of the value.
296 Like the existing DBM Filter functionality, this module arranges for the
297 C<$_> variable to be populated with the key or value that a filter will
298 check. This usually means that most DBM filters tend to be very short.
300 =head2 So what's new?
302 The main enhancements over the standard DBM Filter hooks are:
304 =over 4
306 =item *
308 A cleaner interface.
310 =item *
312 The ability to easily apply multiple filters to a single DBM file.
314 =item *
316 The ability to create "canned" filters. These allow commonly used filters
317 to be packaged into a stand-alone module.
319 =back
321 =head1 METHODS
323 This module will arrange for the following methods to be available via
324 the object returned from the C<tie> call.
326 =head2 $db->Filter_Push()
328 =head2 $db->Filter_Key_Push()
330 =head2 $db->Filter_Value_Push()
332 Add a filter to filter stack for the database, C<$db>. The three formats
333 vary only in whether they apply to the DBM key, the DBM value or both.
335 =over 5
337 =item Filter_Push
339 The filter is applied to I<both> keys and values.
341 =item Filter_Key_Push
343 The filter is applied to the key I<only>.
345 =item Filter_Value_Push
347 The filter is applied to the value I<only>.
349 =back
352 =head2 $db->Filter_Pop()
354 Removes the last filter that was applied to the DBM file associated with
355 C<$db>, if present.
357 =head2 $db->Filtered()
359 Returns TRUE if there are any filters applied to the DBM associated
360 with C<$db>. Otherwise returns FALSE.
364 =head1 Writing a Filter
366 Filters can be created in two main ways
368 =head2 Immediate Filters
370 An immediate filter allows you to specify the filter code to be used
371 at the point where the filter is applied to a dbm. In this mode the
372 Filter_*_Push methods expects to receive exactly two parameters.
374 my $db = tie %hash, 'SDBM_File', ...
375 $db->Filter_Push( Store => sub { },
376 Fetch => sub { });
378 The code reference associated with C<Store> will be called before any
379 key/value is written to the database and the code reference associated
380 with C<Fetch> will be called after any key/value is read from the
381 database.
383 For example, here is a sample filter that adds a trailing NULL character
384 to all strings before they are written to the DBM file, and removes the
385 trailing NULL when they are read from the DBM file
387 my $db = tie %hash, 'SDBM_File', ...
388 $db->Filter_Push( Store => sub { $_ .= "\x00" ; },
389 Fetch => sub { s/\x00$// ; });
392 Points to note:
394 =over 5
396 =item 1.
398 Both the Store and Fetch filters manipulate C<$_>.
400 =back
402 =head2 Canned Filters
404 Immediate filters are useful for one-off situations. For more generic
405 problems it can be useful to package the filter up in its own module.
407 The usage is for a canned filter is:
409 $db->Filter_Push("name", params)
411 where
413 =over 5
415 =item "name"
417 is the name of the module to load. If the string specified does not
418 contain the package separator characters "::", it is assumed to refer to
419 the full module name "DBM_Filter::name". This means that the full names
420 for canned filters, "null" and "utf8", included with this module are:
422 DBM_Filter::null
423 DBM_Filter::utf8
425 =item params
427 any optional parameters that need to be sent to the filter. See the
428 encode filter for an example of a module that uses parameters.
430 =back
432 The module that implements the canned filter can take one of two
433 forms. Here is a template for the first
435 package DBM_Filter::null ;
437 use strict;
438 use warnings;
440 sub Store
442 # store code here
445 sub Fetch
447 # fetch code here
453 Notes:
455 =over 5
457 =item 1.
459 The package name uses the C<DBM_Filter::> prefix.
461 =item 2.
463 The module I<must> have both a Store and a Fetch method. If only one is
464 present, or neither are present, a fatal error will be thrown.
466 =back
468 The second form allows the filter to hold state information using a
469 closure, thus:
471 package DBM_Filter::encoding ;
473 use strict;
474 use warnings;
476 sub Filter
478 my @params = @_ ;
481 return {
482 Store => sub { $_ = $encoding->encode($_) },
483 Fetch => sub { $_ = $encoding->decode($_) }
490 In this instance the "Store" and "Fetch" methods are encapsulated inside a
491 "Filter" method.
494 =head1 Filters Included
496 A number of canned filers are provided with this module. They cover a
497 number of the main areas that filters are needed when interfacing with
498 DBM files. They also act as templates for your own filters.
500 The filter included are:
502 =over 5
504 =item * utf8
506 This module will ensure that all data written to the DBM will be encoded
507 in UTF-8.
509 This module needs the Encode module.
511 =item * encode
513 Allows you to choose the character encoding will be store in the DBM file.
515 =item * compress
517 This filter will compress all data before it is written to the database
518 and uncompressed it on reading.
520 This module needs Compress::Zlib.
522 =item * int32
524 This module is used when interoperating with a C/C++ application that
525 uses a C int as either the key and/or value in the DBM file.
527 =item * null
529 This module ensures that all data written to the DBM file is null
530 terminated. This is useful when you have a perl script that needs
531 to interoperate with a DBM file that a C program also uses. A fairly
532 common issue is for the C application to include the terminating null
533 in a string when it writes to the DBM file. This filter will ensure that
534 all data written to the DBM file can be read by the C application.
536 =back
538 =head1 NOTES
540 =head2 Maintain Round Trip Integrity
542 When writing a DBM filter it is I<very> important to ensure that it is
543 possible to retrieve all data that you have written when the DBM filter
544 is in place. In practice, this means that whatever transformation is
545 applied to the data in the Store method, the I<exact> inverse operation
546 should be applied in the Fetch method.
548 If you don't provide an exact inverse transformation, you will find that
549 code like this will not behave as you expect.
551 while (my ($k, $v) = each %hash)
556 Depending on the transformation, you will find that one or more of the
557 following will happen
559 =over 5
561 =item 1
563 The loop will never terminate.
565 =item 2
567 Too few records will be retrieved.
569 =item 3
571 Too many will be retrieved.
573 =item 4
575 The loop will do the right thing for a while, but it will unexpectedly fail.
577 =back
579 =head2 Don't mix filtered & non-filtered data in the same database file.
581 This is just a restatement of the previous section. Unless you are
582 completely certain you know what you are doing, avoid mixing filtered &
583 non-filtered data.
585 =head1 EXAMPLE
587 Say you need to interoperate with a legacy C application that stores
588 keys as C ints and the values and null terminated UTF-8 strings. Here
589 is how you would set that up
591 my $db = tie %hash, 'SDBM_File', ...
593 $db->Filter_Key_Push('int32') ;
595 $db->Filter_Value_Push('utf8');
596 $db->Filter_Value_Push('null');
598 =head1 SEE ALSO
600 <DB_File>, L<GDBM_File>, L<NDBM_File>, L<ODBM_File>, L<SDBM_File>, L<perldbmfilter>
602 =head1 AUTHOR
604 Paul Marquess <pmqs@cpan.org>