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