FastBinaryEncoding icon indicating copy to clipboard operation
FastBinaryEncoding copied to clipboard

Inefficient output stream operator implementation

Open herolover opened this issue 3 years ago • 4 comments

Now output stream operator includes a set of if statements, which might be inefficient if there are many different enum values. It could be much better if it's replaced by switch statement.

Also it would be very useful to have a separate free function to get const char * of enum. Output stream operator could use the function.

herolover avatar Dec 14 '20 10:12 herolover

FBE protocol spec allows to declare enums with duplicate values:

// Byte enum declaration
enum EnumByte : byte
{
    ENUM_VALUE_0;
    ENUM_VALUE_1 = 0;
    ENUM_VALUE_2;
    ENUM_VALUE_3 = 254;
    ENUM_VALUE_4;
    ENUM_VALUE_5 = ENUM_VALUE_3;
}

In this case switch statement will generate: error C2196: case value 'enums::EnumByte::ENUM_VALUE_0' already used error C2196: case value 'enums::EnumByte::ENUM_VALUE_3' already used

chronoxor avatar Dec 15 '20 00:12 chronoxor

Enum value string is rarely used outside struct's dumps in logs. So << operator is more suitable. In case you need string equivalent try:

std::string to_string(EnumByte value) const { std::stringstream ss; ss << value; return ss.str(); }

chronoxor avatar Dec 15 '20 00:12 chronoxor

FBE protocol spec allows to declare enums with duplicate values:

// Byte enum declaration
enum EnumByte : byte
{
    ENUM_VALUE_0;
    ENUM_VALUE_1 = 0;
    ENUM_VALUE_2;
    ENUM_VALUE_3 = 254;
    ENUM_VALUE_4;
    ENUM_VALUE_5 = ENUM_VALUE_3;
}

In this case switch statement will generate: error C2196: case value 'enums::EnumByte::ENUM_VALUE_0' already used error C2196: case value 'enums::EnumByte::ENUM_VALUE_3' already used

So it means only an alias. And it could be handled, couldn't it? Ok, I just wanted to point it out.

Enum value string is rarely used outside struct's dumps in logs. So << operator is more suitable. In case you need string equivalent try:

std::string to_string(EnumByte value) const { std::stringstream ss; ss << value; return ss.str(); }

Yes, such cases are rare, but they are. This way(using std::stringstream) has a huge overhead(comparing to getting const char * from switch statement).

herolover avatar Dec 15 '20 06:12 herolover

Yes, such cases are rare, but they are. This way(using std::stringstream) has a huge overhead(comparing to getting const char * from switch statement).

Since this is a C++17 library, an std::string_view would be a more appropriate return type.

bitbugprime avatar Feb 08 '21 09:02 bitbugprime