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