All Downloads are FREE. Search and download functionalities are using the official Maven repository.

scodec.codecs.ByteCodec.scala Maven / Gradle / Ivy

There is a newer version: 1.11.3
Show newest version
package scodec
package codecs

import scodec.bits.BitVector

private[codecs] final class ByteCodec(bits: Int, signed: Boolean) extends Codec[Byte] {

  require(bits > 0 && bits <= (if (signed) 8 else 7), "bits must be in range [1, 8] for signed and [1, 7] for unsigned")

  val MaxValue = ((1 << (if (signed) (bits - 1) else bits)) - 1).toByte
  val MinValue = (if (signed) -(1 << (bits - 1)) else 0).toByte

  private def description = s"$bits-bit ${if (signed) "signed" else "unsigned"} byte"

  override def sizeBound = SizeBound.exact(bits.toLong)

  override def encode(b: Byte) = {
    if (b > MaxValue) {
      Attempt.failure(Err(s"$b is greater than maximum value $MaxValue for $description"))
    } else if (b < MinValue) {
      Attempt.failure(Err(s"$b is less than minimum value $MinValue for $description"))
    } else {
      Attempt.successful(BitVector.fromByte(b, bits))
    }
  }

  override def decode(buffer: BitVector) =
    buffer.acquire(bits.toLong) match {
      case Left(e) => Attempt.failure(Err.insufficientBits(bits.toLong, buffer.size))
      case Right(b) => Attempt.successful(DecodeResult(b.toByte(signed), buffer.drop(bits.toLong)))
    }

  override def toString = description
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy