File Coverage

blib/lib/Blockchain/Ethereum/ABI/Type/Bytes.pm
Criterion Covered Total %
statement 35 36 97.2
branch 8 10 80.0
condition 1 5 20.0
subroutine 7 7 100.0
pod 2 2 100.0
total 53 60 88.3


line stmt bran cond sub pod time code
1             package Blockchain::Ethereum::ABI::Type::Bytes;
2              
3 4     4   2189 use v5.26;
  4         18  
4 4     4   27 use strict;
  4         8  
  4         108  
5 4     4   21 use warnings;
  4         10  
  4         123  
6              
7 4     4   22 use Carp;
  4         8  
  4         296  
8 4     4   33 use parent qw(Blockchain::Ethereum::ABI::Type);
  4         11  
  4         21  
9              
10             sub encode {
11 28     28 1 45 my $self = shift;
12 28 100       80 return $self->_encoded if $self->_encoded;
13             # remove 0x and validates the hexadecimal value
14 12 50 0     38 croak 'Invalid hexadecimal value ' . $self->_data // 'undef'
15             unless $self->_data =~ /^(?:0x|0X)?([a-fA-F0-9]+)$/;
16 12         36 my $hex = $1;
17              
18 12         61 my $data_length = length(pack("H*", $hex));
19 12 100       36 unless ($self->fixed_length) {
20             # for dynamic length basic types the length must be included
21 6         36 $self->_push_dynamic($self->_encode_length($data_length));
22 6         18 $self->_push_dynamic($self->pad_right($hex));
23             } else {
24 6 50 33     20 croak "Invalid data length, signature: @{[$self->fixed_length]}, data length: $data_length"
  0         0  
25             if $self->fixed_length && $data_length != $self->fixed_length;
26 6         26 $self->_push_static($self->pad_right($hex));
27             }
28              
29 12         41 return $self->_encoded;
30             }
31              
32             sub decode {
33 9     9 1 17 my $self = shift;
34 9         67 my @data = $self->_data->@*;
35              
36 9         17 my $hex_data;
37 9         24 my $size = $self->fixed_length;
38 9 100       22 unless ($self->fixed_length) {
39 4         11 $size = hex shift @data;
40              
41 4         13 $hex_data = join('', @data);
42             } else {
43 5         8 $hex_data = $data[0];
44             }
45              
46 9         57 my $bytes = substr(pack("H*", $hex_data), 0, $size);
47 9         78 return sprintf "0x%s", unpack("H*", $bytes);
48             }
49              
50             1;
51              
52             __END__