djinni icon indicating copy to clipboard operation
djinni copied to clipboard

Support stringizing enumerations in C++ layer for describing mapped enumeration

Open ringyee opened this issue 8 years ago • 1 comments

I searched issues but I didn't see anything about stringizing enumeration while generating native C++ sources. In my case, I need to get the enumerations' description to show to upper layer. I'm not sure that whether there is the same demand for others?
To achieving this, one way is to define the enumeration strings manually, the second way is to stringize enumerations automatically in djinni. In my opinion, the second way is preferred be cause: it can get the string mapped to enum easily, and also, if djinni plans to support metaprogramming, it will be helpful.

For example, defining enum In djinni file:

Version = enum {
    v_1_0;
    v_2_0;
    v_3_0;
}

it will produced C++ hpp:

enum class Version : int {
    V_1_0,
    V_2_0,
    V_3_0,
};

If I want to return the description of certain enumeration, it needs to define a enumeration string table to achieve this:

static const char *VersionStrs[] = {
    "V_1_0",
    "V_2_0",
    "V_3_0",
};

const char *toString(Version v) {
    return VersionStrs[v];
}

But the works above are bored and horrible if there are so many enumerations, so I suggest to auto generating the codes above into enum hpp files, the expected new hpp file for enum: expected new produced C++ hpp for enum maybe look like:

enum class Version : int {
    V_1_0,
    V_2_0,
    V_3_0,
};

struct VersionHelper {
    static const char *toString(Version v) {
        const static char *__enumStrings[] = {
            "Version::V_1_0",
            "Version::V_2_0",
            "Version::V_3_0",
        };

        return (((int)v) >= (int)(sizeof(__enumStrings)/sizeof(__enumStrings[0])) || ((int)v) < 0) ?
            "INVALID_VALUE" : __enumStrings[(int)v];
    };
};

So is it possible to stringize enumerations automatically in djinn or support it with a djinni compiling option?

thanks~

ringyee avatar Sep 11 '16 13:09 ringyee

made pull-request which is solving this issue https://github.com/dropbox/djinni/pull/452

ctin avatar Oct 07 '19 15:10 ctin