overloading

Crates.iooverloading
lib.rsoverloading
version0.1.2
sourcesrc
created_at2023-01-10 14:35:28.099177
updated_at2023-01-10 15:14:02.959818
descriptionA POC crate that utilizes `Fn*` traits to implement partial overloading
homepage
repositoryhttps://github.com/George-Miao/overloading
max_upload_size
id755416
size7,797
Pop (George-Miao)

documentation

README

Overloading

github crates.io docs.rs

A POC crate that utilizes Fn* traits to implement partial overloading. Caveat: only parameters can be overloaded, not return types.

TLDR

#![feature(unboxed_closures)]
#![feature(fn_traits)]

use overloading::overloading;

#[overloading]
fn overloaded(abc: String) -> i32 {
    abc.parse().unwrap()
}

#[overloading(overloaded)]
fn overloaded() -> i32 {
    114514
}

#[test]
fn test() {
    let res = overloaded("123".to_owned());
    assert_eq!(res, 123);

    let res = overloaded();
    assert_eq!(res, 114514);
}

Expanded code:

#[allow(non_camel_case_types)]
struct overloaded;
impl std::ops::FnOnce<(String,)> for overloaded {
    type Output = i32;
    extern "rust-call" fn call_once(self, (abc,): (String,)) -> Self::Output {
        abc.parse().unwrap()
    }
}
impl std::ops::FnMut<(String,)> for overloaded {
    extern "rust-call" fn call_mut(&mut self, (abc,): (String,)) -> Self::Output {
        abc.parse().unwrap()
    }
}
impl std::ops::Fn<(String,)> for overloaded {
    extern "rust-call" fn call(&self, (abc,): (String,)) -> Self::Output {
        abc.parse().unwrap()
    }
}
impl std::ops::FnOnce<()> for overloaded {
    type Output = i32;
    extern "rust-call" fn call_once(self, _: ()) -> Self::Output {
        114514
    }
}
impl std::ops::FnMut<()> for overloaded {
    extern "rust-call" fn call_mut(&mut self, _: ()) -> Self::Output {
        114514
    }
}
impl std::ops::Fn<()> for overloaded {
    extern "rust-call" fn call(&self, _: ()) -> Self::Output {
        114514
    }
}
Commit count: 7

cargo fmt