diff --git a/eclair-core/src/main/scala/fr/acinq/eclair/UInt64.scala b/eclair-core/src/main/scala/fr/acinq/eclair/UInt64.scala index 97a8293d65..d709124d8e 100644 --- a/eclair-core/src/main/scala/fr/acinq/eclair/UInt64.scala +++ b/eclair-core/src/main/scala/fr/acinq/eclair/UInt64.scala @@ -18,26 +18,18 @@ package fr.acinq.eclair import com.google.common.primitives.UnsignedLongs import scodec.bits.ByteVector -import scodec.bits._ +import scodec.bits.HexStringSyntax case class UInt64(private val underlying: Long) extends Ordered[UInt64] { override def compare(o: UInt64): Int = UnsignedLongs.compare(underlying, o.underlying) - def toByteVector: ByteVector = this match { - case x if x <= UInt64(255) => ByteVector.fromLong(underlying, size = 1) - case x if x <= UInt64(65535) => ByteVector.fromLong(underlying, size = 2) - case x if x <= UInt64(16777215) => ByteVector.fromLong(underlying, size = 3) - case x if x <= UInt64(4294967295L) => ByteVector.fromLong(underlying, size = 4) - case x if x <= UInt64(1099511627775L) => ByteVector.fromLong(underlying, size = 5) - case x if x <= UInt64(281474976710655L) => ByteVector.fromLong(underlying, size = 6) - case x if x <= UInt64(72057594037927935L) => ByteVector.fromLong(underlying, size = 7) - case _ => ByteVector.fromLong(underlying, size = 8) + def toByteVector: ByteVector = underlying match { + case 0 => hex"00" + case _ => ByteVector.fromLong(underlying).dropWhile(_ == 0) } - def toBigInt: BigInt = BigInt(toString) - - def toLong: Long = underlying + def toBigInt: BigInt = BigInt(signum = 1, toByteVector.toArray) override def toString: String = UnsignedLongs.toString(underlying, 10) } diff --git a/eclair-core/src/test/scala/fr/acinq/eclair/UInt64Spec.scala b/eclair-core/src/test/scala/fr/acinq/eclair/UInt64Spec.scala index d1d9d77d36..b6258be587 100644 --- a/eclair-core/src/test/scala/fr/acinq/eclair/UInt64Spec.scala +++ b/eclair-core/src/test/scala/fr/acinq/eclair/UInt64Spec.scala @@ -27,11 +27,23 @@ class UInt64Spec extends FunSuite { val b = UInt64(hex"0xfffffffffffffffe") val c = UInt64(42) val z = UInt64(0) + val l = UInt64(Long.MaxValue) + val l1 = UInt64(hex"8000000000000000") // Long.MaxValue + 1 + assert(a > b) + assert(a.toBigInt > b.toBigInt) assert(b < a) - assert(z < a && z < b && z < c) + assert(b.toBigInt < a.toBigInt) + assert(l.toBigInt < l1.toBigInt) + assert(z < a && z < b && z < c && z < l && c < l && l < l1 && l < b && l < a) assert(a == a) assert(a == UInt64.MaxValue) + assert(l.toByteVector == hex"7fffffffffffffff") + assert(l.toString == Long.MaxValue.toString) + assert(l.toBigInt == BigInt(Long.MaxValue)) + assert(l1.toByteVector == hex"8000000000000000") + assert(l1.toString == "9223372036854775808") + assert(l1.toBigInt == BigInt("9223372036854775808")) assert(a.toByteVector === hex"0xffffffffffffffff") assert(a.toString === "18446744073709551615") assert(b.toByteVector === hex"0xfffffffffffffffe")