I want to implement something like a Vigenère cipher, and I chose to use D's associative arrays. I use the
struct Codes
{
int[char] enc;
char[int] dec;
}
and then i populate the AA's with
foreach(immutable char c; letters ~ whitespace ~ digits)
{
codes.enc[c] = codes.enc.length;
codes.dec[codes.enc.length] = c;
}
It works as it is suppose to work in my [en/de]crypting functions, but I have two questions:
(I'm using the dmd v2.053 compiler if that matter whatsoever this days).
the dec can be a normal array (it's equal to letters ~ whitespace ~ digits
btw)
in enc you can also use a normal array if you only allow ASCII as characters (with length 255 and casting c to int for the index)
edit
you can create a mixin string from the letters ~ whitespace ~ digits
string like so
string createSwitch(string seq,string inp){
string out = "switch("~inp~"){";
int i=0;
foreach(ch;seq){
out~="case "~ch~":return "~i";";
}
out~="default: return -1;";
return out;
}
which you can then use as
int intFromChar(char ch){
mixin(createSwitch(letters ~ whitespace ~ digits,"ch"));
}