Created
September 7, 2013 16:21
-
-
Save volgar1x/6476949 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.elves | |
import java.nio.charset.Charset | |
import java.nio.{CharBuffer, ByteBuffer} | |
import scala.annotation.tailrec | |
class DelimitedTextProtocol(inputDelimiter: String, outputDelimiter: String, charset: Charset) extends Protocol { | |
def encode(session: Session, o: Any): ByteBuffer = ByteBuffer wrap (o.toString + outputDelimiter).getBytes(charset) | |
def decode(session: Session, buf: ByteBuffer): List[Any] = { | |
def writeDown(remaining: String) { | |
session.bufferOption match { | |
case Some(buffer) => charset.newEncoder.encode(CharBuffer wrap remaining, buffer, true) | |
case None => session.buffer = charset encode remaining | |
} | |
} | |
@tailrec | |
def rec(elems: List[Any], input: String): List[Any] = { | |
val index = input.indexOf(inputDelimiter) | |
if (index < 0) { | |
if (!input.isEmpty) writeDown(input) | |
return elems :: Nil | |
} | |
rec(elems :+ input.substring(0, index), input.substring(index + inputDelimiter.length)) | |
} | |
val data: String = ??? | |
rec(List.empty, data) | |
} | |
} | |
object DelimitedTextProtocol { | |
def create(inputDelimiter: String, outputDelimiter: String, charset: Charset) | |
= new DelimitedTextProtocol(inputDelimiter, outputDelimiter, charset) | |
def apply(inputDelimiter: String, outputDelimiter: String)(implicit charset: Charset) | |
= create(inputDelimiter, outputDelimiter, charset) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment