#type #compile-time #checking #ignore #stub #function #onlytypes-rs

macro onlytypes

A library for creating types that can only be created by a certain function

4 releases

0.1.4 Oct 21, 2023
0.1.2 Oct 21, 2023
0.1.1 Oct 20, 2023
0.1.0 Oct 20, 2023

#1872 in Procedural macros

MIT license

13KB
232 lines

Only Types, for Rust

Allows you to ignore impl blocks, or stub functions. If all you need is compile-time type checking, this is for you. Or if you don't want to ship a lot of bloat to your users, this is also for you.

Example

use std::fmt;

pub trait MyTrait {
    type Output;
    fn my_trait_function(&self) -> Self::Output;
    fn some_other_trait_function(&self) -> Self::Output;
}

pub struct MyStruct {
    pub key: String,
    pub value: String
}

#[onlytypes::ignore] // Completely ignores this impl block
impl MyStruct {
    pub fn new(key: String, value: String) -> Self {
        Self { key, value }
    }
    pub fn key(&self) -> &str {
        self.key.as_str()
    }
    pub fn value(&self) -> &str {
        self.value.as_str()
    }
    pub fn to_json(&self) -> String {
        format!("{{\"key\": \"{}\", \"value\": \"{}\"}}", self.key(), self.value())
    }
}

impl fmt::Debug for MyStruct {
    #[onlytypes::stub]// Will stub this function (but still compile)
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PublicStruct")
            .field("key", &self.key())
            .field("value", &self.value())
            .finish()
    }
}

#[onlytypes::stub]// Will stub the entire impl block (but still compile)
impl MyTrait for MyStruct {
    type Output = String;
    fn my_trait_function(&self) -> Self::Output {
        format!("{}: {}", self.key(), self.value())
    }
    fn some_other_trait_function(&self) -> Self::Output {
        format!("{}: {}", self.key(), self.value())
    }
}

Changelog

Dependencies

~230–670KB
~16K SLoC