Help language development. Donate to The Perl Foundation

Trait::Enum cpan:CTILMES last updated on 2020-05-11

Trait::Enum - Raku 'is enum' trait for enumerated types in CStruct classes


    use Trait::Enum;

    enum FooType <A B C>;

    class Foo is repr('CStruct') {
        has int32 $.enum-foo-type is enum(FooType);
        has int32 $.enum-foo-writeable is rw is enum(FooType);

    my $foo = => 2, enum-foo-writeable => 1);

    say $;             # C        -- Returns enumeration value
    say ~$;            # 'C'      -- which stringifies
    say +$;            # 2        -- and numifies

    say $;        # B
    say +$;       # 1

    $;         # Can write a enumeration value
    $;         # Or an Int
    $'C');       # Or a Str

    $;        # Ok to write a bad integer
    say $;        # FooType, undefined enumeration

    $'bad');     # Bad string throws exception


This is a temporary, experimental trait mainly because Raku Native `CStruct` classes don't currently allow enumerated types in them. Once they do, this module will be retired. In the mean time, it makes it very easy to map enumerations into CStruct structures making them more friendly to interact with from Raku.

The trait can only be added on attributes named with the prefix 'enum-'. It adds an additional accessor method without that prefix. (You can still use the 'enum-' accessor methods with the original type.) The new accessor method returns the specified enum.

Naturally this trait must be used only with integer fields (int32, int16, etc.)

If the attribute is also 'rw', three additional multi methods for writing to to the attribute either an Int, a Str, or an actual enumerated value.


This work is subject to the Artistic License 2.0.