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