Skip to content

Instantly share code, notes, and snippets.

@benjaminjackman
Created April 29, 2014 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjaminjackman/11397610 to your computer and use it in GitHub Desktop.
Save benjaminjackman/11397610 to your computer and use it in GitHub Desktop.
import scala.scalajs.js
object UTF8Impl {
private val global = js.Dynamic.global
def toBytes(s: String): Array[Byte] = {
val out = new js.Array[js.Number]()
var n = 0
val str: js.String = s
while (n < str.length) {
val c = str.charCodeAt(n)
if (c < 128) {
out.push(c)
} else if (c < 2048) {
out.push((c >> 6) | 192)
out.push((c & 63) | 128)
} else {
out.push((c >> 12) | 224)
out.push(((c >> 6) & 63) | 128)
out.push((c & 63) | 128)
}
n += 1
}
def toByte(x: js.Number): Byte = {
val y: Double = x
y.toByte
}
out.iterator.map(toByte).toArray
}
def fromBytes(bytes: Array[Byte]): String = {
val out = new js.Array[js.String]()
var pos = 0
while (pos < bytes.length) {
val c1 = bytes(pos).toInt & 0xFF
pos += 1
if (c1 < 128) {
out.push(global.String.fromCharCode(c1).asInstanceOf[js.String])
} else if (c1 > 191 && c1 < 224) {
val c2 = bytes(pos)
pos += 1
out.push(global.String.fromCharCode((c1 & 31) << 6 | c2 & 63).asInstanceOf[js.String])
} else {
val c2 = bytes(pos)
pos += 1
val c3 = bytes(pos)
pos += 1
out.push(global.String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63).asInstanceOf[js.String])
}
}
out.join("").toString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment