#table #type-erasure #require #virtual #wrapper #fn-mut #virtual-table

simple-ref-fn

Simple function wrappers that do not require virtual tables

3 releases

0.1.2 Dec 12, 2022
0.1.1 Dec 12, 2022
0.1.0 Dec 11, 2022

#1616 in Data structures

Download history 2/week @ 2024-02-18 20/week @ 2024-02-25 71/week @ 2024-03-10 1/week @ 2024-03-17 28/week @ 2024-03-31

100 downloads per month

MIT license

20KB
430 lines

simple-ref-fn

crates.io docs CI codecov Coverage Status

Type-erased function wrappers that do not require virtual tables.


lib.rs:

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:

Type Behaves like Send Sync
RefFn<'a, T, R> &'a dyn Fn(T) -> R No No
RefSyncFn<'a, T, R> &'a (dyn Fn(T) -> R + Sync) Yes Yes
RefFnMut<'a, T, R> &'a mut dyn FnMut(T) -> R No Yes
RefSendFnMut<'a, T, R> &'a mut (dyn FnMut(T) -> R + Send) Yes Yes

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);

No runtime deps