File Coverage

blib/lib/Data/CompactReadonly/V0/Scalar.pm
Criterion Covered Total %
statement 33 33 100.0
branch 2 2 100.0
condition n/a
subroutine 8 8 100.0
pod n/a
total 43 43 100.0


line stmt bran cond sub pod time code
1             package Data::CompactReadonly::V0::Scalar;
2             our $VERSION = '0.0.5';
3              
4 9     9   63 use warnings;
  9         20  
  9         327  
5 9     9   49 use strict;
  9         18  
  9         267  
6 9     9   45 use base 'Data::CompactReadonly::V0::Node';
  9         19  
  9         4396  
7              
8             sub _init {
9 986     986   2594 my($class, %args) = @_;
10 986         1714 my $root = $args{root};
11            
12 986         2629 my $word = $root->_bytes_at_current_offset($class->_num_bytes());
13 986         2696 return $class->_decode_word($word);
14             }
15              
16             # turn a sequence of bytes into an integer
17             sub _decode_word {
18 1657     1657   3469 my($class, $word) = @_;
19              
20 1657         2471 my $value = 0;
21 1657         4783 foreach my $byte (split(//, $word)) {
22 2501         3748 $value *= 256;
23 2501         4166 $value += ord($byte);
24             }
25 1657         6208 return $value;
26             }
27              
28             sub _create {
29 58     58   222 my($class, %args) = @_;
30 58         111 my $fh = $args{fh};
31 58         306 $class->_stash_already_seen(%args);
32              
33             print $fh $class->_type_byte_from_class().
34 58         347 $class->_get_bytes_from_word(abs($args{data}));
35 58         543 $class->_set_next_free_ptr(%args);
36             }
37              
38             sub _get_bytes_from_word {
39 65756     65756   151097 my($class, $word) = @_;
40 65756         164244 return $class->_encode_word_as_number_of_bytes($word, $class->_num_bytes());
41             }
42              
43             # given an integer and a number of bytes, encode that int
44             # as a sequence of bytes, zero-padding if necessary
45             sub _encode_word_as_number_of_bytes {
46 197068     197068   391382 my($class, $word, $num_bytes) = @_;
47              
48 197068         290410 my $bytes = '';
49 197068         402243 while($word) {
50 459363         931278 $bytes = chr($word & 0xff).$bytes;
51 459363         946390 $word >>= 8;
52             }
53              
54             # zero-pad if needed
55 197068 100       378108 $bytes = (chr(0) x ($num_bytes - length($bytes))).$bytes
56             if(length($bytes) < $num_bytes);
57              
58 197068         2983089 return $bytes;
59             }
60              
61             1;