Skip to content

Commit

Permalink
Merge pull request #598 from vectos/feature-cidr-addresses
Browse files Browse the repository at this point in the history
cidr: Add addresses method
  • Loading branch information
mpilquist authored Jul 17, 2024
2 parents 40acfe1 + ae971de commit f734033
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
10 changes: 10 additions & 0 deletions shared/src/main/scala/com/comcast/ip4s/Cidr.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit f734033

Please sign in to comment.