diff --git a/shared/src/main/scala/com/comcast/ip4s/Cidr.scala b/shared/src/main/scala/com/comcast/ip4s/Cidr.scala index ff80c8c..6d027a5 100644 --- a/shared/src/main/scala/com/comcast/ip4s/Cidr.scala +++ b/shared/src/main/scala/com/comcast/ip4s/Cidr.scala @@ -114,6 +114,16 @@ sealed class Cidr[+A <: IpAddress] protected (val address: A, val prefixBits: In a => a >= start && a <= end } + /** Returns an iterator over all addresses in the range described by this CIDR. + * @return + */ + def addresses: Iterator[IpAddress] = { + val start: IpAddress = prefix + val end: IpAddress = last + + Iterator.iterate(start)(_.next).takeWhile(_ <= end) + } + override def toString: String = s"$address/$prefixBits" override def hashCode: Int = MurmurHash3.productHash(this, productPrefix.hashCode) override def equals(other: Any): Boolean = diff --git a/test-kit/shared/src/test/scala/com/comcast/ip4s/CidrTest.scala b/test-kit/shared/src/test/scala/com/comcast/ip4s/CidrTest.scala index 49dc9ed..49be88a 100644 --- a/test-kit/shared/src/test/scala/com/comcast/ip4s/CidrTest.scala +++ b/test-kit/shared/src/test/scala/com/comcast/ip4s/CidrTest.scala @@ -41,4 +41,11 @@ class CidrTest extends BaseTestSuite { assertEquals(cidr.isDefined, (prefixBits <= max && prefixBits >= 0)) } } + + test("addresses should return iterator") { + val cidr = Cidr(ipv4"10.0.0.0", 8) + val addresses = cidr.addresses + + assertEquals(addresses.size, 16777216) + } }