| 1 | package MYDan::Util::FastMD5; | ||
| 2 | |||
| 3 | =head1 NAME | ||
| 4 | |||
| 5 | MYDan::Util::FastMD5 | ||
| 6 | |||
| 7 | =cut | ||
| 8 | use warnings; | ||
| 9 | use strict; | ||
| 10 | |||
| 11 | use Digest::MD5; | ||
| 12 | use MYDan::Util::OptConf; | ||
| 13 | use Fcntl qw(:flock SEEK_END); | ||
| 14 | |||
| 15 | our $threshold; | ||
| 16 | BEGIN{ | ||
| 17 | $threshold = MYDan::Util::OptConf->load()->dump('util')->{fastmd5} || 1099511627776; | ||
| 18 | }; | ||
| 19 | |||
| 20 | =head1 SYNOPSIS | ||
| 21 | |||
| 22 | use MYDan::Util::FastMD5; | ||
| 23 | MYDan::Util::FastMD5->hexdigest( '/path/file' ); | ||
| 24 | |||
| 25 | =head1 Methods | ||
| 26 | |||
| 27 | =head3 hexdigest( $file ) | ||
| 28 | |||
| 29 | =cut | ||
| 30 | |||
| 31 | sub hexdigest | ||
| 32 | { | ||
| 33 | my ( $class, $file ) = splice @_; | ||
| 34 | |||
| 35 | my ( $len, $md5 ) = 1048576; | ||
| 36 | |||
| 37 | open my $H, '<', $file or die "Can't open '$file': $!"; | ||
| 38 | |||
| 39 | my $size = ( stat $file )[7]; | ||
| 40 | if( $size > $threshold && $size > $len * 2 ) | ||
| 41 | { | ||
| 42 | my ( $head, $tail ); | ||
| 43 | |||
| 44 | die "read fail" unless $len eq sysread $H, $head, $len; | ||
| 45 | die "seek fail" unless seek $H, -$len, SEEK_END; | ||
| 46 | die "read fail" unless $len eq sysread $H, $tail, $len; | ||
| 47 | |||
| 48 | $md5 = Digest::MD5->new->add( join ':', $size, $head, $tail )->hexdigest; | ||
| 49 | } | ||
| 50 | else { $md5 = Digest::MD5->new()->addfile( $H )->hexdigest(); } | ||
| 51 | |||
| 52 | close $H; | ||
| 53 | |||
| 54 | return $md5; | ||
| 55 | } | ||
| 56 | |||
| 57 | 1; |