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.008';
4 11     11   97662 use v5.10;
  11         46  
5 11     11   554 use Type::Library -base, -declare => qw( IPv4 IPv6 IPAddress CIDR NetIP );
  11         37988  
  11         138  
6 11     11   14539 use Type::Utils -all;
  11         19390  
  11         103  
7 11     11   33839 use Types::Standard -types;
  11         72557  
  11         153  
8 11     11   105415 use Net::IP ();
  11         1161584  
  11         500  
9 11     11   121 use Exporter 'import';
  11         29  
  11         9259  
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 12755 my ($str) = @_;
34 3         18 return Net::IP->new($str);
35             }
36              
37             sub cidr_contains {
38 27     27 0 4507 my ($cidr_str, $ip_str) = @_;
39 27 100       156 my $cidr = Net::IP->new($cidr_str) or return 0;
40 26 100       31936 my $ip = Net::IP->new($ip_str) or return 0;
41 25         24735 my $overlap = $ip->overlaps($cidr);
42 25   33     6564 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 4474 my ($ip_str) = @_;
47 9   100     26 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__