Skip to content

Instantly share code, notes, and snippets.

@jcracknell
Last active December 22, 2015 05:49
Show Gist options
  • Save jcracknell/6426944 to your computer and use it in GitHub Desktop.
Save jcracknell/6426944 to your computer and use it in GitHub Desktop.
LiteralEncoding.scala
object LiteralEncoding {
private val Hex = "0123456789abcdef".toArray
private val StringEscapes = {
val escapes = Map(
'\b' -> 'b', // backspace
'\t' -> 't', // tab
'\n' -> 'n', // linefeed
'\f' -> 'f', // formfeed
'\r' -> 'r', // carriage return
'\\' -> '\\', // backslash
'"' -> '"'
)
(Array.fill('\\'.toInt + 1)('\u0000') /: escapes) { (a, e) => a(e._1) = e._2; a }
}
def encode(str: String): String =
encode(str, new StringBuilder(str.length + 2)).toString
def encode(str: String, sb: StringBuilder): StringBuilder = {
if(null == str) return sb.append("null");
sb.append('"')
for(c <- str) {
if(c <= StringEscapes.length && '\u0000' != StringEscapes(c))
sb.append('\\').append(StringEscapes(c))
else if('~' >= c && c >= ' ')
sb.append(c)
else {
sb.append('\\').append('u')
.append(Hex(c >>> 12 & 0xF))
.append(Hex(c >>> 8 & 0xF))
.append(Hex(c >>> 4 & 0xF))
.append(Hex(c & 0xF))
}
}
sb.append('"')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment