ISSOtm / rgbds-structs

A macro pack adding struct-like functionality to RGBDS
MIT License
21 stars 3 forks source link

Add `enum` macro #22

Open evie-calico opened 1 month ago

evie-calico commented 1 month ago

In the simplest case, this is equivalent to a list of constants defined using rb:

; These are the same
enum Foo
  case Bar
  case Baz
end_enum

rsreset
def Foo_Bar rb
def Foo_Baz rb

However, this macro can also be used to define a tagged union in which structs with different layouts can be stored in the same memory.

enum Result
  case Ok
    bytes 16, Message
  case Err
    words 1, Type
end_enum

This is equivalent to the following set of structures:

struct Result_Ok
  bytes 16, Message
end_struct

struct Result_Err
  words 1, Type
end_struct

struct Result
  bytes 1, Discriminant
  ; Clearly `Result_Ok` is much larger in this example, but this could be hard to keep track of in a large enum.
  bytes sizeof_Result_Ok, Content
end_struct

A second argument may be passed to enum to determine what storage to use for the Discriminant field. This is passed to the internal struct invocation, so any alias of new_field will work (bytes, words, longs). When absent, it defaults to bytes.