File Coverage

blib/lib/Blockchain/Ethereum/ABI/Type/Bytes.pm
Criterion Covered Total %
statement 36 37 97.3
branch 8 10 80.0
condition 1 5 20.0
subroutine 8 8 100.0
pod 2 2 100.0
total 55 62 88.7


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