Created
July 30, 2010 19:58
-
-
Save mccv/501216 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 com.twitter.jetty | |
object OAuthEncoder { | |
val ALPHA = Set((0x41 to 0x5A):_*) ++ Set((0x61 to 0x7A):_*) | |
val DIGIT = Set((0x30 to 0x39):_*) | |
val HYPHEN = Set(0x2D) | |
val PERIOD = Set(0x2E) | |
val UNDERSCORE = Set(0x5F) | |
val TILDE = Set(0x7E) | |
val UNENCODED = ALPHA ++ DIGIT ++ HYPHEN ++ PERIOD ++ UNDERSCORE ++ TILDE | |
val bytesToPercent = Map((0x00 to 0xFF).map { | |
b => | |
(b -> "%%%02X".format(b)) | |
}:_*) | |
def encode(s: String) = { | |
val rv = new StringBuffer() | |
val codePoints = s.codePointCount(0, s.length) | |
for (i <- 0 to (codePoints - 1)) { | |
val cp = s.codePointAt(i) | |
if (UNENCODED.contains(cp)) { | |
rv.append(cp.toChar) | |
} else { | |
// break the code point (which can be multiple bytes) | |
// into byte values for percent encoding | |
var remainingBytes = cp | |
while (remainingBytes != 0) { | |
var currByte = remainingBytes & 0xFF | |
remainingBytes = remainingBytes >> 8 | |
rv.append(bytesToPercent(currByte)) | |
} | |
} | |
} | |
rv | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment