Fixing bug in creating CompactSizeUInt from num, also extending Factory from CompactSizeUInt factory object

This commit is contained in:
Chris Stewart 2016-06-30 09:20:42 -05:00
parent 9b57cdef0b
commit fe352c8a59
2 changed files with 13 additions and 7 deletions

View File

@ -3,7 +3,7 @@ package org.bitcoins.core.protocol
import org.bitcoins.core.number.UInt32
import org.bitcoins.core.protocol.script.{ScriptPubKey, ScriptSignature}
import org.bitcoins.core.script.constant.ScriptNumberUtil
import org.bitcoins.core.util.BitcoinSUtil
import org.bitcoins.core.util.{BitcoinSUtil, Factory}
/**
* Created by chris on 7/14/15.
@ -32,15 +32,15 @@ trait CompactSizeUInt {
case 5 => "fe" + ScriptNumberUtil.longToHex(num)
case _ => "ff" + ScriptNumberUtil.longToHex(num)
}
}
object CompactSizeUInt {
object CompactSizeUInt extends Factory[CompactSizeUInt] {
private sealed case class CompactSizeUIntImpl(num : Long, size : Long) extends CompactSizeUInt
override def fromBytes(bytes: Seq[Byte]): CompactSizeUInt = {
parseCompactSizeUInt(bytes)
}
def apply(num : Long, size : Long) : CompactSizeUInt = {
CompactSizeUIntImpl(num,size)
}
@ -52,7 +52,7 @@ object CompactSizeUInt {
}
private def calcSizeForNum(num : Long) : Int = {
if (num <= 255) 1
if (num <= 252) 1
// can be represented with two bytes
else if (num <= 65535) 3
//can be represented with 4 bytes

View File

@ -19,6 +19,12 @@ class CompactSizeUIntTest extends FlatSpec with MustMatchers {
varInt.hex must be ("00")
}
it must "serialize a compact size uint representing 255" in {
val compactSizeUInt = CompactSizeUInt(255)
compactSizeUInt must be (CompactSizeUInt(255,3))
compactSizeUInt.hex must be ("fdff00")
}
it must "calculate the varint for the following hex string" in {
CompactSizeUInt.calculateCompactSizeUInt("00") must be (CompactSizeUInt(1,1))