#dispatch #function #run-time #map #dynamic

dispatchtable

Small library used to specify function dispatch tables HashMap<K, Box<Fn(..)>>

6 releases

0.2.0 Mar 13, 2020
0.1.4 Mar 11, 2020

#2790 in Rust patterns

MIT license

7KB
148 lines

DispatchTable

A rust library used for storing functions inside a key-based collection.

use dispatchtable::{DispatchTable, Dispatch};

fn add(params: &(isize, isize)) -> isize {
    params.0 + params.1
}

fn sub(params: &(isize, isize)) -> isize {
    params.0 + params.1
}


fn main() {
    let mut table = DispatchTable::new();
    table.insert("add", Box::new(add));
    table.insert("sub", Box::new(sub));

    assert_eq!(table.call(&"add", &(1, 2)), Some(3));
    assert_eq!(table.call(&"sub", &(5, 2)), Some(3));
}

lib.rs:

dispatchtable is a runtime key based collection that contains references to functions.

Quick Start

use dispatchtable::{Dispatch, DispatchTable};

fn add(p: &(u8, u8)) -> u8 { p.0 + p.1 }
fn sub(p: &(u8, u8)) -> u8 { p.0 - p.1 }

fn main() {
  let mut dispatchtable = DispatchTable::new();

  dispatchtable.insert("add".to_string(), Box::new(add));
  dispatchtable.insert("sub".to_string(), Box::new(sub));

  assert_eq!(dispatchtable.call("sub", &(10, 5)), Some(5));
}

No runtime deps