开发者

Associative arrays, symetrical algorithm, CTFE

开发者 https://www.devze.com 2023-03-07 09:47 出处:网络
I want to implement something like a 开发者_Python百科Vigenère cipher, and I chose to use D\'s associative arrays.

I want to implement something like a 开发者_Python百科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:

  1. How can I, if I can, use just one AA. Or is it some other data structure that is as easy to use, more efficient or jut fits better with point 2.
  2. How am I suppose to use CTFE to generate some data structure at compile time and use the output at runtime.

(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"));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消