Skip to content

Instantly share code, notes, and snippets.

@kushti
Created February 15, 2018 07:37
Show Gist options
  • Save kushti/4c827945ff49538f8bc40bdd5d5ee4f1 to your computer and use it in GitHub Desktop.
Save kushti/4c827945ff49538f8bc40bdd5d5ee4f1 to your computer and use it in GitHub Desktop.
object ConcreteCollection extends App {
import scala.reflect.runtime.universe.{typeTag, TypeTag}
def restoreElement[S <: SType](body: Array[Byte], idx: Int): (Value[_ <: SType], TypeTag[_ <: SType]) = {
if (body(idx) == 10) (IntConstant(body(idx + 1)), typeTag[SInt.type])
else if (body(idx) == 11) BooleanConstant.fromBoolean(body(idx + 1) != 0) -> typeTag[SBoolean.type] else ???
}
def normalize[S <: SType](elems: (Value[_ <: SType], TypeTag[_ <: SType])*)(t: TypeTag[S]): IndexedSeq[Value[S]] = {
require(elems.map(_._2).forall(_ == t))
elems.map(_._1).map(v => v.asInstanceOf[Value[S]]).toIndexedSeq
}
def decodeCollection(bs: Array[Byte]): Try[ConcreteCollection[_]] = Try {
bs.head match {
case b: Byte if b == 1 =>
val bt = bs.tail
val elemsCount = bt.head
val body = bt.tail
val elems = (0 until elemsCount).map(i => restoreElement(body, i * 2))
val seq = normalize(elems: _*)(elems.head._2)
ConcreteCollection(seq)
case _ => ???
}
}
assert(decodeCollection(Array[Byte](0, 2, 10, 5, 11, 7)).isFailure)
assert(decodeCollection(Array[Byte](1, 2, 10, 5, 11, 7)).isFailure)
assert(decodeCollection(Array[Byte](1, 2, 10, 5, 10, 7)).get == ConcreteCollection(IndexedSeq(IntConstant(5), IntConstant(7))))
assert(decodeCollection(Array[Byte](1, 2, 10, 5, 10, 7)).get != ConcreteCollection(IndexedSeq(IntConstant(5), IntConstant(8))))
assert(decodeCollection(Array[Byte](1, 2, 11, 5, 10, 7)).isFailure)
assert(decodeCollection(Array[Byte](1, 2, 11, 5, 11, 7)).get == ConcreteCollection(IndexedSeq(TrueLeaf, TrueLeaf)))
assert(decodeCollection(Array[Byte](1, 2, 11, 5, 11, 0)).get == ConcreteCollection(IndexedSeq(TrueLeaf, FalseLeaf)))
assert(decodeCollection(Array[Byte](1, 3, 11, 5, 11, 0, 10, 1)).isFailure)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment