From 7b3ec2a3635ca887ec0ced3e4b93c16949a02a47 Mon Sep 17 00:00:00 2001 From: Fristi Date: Mon, 15 Jul 2024 15:20:13 +0200 Subject: [PATCH 1/2] cidr: Add addresses method --- shared/src/main/scala/com/comcast/ip4s/Cidr.scala | 11 +++++++++++ .../src/test/scala/com/comcast/ip4s/CidrTest.scala | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/shared/src/main/scala/com/comcast/ip4s/Cidr.scala b/shared/src/main/scala/com/comcast/ip4s/Cidr.scala index ff80c8c..125a997 100644 --- a/shared/src/main/scala/com/comcast/ip4s/Cidr.scala +++ b/shared/src/main/scala/com/comcast/ip4s/Cidr.scala @@ -114,6 +114,17 @@ 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) + } } From ae971de1fce2c8f25ab9509f26768121b3c5e68c Mon Sep 17 00:00:00 2001 From: Fristi Date: Tue, 16 Jul 2024 16:20:00 +0200 Subject: [PATCH 2/2] Formatting --- shared/src/main/scala/com/comcast/ip4s/Cidr.scala | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/shared/src/main/scala/com/comcast/ip4s/Cidr.scala b/shared/src/main/scala/com/comcast/ip4s/Cidr.scala index 125a997..6d027a5 100644 --- a/shared/src/main/scala/com/comcast/ip4s/Cidr.scala +++ b/shared/src/main/scala/com/comcast/ip4s/Cidr.scala @@ -114,10 +114,9 @@ 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 - */ + /** 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