jweinst1
5/2/2017 - 11:30 PM

list scala serialization

list scala serialization

//serialize Scala List to binary format

import java.nio.ByteBuffer

object main  {
  def main():Unit = {
    println(Lyte.toBytes(List(1, 2, 4, 6, 7)).mkString(","));
  }
}

//functions to turn scala List to array of bytes
object Lyte {
  
  
  def toBytes(lst:Any):Array[Byte] = lst match {
    case tlst:List[Int] => ints(tlst);
  }
  
  def ints(lst:List[Int]):Array[Byte] = {
    val bytes = ByteBuffer.allocate(2 +lst.length * 4);
    var ref = lst;
    bytes.put((44).toByte);
    //0 is for integers
    bytes.put((0).toByte);
    while(ref != Nil) {
      bytes.putInt(ref.head);
      ref = ref.tail;
    }
    bytes.array();
  }
}

//methods to revert bytes to scalaList
object LyteToList {
  def revert(blist:Array[Byte]):List[Any] = {
    var lst:List[Any] = List();
    val bytes = ByteBuffer.wrap(blist);
    if(validate(bytes.get())) {
      val stype = bytes.get();
      stype match {
        case (0).toByte => 
      }
    }
    else println("Invalid Byte Order");
  }
  
  private def validate(b:Byte) b == (44).toByte;
}

main.main();