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