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