I have to use a type that can hole Ipv4 and Ipv6 addresses in memory efficient manner (in scala). As well as they should be performant. The two options I see are, using the scala BigInt type or a byte array. What the memory/perf hit in both cases?
BigInteger in Java takes 5 * 4 bytes
for 4 int
fields plus int
array. BigInt from Scala is just wrapper over BigInteger so it would be similar. So using Byte
array would definitely take less place.
I might also consider using type aliases with companion object and implicit extensions to keep type safety and rich API without additional overhead (it will still the same amount of space as Array[Byte]
.
trait IP
type IPv4 = Array[Byte] with IP //adding "with IP" would make sure compiler won't accept plain Array[Byte] when type IPv4 is needed
type IPv6 = Array[Byte] with IP
object IPv4 { //create similar for IPv6
def apply(ip: String) = {
ip.split("\\.").map(_.toByte).asInstanceOf[IPv4] //you can create IPv4("127.0.0.1")
}
object Implicits {
implicit class RichIPv4(ip: IPv4) {
def show(): String = ip.map(_.toString).mkString(".") //add method to show as string
def verify(): Boolean = ??? //additional methods
}
}
}
import IPV4.Implicits._
def printIP(ip: IPv4) = println(ip.show) //Will only accept arrays created by IPv4.apply
printIP(IPv4("127.0.0.1")) //ok
printIP(Array[Byte](127,0,0,1)) //won't compile
Alternatively, you should take a look at the great library scala-newtype , which does similar things but without additional boilerplate.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.