#traits #generator #macro #proc-macro

macro conditional-trait-gen

Trait implementation generator macro supporting conditional methods

2 releases

0.4.1 Sep 27, 2024
0.4.0 Sep 27, 2024

#982 in #generator

Download history 133/week @ 2024-10-12 97/week @ 2024-10-19 148/week @ 2024-10-26 26/week @ 2024-11-02 18/week @ 2024-11-09 48/week @ 2024-11-16 69/week @ 2024-11-23 342/week @ 2024-11-30 196/week @ 2024-12-07 83/week @ 2024-12-14 164/week @ 2024-12-21 45/week @ 2024-12-28 89/week @ 2025-01-04 137/week @ 2025-01-11 339/week @ 2025-01-18 124/week @ 2025-01-25

690 downloads per month
Used in 4 crates (via golem-service-base)

MIT/Apache

46KB
733 lines

conditional_trait_gen

A fork of the trait_gen crate, adding support for specializing trait methods based on the type it is generated for.

Introduces a #[when] attribute that can be used on methods of the trait implementation to customize the method based on the actual type used by the generator.

Example:

 #[async_trait]
trait Repo {
    async fn create(&self, param: String) -> Result<u64, String>;
    async fn read(&self, id: u64) -> Result<String, String>;
    async fn update(&self, id: u64, param: String) -> Result<(), String>;
    async fn delete(&self, id: u64) -> Result<(), String>;
}

#[trait_gen(DB -> sqlx::sqlite::Sqlite, sqlx::mysql::MySql, sqlx::postgres::Postgres)]
#[async_trait]
impl Repo for sqlx::Pool<DB> {
    async fn create(&self, param: String) -> Result<u64, String> {
        // Common implementation
        todo!()
    }

    async fn read(&self, id: u64) -> Result<String, String> {
        // Common implementation
        todo!()
    }

    #[when(sqlx::sqlite::Sqlite -> update)]
    async fn update_sqlite(&self, id: u64, param: String) -> Result<(), String> {
        // SQLite specific implementation
        todo!()
    }

    #[when(sqlx::mysql::MySql -> update)]
    async fn update_mysql(&self, id: u64, param: String) -> Result<(), String> {
        // MySQL specific implementation
        todo!()
    }

    #[when(sqlx::postgres::Postgres -> update)]
    async fn update_postgres(&self, id: u64, param: String) -> Result<(), String> {
        // Postgres specific implementation
        todo!()
    }

    async fn delete(&self, id: u64) -> Result<(), String> {
        // Common implementation
        todo!()
    }
}

Dependencies

~1.5MB
~39K SLoC