sensorial-systems / ligen

Apache License 2.0
20 stars 3 forks source link

Enum to Tagged Union Marshalling #4

Open notdanilo opened 3 years ago

notdanilo commented 3 years ago

How can we express the following code in C?

pub enum Error {
  GeneralFailure,
  Other(String)
}
notdanilo commented 3 years ago

Proposal

enum ErrorVariant = { GeneralFailure, Other };

union ErrorObject {
  u8 GeneralFailure;
  char* Other;
}

struct Error {
  enum ErrorVariant variant;
  union ErrorObject object;
}
notdanilo commented 3 years ago

https://doc.rust-lang.org/reference/items/unions.html has this example:

#![allow(unused)]
fn main() {
#[repr(u32)]
enum Tag { I, F }

#[repr(C)]
union U {
    i: i32,
    f: f32,
}

#[repr(C)]
struct Value {
    tag: Tag,
    u: U,
}

fn is_zero(v: Value) -> bool {
    unsafe {
        match v {
            Value { tag: Tag::I, u: U { i: 0 } } => true,
            Value { tag: Tag::F, u: U { f: num } } if num == 0.0 => true,
            _ => false,
        }
    }
}
}
notdanilo commented 3 years ago

Work on this file: src/marshalling/enumeration.rs

notdanilo commented 3 years ago

cargo test -- --nocapture to get prints from tests

notdanilo commented 3 years ago

First step:

Create an enumeration with N items:

pub enum Enumeration {
   A,
   B,
   C
}

Index them by 0, 1 and 2. Get the indexed value from C.