Last active
July 9, 2016 16:28
-
-
Save alphaKAI/9f11414b862dacf5fef4227723b904de to your computer and use it in GitHub Desktop.
An one-linre Base64 Decoder in D. Encoder : https://gist.github.com/alphaKAI/78b9c7ad31195a702dde
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
import std.algorithm, | |
std.string, | |
std.ascii, | |
std.range, | |
std.conv; | |
import std.stdio; | |
R delegate(Args) Z(R, Args...)(R delegate(R delegate(Args), Args) f){ | |
return (Args args) => f(Z(f), args); | |
} | |
string encode(T)(T data) { | |
return | |
(convb => | |
(table => | |
(converted => | |
(binaries => | |
(bLen => | |
(prepared => | |
(pLen => | |
(quotients => | |
pLen % 4 == 0 | |
? quotients | |
: quotients ~ (remainds => | |
remainds.map!(remain => | |
table[remain] | |
).array.join ~ repeat("=", 4 - (pLen % 4)).join | |
)(prepared[($ - (pLen % 4))..$]) | |
)( | |
(pLen / 4).iota.map!(i => | |
(j => | |
4.iota.map!(k => | |
table[prepared[j + k]] | |
).array.join | |
)(i * 4) | |
).array.join | |
) | |
)(prepared.length) | |
)( | |
(quotients => | |
bLen % 6 == 0 | |
? quotients | |
: quotients ~ (remainds => | |
remainds ~ repeat("0", 6 - remainds.length).join | |
)(binaries[($ - (bLen % 6))..$]) | |
)((bLen / 6).iota.map!(i => binaries[(i * 6)..((i + 1) * 6)]).array) | |
) | |
)(binaries.length) | |
)(converted.join) | |
)(data.map!(i => | |
(e => | |
e.length == 8 | |
? e | |
: repeat("0", 8 - e.length).join ~ e | |
)(convb(i, 2))).array | |
) | |
)((charset => | |
assocArray( | |
zip( | |
charset.length.iota.map!(i => | |
(e => | |
e.length == 6 | |
? e | |
: repeat("0", 6 - e.length).join ~ e | |
)(convb(i, 2))), | |
charset)) | |
)((uppercase ~ lowercase ~ digits ~ "+/").split(string.init)) | |
) | |
)((ulong N, int base) => | |
(convbM => | |
convbM(N, N, [], base) | |
)(Z((string delegate(ulong, ulong, ulong[], int base) convbM, ulong N, ulong tmp, ulong[] stack, int base) => | |
tmp ? convbM(N, tmp / base, stack ~ (tmp % base), base) : stack.reverse.map!(e => e.to!string).join))); | |
} | |
void main() { | |
string base = "ABCDEFG", | |
encoded = encode(base); | |
writeln(base == decode(encoded)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment