adding simple checksum role
[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::MD5  ('md5_hex');
6 use Data::Dumper ();
7 use MooseX::Storage::Engine;
8
9 our $VERSION = '0.01';
10
11 sub pack {
12     my ($self, $salt) = @_;
13     my $e = MooseX::Storage::Engine->new( object => $self );
14     my $collapsed = $e->collapse_object;
15     
16     # create checksum
17     
18     local $Data::Dumper::Sortkeys = 1;
19     my $dumped = Data::Dumper::Dumper($collapsed);
20
21     #warn $dumped;
22     
23     $salt ||= $dumped;
24     
25     $collapsed->{checksum} = md5_hex($dumped, $salt);
26     
27     return $collapsed;
28 }
29
30 sub unpack {
31     my ($class, $data, $salt) = @_;
32
33     # check checksum on data
34     
35     my $old_checksum = $data->{checksum};
36     delete $data->{checksum};
37     
38     local $Data::Dumper::Sortkeys = 1;
39     my $dumped = Data::Dumper::Dumper($data);
40     
41     #warn $dumped;
42     
43     $salt ||= $dumped;
44     
45     my $checksum = md5_hex($dumped, $salt);
46     
47     ($checksum eq $old_checksum)
48         || confess "Bad Checksum got=($checksum) expected=($data->{checksum})";    
49
50     my $e = MooseX::Storage::Engine->new(class => $class);
51     $class->new($e->expand_object($data));
52 }
53
54 1;
55
56 __END__
57
58 =pod
59
60 =head1 NAME
61
62 MooseX::Storage::Base::WithChecksum
63
64 =head1 SYNOPSIS
65
66 =head1 DESCRIPTION
67
68 =head1 METHODS
69
70 =over 4
71
72 =item B<pack (?$salt)>
73
74 =item B<unpack ($data, ?$salt)>
75
76 =back
77
78 =head2 Introspection
79
80 =over 4
81
82 =item B<meta>
83
84 =back
85
86 =head1 BUGS
87
88 All complex software has bugs lurking in it, and this module is no 
89 exception. If you find a bug please either email me, or add the bug
90 to cpan-RT.
91
92 =head1 AUTHOR
93
94 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
95
96 =head1 COPYRIGHT AND LICENSE
97
98 Copyright 2007 by Infinity Interactive, Inc.
99
100 L<http://www.iinteractive.com>
101
102 This library is free software; you can redistribute it and/or modify
103 it under the same terms as Perl itself.
104
105 =cut