File Coverage

blib/lib/IO/K8s/Types/Net.pm
Criterion Covered Total %
statement 26 26 100.0
branch 4 4 100.0
condition 4 6 66.6
subroutine 9 9 100.0
pod 0 3 0.0
total 43 48 89.5


line stmt bran cond sub pod time code
1             package IO::K8s::Types::Net;
2             # ABSTRACT: Type::Tiny constraints for IP addresses and CIDR notation
3             our $VERSION = '1.009';
4 11     11   103698 use v5.10;
  11         35  
5 11     11   509 use Type::Library -base, -declare => qw( IPv4 IPv6 IPAddress CIDR NetIP );
  11         35316  
  11         161  
6 11     11   12950 use Type::Utils -all;
  11         15004  
  11         151  
7 11     11   27457 use Types::Standard -types;
  11         75780  
  11         102  
8 11     11   104238 use Net::IP ();
  11         1210417  
  11         536  
9 11     11   122 use Exporter 'import';
  11         24  
  11         8540  
10              
11             our @EXPORT_OK = qw( parse_ip cidr_contains is_rfc1918 );
12              
13             declare IPv4, as Str, where {
14             !/\// && do { my $ip = Net::IP->new($_, 4); defined $ip && $ip->version == 4 };
15             }, message { "'$_' is not a valid IPv4 address" };
16              
17             declare IPv6, as Str, where {
18             !/\// && do { my $ip = Net::IP->new($_, 6); defined $ip && $ip->version == 6 };
19             }, message { "'$_' is not a valid IPv6 address" };
20              
21             declare IPAddress, as Str, where {
22             !/\// && defined Net::IP->new($_);
23             }, message { "'$_' is not a valid IP address" };
24              
25             declare CIDR, as Str, where {
26             /\// && defined Net::IP->new($_);
27             }, message { "'$_' is not valid CIDR notation" };
28              
29             declare NetIP, as InstanceOf['Net::IP'];
30             coerce NetIP, from Str, via { Net::IP->new($_) };
31              
32             sub parse_ip {
33 3     3 0 9616 my ($str) = @_;
34 3         14 return Net::IP->new($str);
35             }
36              
37             sub cidr_contains {
38 27     27 0 3167 my ($cidr_str, $ip_str) = @_;
39 27 100       77 my $cidr = Net::IP->new($cidr_str) or return 0;
40 26 100       18723 my $ip = Net::IP->new($ip_str) or return 0;
41 25         13222 my $overlap = $ip->overlaps($cidr);
42 25   33     3538 return defined $overlap && ($overlap == $Net::IP::IP_A_IN_B_OVERLAP || $overlap == $Net::IP::IP_IDENTICAL);
43             }
44              
45             sub is_rfc1918 {
46 9     9 0 2982 my ($ip_str) = @_;
47 9   100     15 return cidr_contains('10.0.0.0/8', $ip_str)
48             || cidr_contains('172.16.0.0/12', $ip_str)
49             || cidr_contains('192.168.0.0/16', $ip_str);
50             }
51              
52             1;
53              
54             __END__