Add Storable 0.7.2 from Raphael Manfredi,
[p5sagit/p5-mst-13.2.git] / ext / Storable / Storable.pm
1 ;# $Id: Storable.pm,v 0.7.1.2 2000/08/14 07:18:40 ram Exp $
2 ;#
3 ;#  Copyright (c) 1995-2000, Raphael Manfredi
4 ;#  
5 ;#  You may redistribute only under the terms of the Artistic License,
6 ;#  as specified in the README file that comes with the distribution.
7 ;#
8 ;# $Log: Storable.pm,v $
9 ;# Revision 0.7.1.2  2000/08/14 07:18:40  ram
10 ;# patch2: increased version number
11 ;#
12 ;# Revision 0.7.1.1  2000/08/13 20:08:58  ram
13 ;# patch1: mention new Clone(3) extension in SEE ALSO
14 ;# patch1: contributor Marc Lehmann added overloading and ref to tied items
15 ;# patch1: updated e-mail from Benjamin Holzman
16 ;#
17 ;# Revision 0.7  2000/08/03 22:04:44  ram
18 ;# Baseline for second beta release.
19 ;#
20
21 require DynaLoader;
22 require Exporter;
23 package Storable; @ISA = qw(Exporter DynaLoader);
24
25 @EXPORT = qw(store retrieve);
26 @EXPORT_OK = qw(
27         nstore store_fd nstore_fd retrieve_fd
28         freeze nfreeze thaw
29         dclone
30 );
31
32 use AutoLoader;
33 use vars qw($forgive_me $VERSION);
34
35 $VERSION = '0.702';
36 *AUTOLOAD = \&AutoLoader::AUTOLOAD;             # Grrr...
37
38 #
39 # Use of Log::Agent is optional
40 #
41
42 eval "use Log::Agent";
43
44 unless (defined @Log::Agent::EXPORT) {
45         eval q{
46                 sub logcroak {
47                         require Carp;
48                         Carp::croak(@_);
49                 }
50         };
51 }
52
53 sub logcroak;
54
55 bootstrap Storable;
56 1;
57 __END__
58
59 #
60 # store
61 #
62 # Store target object hierarchy, identified by a reference to its root.
63 # The stored object tree may later be retrieved to memory via retrieve.
64 # Returns undef if an I/O error occurred, in which case the file is
65 # removed.
66 #
67 sub store {
68         return _store(\&pstore, @_);
69 }
70
71 #
72 # nstore
73 #
74 # Same as store, but in network order.
75 #
76 sub nstore {
77         return _store(\&net_pstore, @_);
78 }
79
80 # Internal store to file routine
81 sub _store {
82         my $xsptr = shift;
83         my $self = shift;
84         my ($file) = @_;
85         logcroak "not a reference" unless ref($self);
86         logcroak "too many arguments" unless @_ == 1;   # No @foo in arglist
87         local *FILE;
88         open(FILE, ">$file") || logcroak "can't create $file: $!";
89         binmode FILE;                           # Archaic systems...
90         my $da = $@;                            # Don't mess if called from exception handler
91         my $ret;
92         # Call C routine nstore or pstore, depending on network order
93         eval { $ret = &$xsptr(*FILE, $self) };
94         close(FILE) or $ret = undef;
95         unlink($file) or warn "Can't unlink $file: $!\n" if $@ || !defined $ret;
96         logcroak $@ if $@ =~ s/\.?\n$/,/;
97         $@ = $da;
98         return $ret ? $ret : undef;
99 }
100
101 #
102 # store_fd
103 #
104 # Same as store, but perform on an already opened file descriptor instead.
105 # Returns undef if an I/O error occurred.
106 #
107 sub store_fd {
108         return _store_fd(\&pstore, @_);
109 }
110
111 #
112 # nstore_fd
113 #
114 # Same as store_fd, but in network order.
115 #
116 sub nstore_fd {
117         my ($self, $file) = @_;
118         return _store_fd(\&net_pstore, @_);
119 }
120
121 # Internal store routine on opened file descriptor
122 sub _store_fd {
123         my $xsptr = shift;
124         my $self = shift;
125         my ($file) = @_;
126         logcroak "not a reference" unless ref($self);
127         logcroak "too many arguments" unless @_ == 1;   # No @foo in arglist
128         my $fd = fileno($file);
129         logcroak "not a valid file descriptor" unless defined $fd;
130         my $da = $@;                            # Don't mess if called from exception handler
131         my $ret;
132         # Call C routine nstore or pstore, depending on network order
133         eval { $ret = &$xsptr($file, $self) };
134         logcroak $@ if $@ =~ s/\.?\n$/,/;
135         $@ = $da;
136         return $ret ? $ret : undef;
137 }
138
139 #
140 # freeze
141 #
142 # Store oject and its hierarchy in memory and return a scalar
143 # containing the result.
144 #
145 sub freeze {
146         _freeze(\&mstore, @_);
147 }
148
149 #
150 # nfreeze
151 #
152 # Same as freeze but in network order.
153 #
154 sub nfreeze {
155         _freeze(\&net_mstore, @_);
156 }
157
158 # Internal freeze routine
159 sub _freeze {
160         my $xsptr = shift;
161         my $self = shift;
162         logcroak "not a reference" unless ref($self);
163         logcroak "too many arguments" unless @_ == 0;   # No @foo in arglist
164         my $da = $@;                            # Don't mess if called from exception handler
165         my $ret;
166         # Call C routine mstore or net_mstore, depending on network order
167         eval { $ret = &$xsptr($self) };
168         logcroak $@ if $@ =~ s/\.?\n$/,/;
169         $@ = $da;
170         return $ret ? $ret : undef;
171 }
172
173 #
174 # retrieve
175 #
176 # Retrieve object hierarchy from disk, returning a reference to the root
177 # object of that tree.
178 #
179 sub retrieve {
180         my ($file) = @_;
181         local *FILE;
182         open(FILE, "$file") || logcroak "can't open $file: $!";
183         binmode FILE;                                                   # Archaic systems...
184         my $self;
185         my $da = $@;                                                    # Could be from exception handler
186         eval { $self = pretrieve(*FILE) };              # Call C routine
187         close(FILE);
188         logcroak $@ if $@ =~ s/\.?\n$/,/;
189         $@ = $da;
190         return $self;
191 }
192
193 #
194 # retrieve_fd
195 #
196 # Same as retrieve, but perform from an already opened file descriptor instead.
197 #
198 sub retrieve_fd {
199         my ($file) = @_;
200         my $fd = fileno($file);
201         logcroak "not a valid file descriptor" unless defined $fd;
202         my $self;
203         my $da = $@;                                                    # Could be from exception handler
204         eval { $self = pretrieve($file) };              # Call C routine
205         logcroak $@ if $@ =~ s/\.?\n$/,/;
206         $@ = $da;
207         return $self;
208 }
209
210 #
211 # thaw
212 #
213 # Recreate objects in memory from an existing frozen image created
214 # by freeze.  If the frozen image passed is undef, return undef.
215 #
216 sub thaw {
217         my ($frozen) = @_;
218         return undef unless defined $frozen;
219         my $self;
220         my $da = $@;                                                    # Could be from exception handler
221         eval { $self = mretrieve($frozen) };    # Call C routine
222         logcroak $@ if $@ =~ s/\.?\n$/,/;
223         $@ = $da;
224         return $self;
225 }
226
227 =head1 NAME
228
229 Storable - persistency for perl data structures
230
231 =head1 SYNOPSIS
232
233  use Storable;
234  store \%table, 'file';
235  $hashref = retrieve('file');
236
237  use Storable qw(nstore store_fd nstore_fd freeze thaw dclone);
238
239  # Network order
240  nstore \%table, 'file';
241  $hashref = retrieve('file');   # There is NO nretrieve()
242
243  # Storing to and retrieving from an already opened file
244  store_fd \@array, \*STDOUT;
245  nstore_fd \%table, \*STDOUT;
246  $aryref = retrieve_fd(\*SOCKET);
247  $hashref = retrieve_fd(\*SOCKET);
248
249  # Serializing to memory
250  $serialized = freeze \%table;
251  %table_clone = %{ thaw($serialized) };
252
253  # Deep (recursive) cloning
254  $cloneref = dclone($ref);
255
256 =head1 DESCRIPTION
257
258 The Storable package brings persistency to your perl data structures
259 containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be
260 convenientely stored to disk and retrieved at a later time.
261
262 It can be used in the regular procedural way by calling C<store> with
263 a reference to the object to be stored, along with the file name where
264 the image should be written.
265 The routine returns C<undef> for I/O problems or other internal error,
266 a true value otherwise. Serious errors are propagated as a C<die> exception.
267
268 To retrieve data stored to disk, use C<retrieve> with a file name,
269 and the objects stored into that file are recreated into memory for you,
270 a I<reference> to the root object being returned. In case an I/O error
271 occurs while reading, C<undef> is returned instead. Other serious
272 errors are propagated via C<die>.
273
274 Since storage is performed recursively, you might want to stuff references
275 to objects that share a lot of common data into a single array or hash
276 table, and then store that object. That way, when you retrieve back the
277 whole thing, the objects will continue to share what they originally shared.
278
279 At the cost of a slight header overhead, you may store to an already
280 opened file descriptor using the C<store_fd> routine, and retrieve
281 from a file via C<retrieve_fd>. Those names aren't imported by default,
282 so you will have to do that explicitely if you need those routines.
283 The file descriptor you supply must be already opened, for read
284 if you're going to retrieve and for write if you wish to store.
285
286         store_fd(\%table, *STDOUT) || die "can't store to stdout\n";
287         $hashref = retrieve_fd(*STDIN);
288
289 You can also store data in network order to allow easy sharing across
290 multiple platforms, or when storing on a socket known to be remotely
291 connected. The routines to call have an initial C<n> prefix for I<network>,
292 as in C<nstore> and C<nstore_fd>. At retrieval time, your data will be
293 correctly restored so you don't have to know whether you're restoring
294 from native or network ordered data.
295
296 When using C<retrieve_fd>, objects are retrieved in sequence, one
297 object (i.e. one recursive tree) per associated C<store_fd>.
298
299 If you're more from the object-oriented camp, you can inherit from
300 Storable and directly store your objects by invoking C<store> as
301 a method. The fact that the root of the to-be-stored tree is a
302 blessed reference (i.e. an object) is special-cased so that the
303 retrieve does not provide a reference to that object but rather the
304 blessed object reference itself. (Otherwise, you'd get a reference
305 to that blessed object).
306
307 =head1 MEMORY STORE
308
309 The Storable engine can also store data into a Perl scalar instead, to
310 later retrieve them. This is mainly used to freeze a complex structure in
311 some safe compact memory place (where it can possibly be sent to another
312 process via some IPC, since freezing the structure also serializes it in
313 effect). Later on, and maybe somewhere else, you can thaw the Perl scalar
314 out and recreate the original complex structure in memory.
315
316 Surprisingly, the routines to be called are named C<freeze> and C<thaw>.
317 If you wish to send out the frozen scalar to another machine, use
318 C<nfreeze> instead to get a portable image.
319
320 Note that freezing an object structure and immediately thawing it
321 actually achieves a deep cloning of that structure:
322
323     dclone(.) = thaw(freeze(.))
324
325 Storable provides you with a C<dclone> interface which does not create
326 that intermediary scalar but instead freezes the structure in some
327 internal memory space and then immediatly thaws it out.
328
329 =head1 SPEED
330
331 The heart of Storable is written in C for decent speed. Extra low-level
332 optimization have been made when manipulating perl internals, to
333 sacrifice encapsulation for the benefit of a greater speed.
334
335 =head1 CANONICAL REPRESENTATION
336
337 Normally Storable stores elements of hashes in the order they are
338 stored internally by Perl, i.e. pseudo-randomly.  If you set
339 C<$Storable::canonical> to some C<TRUE> value, Storable will store
340 hashes with the elements sorted by their key.  This allows you to
341 compare data structures by comparing their frozen representations (or
342 even the compressed frozen representations), which can be useful for
343 creating lookup tables for complicated queries.
344
345 Canonical order does not imply network order, those are two orthogonal
346 settings.
347
348 =head1 ERROR REPORTING
349
350 Storable uses the "exception" paradigm, in that it does not try to workaround
351 failures: if something bad happens, an exception is generated from the
352 caller's perspective (see L<Carp> and C<croak()>).  Use eval {} to trap
353 those exceptions.
354
355 When Storable croaks, it tries to report the error via the C<logcroak()>
356 routine from the C<Log::Agent> package, if it is available.
357
358 =head1 WIZARDS ONLY
359
360 =head2 Hooks
361
362 Any class may define hooks that will be called during the serialization
363 and deserialization process on objects that are instances of that class.
364 Those hooks can redefine the way serialization is performed (and therefore,
365 how the symetrical deserialization should be conducted).
366
367 Since we said earlier:
368
369     dclone(.) = thaw(freeze(.))
370
371 everything we say about hooks should also hold for deep cloning. However,
372 hooks get to know whether the operation is a mere serialization, or a cloning.
373
374 Therefore, when serializing hooks are involved,
375
376     dclone(.) <> thaw(freeze(.))
377
378 Well, you could keep them in sync, but there's no guarantee it will always
379 hold on classes somebody else wrote.  Besides, there is little to gain in
380 doing so: a serializing hook could only keep one attribute of an object,
381 which is probably not what should happen during a deep cloning of that
382 same object.
383
384 Here is the hooking interface:
385
386 =over
387
388 =item C<STORABLE_freeze> I<obj>, I<cloning>
389
390 The serializing hook, called on the object during serialization.  It can be
391 inherited, or defined in the class itself, like any other method.
392
393 Arguments: I<obj> is the object to serialize, I<cloning> is a flag indicating
394 whether we're in a dclone() or a regular serialization via store() or freeze().
395
396 Returned value: A LIST C<($serialized, $ref1, $ref2, ...)> where $serialized
397 is the serialized form to be used, and the optional $ref1, $ref2, etc... are
398 extra references that you wish to let the Storable engine serialize.
399
400 At deserialization time, you will be given back the same LIST, but all the
401 extra references will be pointing into the deserialized structure.
402
403 The B<first time> the hook is hit in a serialization flow, you may have it
404 return an empty list.  That will signal the Storable engine to further
405 discard that hook for this class and to therefore revert to the default
406 serialization of the underlying Perl data.  The hook will again be normally
407 processed in the next serialization.
408
409 Unless you know better, serializing hook should always say:
410
411     sub STORABLE_freeze {
412         my ($self, $cloning) = @_;
413         return if $cloning;         # Regular default serialization
414         ....
415     }
416
417 in order to keep reasonable dclone() semantics.
418
419 =item C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, ...
420
421 The deserializing hook called on the object during deserialization.
422 But wait. If we're deserializing, there's no object yet... right?
423
424 Wrong: the Storable engine creates an empty one for you.  If you know Eiffel,
425 you can view C<STORABLE_thaw> as an alternate creation routine.
426
427 This means the hook can be inherited like any other method, and that
428 I<obj> is your blessed reference for this particular instance.
429
430 The other arguments should look familiar if you know C<STORABLE_freeze>:
431 I<cloning> is true when we're part of a deep clone operation, I<serialized>
432 is the serialized string you returned to the engine in C<STORABLE_freeze>,
433 and there may be an optional list of references, in the same order you gave
434 them at serialization time, pointing to the deserialized objects (which
435 have been processed courtesy of the Storable engine).
436
437 It is up to you to use these information to populate I<obj> the way you want.
438
439 Returned value: none.
440
441 =back
442
443 =head2 Predicates
444
445 Predicates are not exportable.  They must be called by explicitely prefixing
446 them with the Storable package name.
447
448 =over
449
450 =item C<Storable::last_op_in_netorder>
451
452 The C<Storable::last_op_in_netorder()> predicate will tell you whether
453 network order was used in the last store or retrieve operation.  If you
454 don't know how to use this, just forget about it.
455
456 =item C<Storable::is_storing>
457
458 Returns true if within a store operation (via STORABLE_freeze hook).
459
460 =item C<Storable::is_retrieving>
461
462 Returns true if within a retrieve operation, (via STORABLE_thaw hook).
463
464 =back
465
466 =head2 Recursion
467
468 With hooks comes the ability to recurse back to the Storable engine.  Indeed,
469 hooks are regular Perl code, and Storable is convenient when it comes to
470 serialize and deserialize things, so why not use it to handle the
471 serialization string?
472
473 There are a few things you need to know however:
474
475 =over
476
477 =item *
478
479 You can create endless loops if the things you serialize via freeze()
480 (for instance) point back to the object we're trying to serialize in the hook.
481
482 =item *
483
484 Shared references among objects will not stay shared: if we're serializing
485 the list of object [A, C] where both object A and C refer to the SAME object
486 B, and if there is a serializing hook in A that says freeze(B), then when
487 deserializing, we'll get [A', C'] where A' refers to B', but C' refers to D,
488 a deep clone of B'.  The topology was not preserved.
489
490 =back
491
492 That's why C<STORABLE_freeze> lets you provide a list of references
493 to serialize.  The engine guarantees that those will be serialized in the
494 same context as the other objects, and therefore that shared objects will
495 stay shared.
496
497 In the above [A, C] example, the C<STORABLE_freeze> hook could return:
498
499         ("something", $self->{B})
500
501 and the B part would be serialized by the engine.  In C<STORABLE_thaw>, you
502 would get back the reference to the B' object, deserialized for you.
503
504 Therefore, recursion should normally be avoided, but is nonetheless supported.
505
506 =head2 Deep Cloning
507
508 There is a new Clone module available on CPAN which implements deep cloning
509 natively, i.e. without freezing to memory and thawing the result.  It is
510 aimed to replace Storable's dclone() some day.  However, it does not currently
511 support Storable hooks to redefine the way deep cloning is performed.
512
513 =head1 EXAMPLES
514
515 Here are some code samples showing a possible usage of Storable:
516
517         use Storable qw(store retrieve freeze thaw dclone);
518
519         %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
520
521         store(\%color, '/tmp/colors') or die "Can't store %a in /tmp/colors!\n";
522
523         $colref = retrieve('/tmp/colors');
524         die "Unable to retrieve from /tmp/colors!\n" unless defined $colref;
525         printf "Blue is still %lf\n", $colref->{'Blue'};
526
527         $colref2 = dclone(\%color);
528
529         $str = freeze(\%color);
530         printf "Serialization of %%color is %d bytes long.\n", length($str);
531         $colref3 = thaw($str);
532
533 which prints (on my machine):
534
535         Blue is still 0.100000
536         Serialization of %color is 102 bytes long.
537
538 =head1 WARNING
539
540 If you're using references as keys within your hash tables, you're bound
541 to disapointment when retrieving your data. Indeed, Perl stringifies
542 references used as hash table keys. If you later wish to access the
543 items via another reference stringification (i.e. using the same
544 reference that was used for the key originally to record the value into
545 the hash table), it will work because both references stringify to the
546 same string.
547
548 It won't work across a C<store> and C<retrieve> operations however, because
549 the addresses in the retrieved objects, which are part of the stringified
550 references, will probably differ from the original addresses. The
551 topology of your structure is preserved, but not hidden semantics
552 like those.
553
554 On platforms where it matters, be sure to call C<binmode()> on the
555 descriptors that you pass to Storable functions.
556
557 Storing data canonically that contains large hashes can be
558 significantly slower than storing the same data normally, as
559 temprorary arrays to hold the keys for each hash have to be allocated,
560 populated, sorted and freed.  Some tests have shown a halving of the
561 speed of storing -- the exact penalty will depend on the complexity of
562 your data.  There is no slowdown on retrieval.
563
564 =head1 BUGS
565
566 You can't store GLOB, CODE, FORMLINE, etc... If you can define
567 semantics for those operations, feel free to enhance Storable so that
568 it can deal with them.
569
570 The store functions will C<croak> if they run into such references
571 unless you set C<$Storable::forgive_me> to some C<TRUE> value. In that
572 case, the fatal message is turned in a warning and some
573 meaningless string is stored instead.
574
575 Setting C<$Storable::canonical> may not yield frozen strings that
576 compare equal due to possible stringification of numbers. When the
577 string version of a scalar exists, it is the form stored, therefore
578 if you happen to use your numbers as strings between two freezing
579 operations on the same data structures, you will get different
580 results.
581
582 Due to the aforementionned optimizations, Storable is at the mercy
583 of perl's internal redesign or structure changes. If that bothers
584 you, you can try convincing Larry that what is used in Storable
585 should be documented and consistently kept in future revisions.
586
587 =head1 CREDITS
588
589 Thank you to (in chronological order):
590
591         Jarkko Hietaniemi <jhi@iki.fi>
592         Ulrich Pfeifer <pfeifer@charly.informatik.uni-dortmund.de>
593         Benjamin A. Holzman <bah@ecnvantage.com>
594         Andrew Ford <A.Ford@ford-mason.co.uk>
595         Gisle Aas <gisle@aas.no>
596         Jeff Gresham <gresham_jeffrey@jpmorgan.com>
597         Murray Nesbitt <murray@activestate.com>
598         Marc Lehmann <pcg@opengroup.org>
599
600 for their bug reports, suggestions and contributions.
601
602 Benjamin Holzman contributed the tied variable support, Andrew Ford
603 contributed the canonical order for hashes, and Gisle Aas fixed
604 a few misunderstandings of mine regarding the Perl internals,
605 and optimized the emission of "tags" in the output streams by
606 simply counting the objects instead of tagging them (leading to
607 a binary incompatibility for the Storable image starting at version
608 0.6--older images are of course still properly understood).
609 Murray Nesbitt made Storable thread-safe.  Marc Lehmann added overloading
610 and reference to tied items support.
611
612 =head1 TRANSLATIONS
613
614 There is a Japanese translation of this man page available at
615 http://member.nifty.ne.jp/hippo2000/perltips/storable.htm ,
616 courtesy of Kawai, Takanori <kawai@nippon-rad.co.jp>.
617
618 =head1 AUTHOR
619
620 Raphael Manfredi F<E<lt>Raphael_Manfredi@pobox.comE<gt>>
621
622 =head1 SEE ALSO
623
624 Clone(3).
625
626 =cut
627