Print address seperated by dashes.

This commit is contained in:
Felix Ableitner 2015-07-27 13:18:02 +02:00
parent cdece0ef42
commit 625743d174
2 changed files with 30 additions and 3 deletions

View file

@ -14,10 +14,13 @@ object AddressTest {
val a4 = new Address("4444459893F8810C4024CFC951374AABA1F4DE6347A3D7D8E44918AD1FF2BA36")
val Addresses = Set(a1, a1Dashed, a2, a3, a4, Address.Broadcast, Address.Null)
val a1Binary: Array[Byte] = Array(-91, 27, 116, 71, 94, -26, 34, -61, -55, 36, -37, 20, 118, 104,
-8, 94, 2, 76, -96, -76, 76, -95, 70, -75, -29, -45, -61, 26, 84, -77, 76, 30).map(_.toByte)
val Addresses = Set(a1, a2, a3, a4, Address.Broadcast, Address.Null)
val a1Dashed =
new Address("A51B7447-5EE622C3-C924DB14-7668F85E-024CA0B4-4CA146B5-E3D3C31A-54B34C1E")
}
@ -35,4 +38,8 @@ class AddressTest extends AndroidTestCase {
assertEquals(a1Binary.deep, a1.bytes.deep)
}
def testDashes(): Unit = {
assertEquals(a1, a1Dashed)
}
}

View file

@ -6,6 +6,11 @@ object Address {
val Length = 32
/**
* Number of characters between each pair of dashes in [[Address.toString]].
*/
val GroupLength = 8
// 32 bytes, all ones
// 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
val Broadcast = new Address("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
@ -25,8 +30,15 @@ case class Address(bytes: Array[Byte]) {
require(bytes.length == Address.Length, "Invalid address length (was " + bytes.length + ")")
/**
* Parses address from string. Dash characters ("-") are ignored.
*/
def this(hex: String) {
this(hex.sliding(2, 2).map(Integer.parseInt(_, 16).toByte).toArray)
this(hex
.replace("-", "")
.sliding(2, 2)
.map(Integer.parseInt(_, 16).toByte)
.toArray)
}
override def hashCode = util.Arrays.hashCode(bytes)
@ -36,6 +48,14 @@ case class Address(bytes: Array[Byte]) {
case _ => false
}
override def toString = bytes.map("%02X".format(_)).mkString
/**
* Converts address to a string, with groups seperated by dashes.
*/
override def toString =
bytes
.map("%02X".format(_))
.mkString
.grouped(Address.GroupLength)
.reduce(_ + "-" + _)
}