Skip to content

Commit

Permalink
Merge pull request #133 from lJoublanc/series/1.10.x
Browse files Browse the repository at this point in the history
Pad-left on pbcd codec (take 2). Fixes #126.
  • Loading branch information
mpilquist committed Jan 21, 2019
2 parents 6ddb595 + 9469a46 commit f247b4c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
10 changes: 9 additions & 1 deletion shared/src/main/scala/scodec/codecs/package.scala
Expand Up @@ -467,7 +467,15 @@ package object codecs {
* @param nibbles number of nibbles (4-bit chunks)
* @group numbers
*/
def pbcd(nibbles: Int): Codec[Long] = fixedSizeBits(nibbles.toLong*4, vpbcd)
def pbcd(nibbles: Int): Codec[Long] = new Codec[Long] {
private def width: Long = nibbles.toLong * 4L
def decode(bits: BitVector): Attempt[DecodeResult[Long]] =
bits.consumeThen(width)(e => Attempt failure Err(e),
(bits,rem) => vpbcd decodeValue bits map (a => DecodeResult(a,rem))
)
def encode(l : Long): Attempt[BitVector] = vpbcd encode l map (_ padLeft width)
def sizeBound = SizeBound exact width
}

/**
* Codec for n-nibble packed decimal (BCD) integers that are represented with `Long`.
Expand Down
Expand Up @@ -18,6 +18,12 @@ class PackedDecimalCodecTest extends CodecSuite {
pbcd(6).decode(hex"010323".bits) should be (Attempt.successful(DecodeResult(10323L, BitVector.empty)))
}

"pad left when encoding (#126)" in {
pbcd(3).encode(0) shouldEqual Attempt.successful(bin"0000 0000 0000")
pbcd(3).encode(1) shouldEqual Attempt.successful(bin"0000 0000 0001")
pbcd(3).encode(79) shouldEqual Attempt.successful(bin"0000 0111 1001")
pbcd(3).encode(999) shouldEqual Attempt.successful(bin"1001 1001 1001")
}
}

"the lpbcd codec" should {
Expand Down

0 comments on commit f247b4c

Please sign in to comment.