blib/lib/Data/Floid.pm untested

filter: Statementstmt 0.0% 0 / 66 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 116 CC 14 SCAR 40.5
CC
14
Cov
0%
mint
110.0
serialize
20.0
new
6.0
CRAP 57.2
1 package Data::Floid;
2  
3 # ABSTRACT: simple, lightweight unique identifier generator
4  
5 use strict;
6 use warnings;
7  
8 use Fcntl;
9 use DB_File;
10  
11 sub new {
12 my $cls = shift;
13 unshift @_, 'directory' if @_ % 2;
14 my %self = @_;
15 my ($ifile, $lfile) = map { $self{'directory'} . '/' . $_ } qw(floid.idx floid.log);
16 tie my %index, 'DB_File', $ifile, O_CREAT, 0644, $DB_BTREE or die "Can't open index file $ifile: $!";
17 bless {
18 %self,
19 'logfile' => $lfile,
20 'logfh' => undef,
21 'index' => \%index,
22 }, $cls;
23 }
24  
25 sub mint {
26 my ($self, $spec, $data) = @_;
27 my $index = $self->{'index'};
28 my $logfh = $self->{'logfh'};
29 if (!defined $logfh) {
30 open $logfh, '>>', $self->{'logfile'} or die "Can't open log file $self->{'logfile'}: $!";
31 }
32 if ($spec =~ /^([^%]*)%R(\d*)x([^%]*)$/) {
33 my ($pfx, $size, $sfx) = ($1, $2, $3);
34 use Digest;
35 my $hash = eval { Digest->new('SHA-256') }
36 || eval { Digest->new('MD5' ) }
37 || die;
38 my $next;
39 my $fmt = '%';
40 $fmt .= "-$size.$size" if $size;
41 $fmt .= 's';
42 while (1) {
43 $hash->add($$, ':', rand, ':', time);
44 $next = $pfx . sprintf($fmt, $hash->clone->hexdigest) . $sfx;
45 if (!exists $index->{'#'.$next}) {
46 $index->{'#'.$next} = 1; # serialize($data);
47 print $logfh 'ID ', $next, ' FROM ', $spec;
48 print $logfh ' DATA ', serialize($data) if defined $data;
49 print $logfh "\n";
50 return $next;
51 }
52 }
53 return $next;
54 }
55 elsif ($spec =~ /^([^%]*)%N(\d*)([dx])([^%]*)$/) {
56 my ($pfx, $size, $type, $sfx) = ($1, $2, $3, $4);
57 my $fmt = '%';
58 $fmt .= '0'.$size if $size;
59 $fmt .= $type;
60 my $nextint = ++$index->{'<'.$spec};
61 my $next = $pfx . sprintf $fmt, $nextint . $sfx;
62 die if exists $index->{'#'.$next};
63 $index->{'#'.$next} = 1; # serialize($data);
64 print $logfh 'ID ', $next, ' FROM ', $spec, ' INCR ', $nextint+1;
65 print $logfh ' DATA ', serialize($data) if defined $data;
66 print $logfh "\n";
67 return $next;
68 }
69 else {
70 die;
71 }
72 }
73  
74 sub serialize {
75 my ($val) = @_;
76 return '~' if !defined $val;
77 my $ref = ref $val;
78 return '=' . $val if $ref eq '';
79 return '=' . $$val if $ref eq 'SCALAR';
80 die;
81 }
82  
83 1;