Created
September 27, 2011 09:28
-
-
Save MartinNowak/1244676 to your computer and use it in GitHub Desktop.
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
import std.ascii, std.algorithm, std.conv, std.range, std.stdio, std.string; | |
ulong fromHexDigit(dchar c) { | |
if (!isHexDigit(c)) | |
throw new Exception("Illegal char in hex number: "~to!string(c)); | |
return c <= '9' ? (c & 0xF) : 9 + (c & 0xF); | |
} | |
ulong fromBinDigit(dchar c) { | |
if (c == '0') return 0; | |
else if (c == '1') return 1; | |
throw new Exception("Illegal char in binary number: " ~ to!string(c)); | |
} | |
long delegate(string) getParseFun(string name) | |
{ | |
switch (name) | |
{ | |
case "int": | |
return (string sint) { | |
return to!long(sint); | |
}; | |
case "hex": | |
return (string shex) { | |
shex = shex.toLower(); | |
skipOver(shex, "0x"); | |
return reduce!("(a << 4) + b")(0UL, map!fromHexDigit(shex)); | |
}; | |
case "bin": | |
return (string sbin) { | |
sbin = sbin.toLower(); | |
skipOver(sbin, "0b"); | |
return reduce!("(a << 1) + b")(0UL, map!fromBinDigit(sbin)); | |
}; | |
default: | |
assert(0, "unknown conv source " ~ name); | |
} | |
} | |
string delegate(long) getPrintFun(string name) | |
{ | |
switch (name) | |
{ | |
case "int": | |
return (long val) { | |
return std.string.format("%.1d", val); | |
}; | |
case "hex": | |
return (long val) { | |
return std.string.format("0x%.1x", val); | |
}; | |
case "bin": | |
return (long val) { | |
return std.string.format("0b%.1b", val); | |
}; | |
default: | |
assert(0, "unknown conv target " ~ name); | |
} | |
} | |
string delegate(string) getConvFun(string execName) { | |
auto r = findSplit(execName, "2"); | |
if (r[1].empty) throw new Exception("Unknown conv function: " ~ execName); | |
auto parse = getParseFun(r[0]); | |
auto conv = getPrintFun(r[2]); | |
return (string val) { return conv(parse(val)); }; | |
} | |
int main(string[] args) { | |
if (!args.length) | |
return 1; | |
auto mode = args[0]; | |
mode.skipOver("./"); | |
auto conv = getConvFun(mode); | |
if (args.length > 1) { | |
if (args[1] == "-") { | |
char[] buf; | |
while (stdin.readln(buf)) | |
writeln(conv(chomp(buf.idup))); | |
} else { | |
foreach(ref elem; map!(conv)(args[1 .. $])) { | |
writeln(elem); | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment