Four Bit Enum Abstract

Dear community,

it’s time for a stupid idea again.

I love @:enum abstacts. But what I do not appriciate is the concept of having very often a small list of enums (let’s say four) that is represented with a 32-bit/ 64 integer.

I then have experimented with an @:enum abstract that has an underlying type of a vector storing booleans.

The vectors are set up to store only two booleans, so we have a four-bit-constellation.

This construction works as you can see here:

https://try.haxe.org/#984D0

But I ask myself, if there actually is an advantage of memory usage and/ or performance or if the advantages are eaten up by the overhead.

Or can the same purpose could be achieved easier with the class Bytes?

What do you think?

Kind regards
Arnim

1 Like

But what I do not appriciate is the concept of having very often a small list of enums (let’s say four) that is represented with a 32-bit/ 64 integer.

Why not? Maybe I’m missing the point, but what is the advantage over just this:

class Test {
    static function main() {
        var fourBitEnumAbstract:FourBitEnumAbstract = FourBitEnumAbstract.blackBlue;
        trace( fourBitEnumAbstract );
    }
}

@:enum abstract FourBitEnumAbstract ( Int ) {
    var redBlue = 1;
    var blackBlue = 2;
    var blackBlack = 3;
    var redBlack = 4;

    @:to public inline function toString() : String {
        return switch (cast this:FourBitEnumAbstract) {
            case redBlue: "redBlue";
            case blackBlue: "blackBlue";
            case blackBlack: "blackBlack";
            case redBlack: "redBlack";
        }
    }
}

I’m not sure you really want to go into sub-byte sizes, because then alignment goes out of whack, potentially adding CPU cycles to retrieve memory.

What you can do however is something like this:

typedef Byte = 
  #if cpp
    cpp.Int8;
  #elseif java
    java.Int8;
  #elseif cs
    cs.Int8;
  #else
    Int;//all other platforms actually don't have small int types
  #end

@:enum abstract Blargh(Byte) {
  // put stuff here
}
1 Like

Thank you guys for your replies.

That helps me a lot.