Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: create macros to generate impl From<T> on wrapper structs and enums #6

Open
ashneverdawn opened this issue Sep 12, 2024 · 0 comments

Comments

@ashneverdawn
Copy link
Contributor

ashneverdawn commented Sep 12, 2024

We often use this pattern to be able to use the wasmbingen macro and implement traits on foreign types from Warp:

#[wasm_bindgen]
pub struct WrapperType(ForeignType);

impl From<WrapperType> for ForeignType {
    fn from(value: WrapperType) -> Self {
        value.0
    }
}

impl From< ForeignType > for WrapperType {
    fn from(value: ForeignType) -> Self {
        Self(value)
    }
}

Another frequent similar case is where we wrap a foreign enum for the same reasons:

#[wasm_bindgen]
pub enum WrapperEnum {
    Variant1,
    Variant2,
    Variant3,
}

impl From<ForeignEnum> for WrapperEnum {
    fn from(value: ForeignEnum) -> Self {
        match value {
            ForeignEnum::Variant1 => WrapperEnum::Variant1,
            ForeignEnum::Variant2 => WrapperEnum::Variant2,
            ForeignEnum::Variant3 => WrapperEnum::Variant3,
        }
    }
}

impl From<WrapperEnum> for ForeignEnum {
    fn from(value: WrapperEnum) -> Self {
        match value {
            WrapperEnum::Variant1 => ForeignEnum::Variant1,
            WrapperEnum::Variant2 => ForeignEnum::Variant2,
            WrapperEnum::Variant3 => ForeignEnum::Variant3,
        }
    }
}

We want to create a couple macros that will handle automatic code generation of these repetitive impl blocks. The macros would generate the same code as above, and might be used like so:

#[wasm_bindgen]
#[foreign_type_wrapper]
pub struct WrapperType(ForeignType);

#[wasm_bindgen]
#[foreign_enum_wrapper(ForeignEnum)]
pub enum WrapperEnum {
    // the variants should be generated by the macro too
}

by the way, a macro must be defined in its own crate with this in Cargo.toml:

[lib]
proc-macro = true

See: https://doc.rust-lang.org/book/ch19-06-macros.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant