Crate simple_ref_fn
source ·Expand description
This crate provides type-erased function wrappers that behave like &dyn Fn(T) -> R
and &mut dyn FnMut(T) -> R
,
but do not require compiler to generate virtual tables.
The following wrapper types are provided:
Examples
Bind a function with a reference
use simple_ref_fn::{RefFn, StaticRefFunction};
// Define a static function.
struct F;
impl StaticRefFunction<'_, u32, u32> for F {
type Output = u32;
fn call(data: &u32, arg: u32) -> Self::Output {
data + arg
}
}
// Bind the function with a reference.
let data = 2;
let f: RefFn<u32, u32> = F::bind(&data); // Type-erasure.
assert_eq!(f.call(3), 5);
assert_eq!(f.call(5), 7);
assert_eq!(f.call(7), 9);
Erase the type of a closure
use simple_ref_fn::RefFn;
let data = 2_u32;
let closure = |arg: u32| data + arg;
let f: RefFn<u32, u32> = RefFn::from(&closure); // Type-erasure.
assert_eq!(f.call(3), 5);
assert_eq!(f.call(5), 7);
assert_eq!(f.call(7), 9);
Structs
A simple function wrapper that behaves like a
&dyn Fn(T) -> R
type, but does not require a virtual table.A simple function wrapper that behaves like a
&mut dyn FnMut(T) -> R
type, but does not require a
virtual table.A simple function wrapper that behaves like a
&mut (dyn FnMut(T) -> R + Send)
type, but does not
require a virtual table.A simple function wrapper that behaves like a
&(dyn Fn(T) -> R + Sync)
type, but does not require a
virtual table.Traits
A trait for defining a static function will be type erased.
A trait for defining a static function that will be type erased.