apen6.okkam-http_2.12.0.1.3.source-code.Codecs.scala Maven / Gradle / Ivy
package okkam.http
import java.nio.charset.StandardCharsets.{UTF_8 => `UTF-8`}
import org.apache.commons.codec.net.URLCodec
/**
* Provides URI / IRI percent-encoding methods such that
*
* - Characters in "unreserved" are not percent-encoded
* - Characters out of "unreserved" are percent-encoded
*
* The term "unreseved" refers to the character set of its name defined in RFC3986.
*
* @see RFC3986 and RFC3987
*/
object ParameterCodec {
type KeyValuePair = (String, String)
lazy val urlCodec = new URLCodec()
final val PreservedChars = raw"[\w\-\.\~]"
final val EscapedChars = raw"[^\w\-\.\~]"
def isUnreserved(b: Int): Boolean =
(b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') ||
b == '-' || b == '.' || b == '_' || b == '~'
val table: IndexedSeq[String] = 0 to 255 map { b =>
if (isUnreserved(b))
b.toChar.toString
else
"%%%02X".format(b)
}
def encodeString(s: String, otherPrservedChars: Seq[Char] = Nil): String = {
val atbl: IndexedSeq[String] =
if (otherPrservedChars.isEmpty)
table
else {
val ar = new Array[String](256)
table.copyToArray(ar)
otherPrservedChars foreach {
c => ar(c.toInt) = c.toString
}
ar
}
val sb = new StringBuilder
s.getBytes(`UTF-8`) foreach { b =>
sb ++= atbl(if (b < 0) b + 256 else b)
}
sb.toString
}
def decodeString(s: String): String = urlCodec.decode(s)
def renderKeyValue(kv: (String, String), quote: String = ""): String
= encodeString(kv._1) + "=" + quote + encodeString(kv._2) + quote
def renderKeyValues(params: Seq[KeyValuePair], quote: String = ""): Seq[String] =
params.map { renderKeyValue(_, quote) }
def renderParams(params: Seq[KeyValuePair], delim: String = "&", quote: String = ""): String
= renderKeyValues(params, quote).mkString(delim)
}