Created
January 14, 2013 13:44
-
-
Save pyalot/4530137 to your computer and use it in GitHub Desktop.
Coffeescript efficient base64 decode to typed array.
This file contains 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
decodingTable = new Uint8Array(256) | |
for c, i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' | |
decodingTable[c.charCodeAt(0)] = i | |
base64decode = (string) -> | |
last = string[string.length-2...string.length] | |
if last == '==' | |
remainder = 2 | |
else if last[1] == '=' | |
remainder = 1 | |
else | |
remainder = 0 | |
filledLength = string.length - string.length % 4 | |
byteLength = (filledLength/4)*3 + remainder | |
result = new Uint8Array(byteLength) | |
for i in [0...filledLength] by 4 | |
c1 = decodingTable[string.charCodeAt(i)] | |
c2 = decodingTable[string.charCodeAt(i+1)] | |
c3 = decodingTable[string.charCodeAt(i+2)] | |
c4 = decodingTable[string.charCodeAt(i+3)] | |
idx = (i/4)*3 | |
result[idx] = (c1<<2) + (c2>>4) | |
result[idx+1] = ((c2&15)<<4) + (c3>>2) | |
result[idx+2] = ((c3&3)<<6) + c4 | |
idx = (i/4)*3 | |
if remainder > 0 | |
c1 = decodingTable[string.charCodeAt(i)] | |
c2 = decodingTable[string.charCodeAt(i+1)] | |
result[idx] = (c1<<2) + (c2>>4) | |
if remainder > 1 | |
c3 = decodingTable[string.charCodeAt(i+2)] | |
result[idx+1] = ((c2&15)<<4) + (c3>>2) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment