WithCheksum 2.0
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Base / WithChecksum.pm
1
2 package MooseX::Storage::Base::WithChecksum;
3 use Moose::Role;
4
5 use Digest ();
6 use Storable ();
7 use MooseX::Storage::Engine;
8
9 our $VERSION = '0.01';
10
11 sub pack {
12     my ($self, @args ) = @_;
13
14     my $e = MooseX::Storage::Engine->new( object => $self );
15
16     my $collapsed = $e->collapse_object;
17     
18     $collapsed->{__DIGEST__} = $self->_digest_packed($collapsed, @args);
19     
20     return $collapsed;
21 }
22
23 sub unpack {
24     my ($class, $data, @args) = @_;
25
26     # check checksum on data
27     
28     my $old_checksum = $data->{__DIGEST__};
29     delete $data->{__DIGEST__};
30     
31     my $checksum = $class->_digest_packed($data, @args);
32
33     ($checksum eq $old_checksum)
34         || confess "Bad Checksum got=($checksum) expected=($old_checksum)";    
35
36     my $e = MooseX::Storage::Engine->new(class => $class);
37     $class->new($e->expand_object($data));
38 }
39
40
41 sub _digest_packed {
42     my ( $self, $collapsed, @args ) = @_;
43
44     my $d = shift @args;
45
46     if ( ref $d ) {
47         if ( $d->can("clone") ) {
48             $d = $d->clone;
49         } elsif ( $d->can("reset") ) {
50             $d->reset;
51         } else {
52             die "Can't clone or reset digest object: $d";
53         }
54     } else {
55         $d = Digest->new($d || "SHA1", @args);
56     }
57
58     {
59         local $Storable::canonical = 1;
60         $d->add( Storable::nfreeze($collapsed) );
61     }
62
63     return $d->hexdigest;
64 }
65
66
67 1;
68
69 __END__
70
71 =pod
72
73 =head1 NAME
74
75 MooseX::Storage::Base::WithChecksum
76
77 =head1 SYNOPSIS
78
79 =head1 DESCRIPTION
80
81 =head1 METHODS
82
83 =over 4
84
85 =item B<pack (?$salt)>
86
87 =item B<unpack ($data, ?$salt)>
88
89 =back
90
91 =head2 Introspection
92
93 =over 4
94
95 =item B<meta>
96
97 =back
98
99 =head1 BUGS
100
101 All complex software has bugs lurking in it, and this module is no 
102 exception. If you find a bug please either email me, or add the bug
103 to cpan-RT.
104
105 =head1 AUTHOR
106
107 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
108
109 =head1 COPYRIGHT AND LICENSE
110
111 Copyright 2007 by Infinity Interactive, Inc.
112
113 L<http://www.iinteractive.com>
114
115 This library is free software; you can redistribute it and/or modify
116 it under the same terms as Perl itself.
117
118 =cut