File Coverage

blib/lib/REFECO/Blockchain/Contract/Solidity/ABI/Type/Bytes.pm
Criterion Covered Total %
statement 38 39 97.4
branch 8 10 80.0
condition 1 5 20.0
subroutine 8 8 100.0
pod 0 2 0.0
total 55 64 85.9


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