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.1.0';
3              
4 10     10   63 use warnings;
  10         29  
  10         680  
5 10     10   74 use strict;
  10         21  
  10         304  
6 10     10   50 use base 'Data::CompactReadonly::V0::Node';
  10         17  
  10         5757  
7              
8             sub _init {
9 1069     1069   3639 my($class, %args) = @_;
10 1069         2492 my $root = $args{root};
11            
12 1069         3906 my $word = $root->_bytes_at_current_offset($class->_num_bytes());
13 1069         3594 return $class->_decode_word($word);
14             }
15              
16             # turn a sequence of bytes into an integer
17             sub _decode_word {
18 1808     1808   4242 my($class, $word) = @_;
19              
20 1808         14086 my $value = 0;
21 1808         6068 foreach my $byte (split(//, $word)) {
22 2659         4509 $value *= 256;
23 2659         5472 $value += ord($byte);
24             }
25 1808         8680 return $value;
26             }
27              
28             sub _create {
29 54     54   238 my($class, %args) = @_;
30 54         122 my $fh = $args{fh};
31 54         341 $class->_stash_already_seen(%args);
32              
33             print $fh $class->_type_byte_from_class().
34 54         341 $class->_get_bytes_from_word(abs($args{data}));
35 54         530 $class->_set_next_free_ptr(%args);
36             }
37              
38             sub _get_bytes_from_word {
39 65770     65770   147252 my($class, $word) = @_;
40 65770         242307 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 197109     197109   417899 my($class, $word, $num_bytes) = @_;
47              
48 197109         323035 my $bytes = '';
49 197109         464751 while($word) {
50 459403         963809 $bytes = chr($word & 0xff).$bytes;
51 459403         1041567 $word >>= 8;
52             }
53              
54             # zero-pad if needed
55 197109 100       446225 $bytes = (chr(0) x ($num_bytes - length($bytes))).$bytes
56             if(length($bytes) < $num_bytes);
57              
58 197109         5633605 return $bytes;
59             }
60              
61             1;