From 6477e5a14e0fbd02750cf87dc21900525f63452f Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Fri, 5 Nov 2010 15:27:41 -0400 Subject: [PATCH] Make combine_all operate recursively. Create a new test to test the recursive combine_all. Add a custom (==) implementation for Cidrs. Fix an incorrect test. --- src/Cidr.hs | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/Cidr.hs b/src/Cidr.hs index 823f43f..b5dc9d2 100644 --- a/src/Cidr.hs +++ b/src/Cidr.hs @@ -31,7 +31,7 @@ import Octet data Cidr = None | Cidr { ipv4address :: IPv4Address, maskbits :: Maskbits } - deriving (Eq) + instance Show Cidr where @@ -47,6 +47,9 @@ instance Arbitrary Cidr where coarbitrary _ = variant 0 +instance Eq Cidr where + cidr1 == cidr2 = (cidr1 `equivalent` cidr2) + -- Two CIDR ranges are equivalent if they have the same network bits -- and the masks are the same. @@ -194,9 +197,15 @@ redundant cidrlist cidr = any ((flip contains_proper) cidr) cidrlist -- adjacent Cidrs are combined into a larger one, they will be removed -- in the second step since the larger Cidr must contain the smaller -- two. +-- +-- Once this is done, we see whether or not the result is different +-- than the argument that was passed in. If nothing changed, we're +-- done and return the list that was passed to us. However, if +-- something changed, we recurse and try to combine the list again. combine_all :: [Cidr] -> [Cidr] -combine_all cidrs = - combine_contained unique_cidrs +combine_all cidrs + | cidrs == (combine_contained unique_cidrs) = cidrs + | otherwise = combine_all (combine_contained unique_cidrs) where unique_cidrs = nubBy equivalent valid_cidr_combinations valid_cidr_combinations = filter (/= Cidr.None) cidr_combinations @@ -358,8 +367,8 @@ test_combine_all1 = cidr3 = cidr_from_string "10.0.2.0/24" cidr4 = cidr_from_string "10.0.3.0/23" cidr5 = cidr_from_string "10.0.0.0/23" - expected_cidrs = [cidr4, cidr5] - test_cidrs = [cidr1, cidr2, cidr3, cidr4] + expected_cidrs = [cidr_from_string "10.0.0.0/22"] + test_cidrs = [cidr1, cidr2, cidr3, cidr4, cidr5] test_combine_all2 :: Test @@ -371,6 +380,18 @@ test_combine_all2 = test_cidrs = [cidr1, cidr1, cidr1, cidr1, cidr1] +test_combine_all3 :: Test +test_combine_all3 = + TestCase $ assertEqual "10.0.0.16, 10.0.0.17, 10.0.0.18, and 10.0.0.19 get combined into 10.0.0.16/30" expected_cidrs (combine_all test_cidrs) + where + cidr1 = cidr_from_string "10.0.0.16/32" + cidr2 = cidr_from_string "10.0.0.17/32" + cidr3 = cidr_from_string "10.0.0.18/32" + cidr4 = cidr_from_string "10.0.0.19/32" + expected_cidrs = [cidr_from_string "10.0.0.16/30"] + test_cidrs = [cidr1, cidr2, cidr3, cidr4] + + cidr_tests :: [Test] cidr_tests = [ test_min_host1, test_max_host1, @@ -386,7 +407,8 @@ cidr_tests = [ test_min_host1, test_combine_contained1, test_combine_contained2, test_combine_all1, - test_combine_all2 + test_combine_all2, + test_combine_all3 ] -- 2.44.2