WithCheksum 2.0
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Base / WithChecksum.pm
CommitLineData
c4a322ec 1
2package MooseX::Storage::Base::WithChecksum;
3use Moose::Role;
4
98ae09f0 5use Digest ();
6use Storable ();
c4a322ec 7use MooseX::Storage::Engine;
8
9our $VERSION = '0.01';
10
11sub pack {
98ae09f0 12 my ($self, @args ) = @_;
13
c4a322ec 14 my $e = MooseX::Storage::Engine->new( object => $self );
c4a322ec 15
98ae09f0 16 my $collapsed = $e->collapse_object;
c4a322ec 17
98ae09f0 18 $collapsed->{__DIGEST__} = $self->_digest_packed($collapsed, @args);
c4a322ec 19
20 return $collapsed;
21}
22
23sub unpack {
98ae09f0 24 my ($class, $data, @args) = @_;
c4a322ec 25
26 # check checksum on data
27
98ae09f0 28 my $old_checksum = $data->{__DIGEST__};
29 delete $data->{__DIGEST__};
c4a322ec 30
98ae09f0 31 my $checksum = $class->_digest_packed($data, @args);
32
c4a322ec 33 ($checksum eq $old_checksum)
98ae09f0 34 || confess "Bad Checksum got=($checksum) expected=($old_checksum)";
c4a322ec 35
36 my $e = MooseX::Storage::Engine->new(class => $class);
37 $class->new($e->expand_object($data));
38}
39
98ae09f0 40
41sub _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
c4a322ec 671;
68
69__END__
70
71=pod
72
73=head1 NAME
74
75MooseX::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
101All complex software has bugs lurking in it, and this module is no
102exception. If you find a bug please either email me, or add the bug
103to cpan-RT.
104
105=head1 AUTHOR
106
107Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
108
109=head1 COPYRIGHT AND LICENSE
110
111Copyright 2007 by Infinity Interactive, Inc.
112
113L<http://www.iinteractive.com>
114
115This library is free software; you can redistribute it and/or modify
116it under the same terms as Perl itself.
117
118=cut