anymsg 0.1.0

Type-routed message passing infrastructure
Documentation

A system for managing typed events

Example

use std::thread;
use std::sync::atomic::{AtomicBool, Ordering};
use anymsg::{Pump, EventLoopMapping};

let mut pump = Pump::new();

// Define various messages
struct UpdateMsg { what: usize }
struct AddMsg { by: usize }
struct VerifyMsg { equals: usize }

// Define our Client, with its own state
struct ReceiverType {
    counter: usize
}

// Create our initial state
let receiver = ReceiverType { counter: 1 };

#
# static RAN_VERIFY: AtomicBool = AtomicBool::new(false);

let sender = pump.sender();
let mut mapping = EventLoopMapping::new();

mapping.add_client(receiver)
    .add_handler(|this: &mut ReceiverType, msg: &UpdateMsg| {
        this.counter = msg.what;
    })
    .add_handler(|this: &mut ReceiverType, msg: &AddMsg| {
        this.counter += msg.by;
    })
    .add_handler(|this, msg: &VerifyMsg| {
        assert!(this.counter == msg.equals);
        println!("We passed the test!");
#        RAN_VERIFY.store(true, Ordering::SeqCst);
    });

let event_loop = pump.event_loop(mapping);
let pthread = pump.start();
let client_thread = thread::spawn(move || {
    let mut event_loop = event_loop;
    while event_loop.poll_once().is_ok() {}
});

// Send our messages and terminate
sender.send(UpdateMsg {what: 7});
sender.send(AddMsg {by: 1}).unwrap();
sender.send(VerifyMsg {equals: 8}).unwrap();
sender.hang_up();

client_thread.join().unwrap();
# assert!(RAN_VERIFY.load(Ordering::SeqCst));
pthread.join();