From b625c08df9bff534204a7ad389147589e8b3e0f7 Mon Sep 17 00:00:00 2001 From: Sebastian Wallin Date: Tue, 8 Mar 2016 16:23:45 -0800 Subject: [PATCH 1/2] Fix divide_by_subnets to not hang indefinitely on wrong input --- lib/ip/base.rb | 1 + test/ip_test.rb | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/lib/ip/base.rb b/lib/ip/base.rb index 6ed5a71..042cc1a 100644 --- a/lib/ip/base.rb +++ b/lib/ip/base.rb @@ -220,6 +220,7 @@ def split # stop when subnets reach their smallest possible size (i.e. 31 for IP4) def divide_by_subnets(number_subnets) nets = [] + return nets if split.empty? nets << self loop do new_nets = [] diff --git a/test/ip_test.rb b/test/ip_test.rb index 6a69ed3..f90c71c 100644 --- a/test/ip_test.rb +++ b/test/ip_test.rb @@ -174,6 +174,14 @@ class IPTest < Minitest::Test IP.new('1.2.3.0/24').split end + it 'has divide_by_subnets returns empty array when single IPv4' do + assert_equal [], IP.new('1.2.3.4').divide_by_subnets(1) + end + + it 'has divide_by_subnets returns empty array when single IPv6' do + assert_equal [], IP.new('1:0:2:0:0:0:0:0').divide_by_subnets(1) + end + it 'has divide_by_subnets be exact' do assert_equal [IP.new('1.2.3.0/26'), IP.new('1.2.3.64/26'), IP.new('1.2.3.128/26'), IP.new('1.2.3.192/26')], From 0220a3fb0e5a30e65e9b368318dc0efa3632ee92 Mon Sep 17 00:00:00 2001 From: Sebastian Wallin Date: Tue, 8 Mar 2016 16:24:41 -0800 Subject: [PATCH 2/2] Fix divide_by_hosts to not crash on wrong input --- lib/ip/base.rb | 1 + test/ip_test.rb | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/lib/ip/base.rb b/lib/ip/base.rb index 042cc1a..b896e33 100644 --- a/lib/ip/base.rb +++ b/lib/ip/base.rb @@ -237,6 +237,7 @@ def divide_by_subnets(number_subnets) # subdivide a larger subnet into smaller subnets by number of hosts def divide_by_hosts(number_hosts) nets = [] + return nets if split.empty? nets << self while number_hosts <= (nets[0].split[0].size - 2) && nets[0].pfxlen <= (self.class::ADDR_BITS - 1) diff --git a/test/ip_test.rb b/test/ip_test.rb index f90c71c..e07c36c 100644 --- a/test/ip_test.rb +++ b/test/ip_test.rb @@ -206,6 +206,14 @@ class IPTest < Minitest::Test IP.new('1.2.3.0/24').divide_by_hosts(68) end + it 'has divide_by_hosts returns empty array when single IPv4' do + assert_equal [], IP.new('1.2.3.4/32').divide_by_hosts(68) + end + + it 'has divide_by_hosts returns empty array when single IPv6' do + assert_equal [], IP.new('1:0:2:0:0:0:0:0').divide_by_subnets(1) + end + it 'has size' do assert_equal 256, @addr.size end