zserio icon indicating copy to clipboard operation
zserio copied to clipboard

Remove length member for arrays in generated types

Open MikeLankamp-TomTom opened this issue 2 years ago • 1 comments

A type like

struct ArrayExample
{
    int16   numItems;
    Element list[numItems];
};

will result in getters and setters on the C++ type for int16_t numItems and std::vector list. The former is unnecessary since std::vector already holds a size and thus duplicates information. In general, this leads to a confusing generated type, especially when constructing them, since numItems has to be explicitly set after filling list.

As I see it, the generator could recognize this and remove numItems as a member, deducing it from the length of the vector when writing. In case multiple arrays are defined by the same count, the write method has to validate that the vectors are of the same length.

MikeLankamp-TomTom avatar Dec 14 '23 19:12 MikeLankamp-TomTom

Thanks for an idea. Yes, this specific use case can be detected and improved.

However, only this simple one. Consider the following schema:

struct ArrayExample
{
    varsize size1;
    varsize size2;
    Element list[size1 + size2];
};

In this case, we are not able to deduce size1 and size2 from list array size.

So, if we are talking about this simple case only, zserio language offers a special construct for this: auto arrays together with lengthof operator.

Example:

struct ArrayExample
{
    int32 array1[];
    int32 array2[lengthof(array1)];
};

This will avoid the generation of unnecessary getter and setter for array size.

In general, if language offers better construct for this, I am not sure if removal of unnecessary getter and setter for numItems will be intituive. It could happen that somebody will be suprised by such optimization only for one specific use case. Or it could happen that someone will find such getter and setter usefull.

One idea could be for example to implement warning that this simple construct is not optimal for most use cases and can be replaced by auto arrays.

mikir avatar Dec 15 '23 10:12 mikir