add comment about YAML::LibYAML
[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
72a40e08 11our $DIGEST_MARKER = '__DIGEST__';
88651e76 12
c4a322ec 13sub 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
25sub 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
43sub _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 691;
70
71__END__
72
73=pod
74
75=head1 NAME
76
77MooseX::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
103All complex software has bugs lurking in it, and this module is no
104exception. If you find a bug please either email me, or add the bug
105to cpan-RT.
106
107=head1 AUTHOR
108
109Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
110
111=head1 COPYRIGHT AND LICENSE
112
113Copyright 2007 by Infinity Interactive, Inc.
114
115L<http://www.iinteractive.com>
116
117This library is free software; you can redistribute it and/or modify
118it under the same terms as Perl itself.
119
120=cut