1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// This Source Code Form is subject to the terms of the
// Mozilla Public License, v. 2.0. If a copy of the MPL was
// not distributed with this file, You can obtain one at
// http://mozilla.org/MPL/2.0/.

//! Crate which contains a "handler map", a structure that maps message types with "handlers" that
//! can be called with them.
//!
//! The focal point of this crate is the `HandlerMap` type, which stores information about
//! functions which receive various types. This can be used to encode event handlers, message
//! handlers, or other situations where you want to dynamically select a function to call based on
//! the data it receives.
//!
//! To register a handler, pass it to `insert`:
//!
//! ```rust
//! use handler_map::HandlerMap;
//!
//! /// Message which prints to the console when received.
//! struct MyMessage;
//!
//! fn handle(_: MyMessage) {
//!     println!("got your message!");
//! }
//!
//! let mut map = HandlerMap::new();
//! map.insert(handle);
//! ```
//!
//! This adds the handler to the map so that it can be `call`ed later on:
//!
//! ```rust
//! # use handler_map::HandlerMap;
//!
//! # /// Message which prints to the console when received.
//! # struct MyMessage;
//!
//! # fn handle(_: MyMessage) {
//! #     println!("got your message!");
//! # }
//!
//! # let mut map = HandlerMap::new();
//! # map.insert(handle);
//! map.call(MyMessage);
//! ```
//!
//! The map can also take closures, as long as they implement `Fn` and don't capture any references
//! to their environment:
//!
//! ```rust
//! use handler_map::HandlerMap;
//! use std::rc::Rc;
//! use std::cell::Cell;
//!
//! /// Message which increments an accumulator when received.
//! struct MyMessage;
//!
//! let mut map = HandlerMap::new();
//! let acc = Rc::new(Cell::new(0));
//! {
//!     let acc = acc.clone();
//!     map.insert(move |_: MyMessage| {
//!         acc.set(acc.get() + 1);
//!     });
//! }
//!
//! // call the handler a few times to increment the counter
//! map.call(MyMessage);
//! map.call(MyMessage);
//! map.call(MyMessage);
//!
//! assert_eq!(acc.get(), 3);
//! ```
//!
//! `call` can take a message of any type, even if that type hasn't been registered. It returns a
//! `bool` representing whether a handler was called. If a handler for that type has been
//! registered in the map, it returns `true`; otherwise, it returns `false`. If you want to check
//! that a handler has been registered without calling it, use `is_registered` or
//! `val_is_registered`.
//!
//! If you want to remove an event from the handler, call `remove`:
//!
//! ```rust
//! use handler_map::HandlerMap;
//!
//! struct MyMessage;
//! fn handle_msg(_: MyMessage) {}
//!
//! let mut map = HandlerMap::new();
//! map.insert(handle_msg);
//!
//! assert!(map.is_registered::<MyMessage>());
//!
//! map.remove::<MyMessage>();
//!
//! assert!(!map.is_registered::<MyMessage>());
//! ```

mod boxfn;

use std::any::{Any, TypeId};
use std::collections::HashMap;

use boxfn::{BoxFn, Opaque};

/// Struct that maps types with functions or closures that can receive them.
///
/// See the [module-level documentation](index.html) for more information.
#[derive(Default)]
pub struct HandlerMap(HashMap<TypeId, BoxFn<'static, Opaque>>);

impl HandlerMap {
    /// Creates a new map with no handlers.
    pub fn new() -> HandlerMap {
        Self::default()
    }

    /// Registers a new handler into the map.
    pub fn insert<T: Any, F: Fn(T) + 'static>(&mut self, handler: F) {
        let ptr: BoxFn<'static, T, F> = Box::new(handler).into();
        let ptr: BoxFn<'static, Opaque> = ptr.erase().erase_arg();
        let id = TypeId::of::<T>();

        self.0.insert(id, ptr);
    }

    /// Un-registers the handler for the given type from this map.
    pub fn remove<T: Any>(&mut self) {
        let id = TypeId::of::<T>();
        self.0.remove(&id);
    }

    /// Returns true if the given message type has a handler registered in the map.
    pub fn is_registered<T: Any>(&self) -> bool {
        let id = TypeId::of::<T>();
        self.0.contains_key(&id)
    }

    /// Returns true if the given message has a handler registered in this map.
    ///
    /// This is the same operation as `is_registered`, but allows you to call it with a value
    /// rather than having to supply the type.
    pub fn val_is_registered<T: Any>(&self, _msg: &T) -> bool {
        self.is_registered::<T>()
    }

    /// Calls the handler with the given message, returning whether the handler was registered.
    pub fn call<T: Any>(&self, msg: T) -> bool {
        let id = TypeId::of::<T>();
        if let Some(act) = self.0.get(&id) {
            unsafe { act.call_erased(msg); }
            true
        } else {
            false
        }
    }
}

#[cfg(test)]
mod tests {
    use super::HandlerMap;

    #[test]
    fn it_works() {
        struct MyMessage;
        fn respond(_: MyMessage) {}

        let mut map = HandlerMap::new();
        map.insert(respond);

        assert!(map.call(MyMessage));
    }

    #[test]
    fn no_handler() {
        struct MyMessage;

        let map = HandlerMap::new();

        assert!(!map.call(MyMessage));
    }

    #[test]
    fn handler_is_called() {
        use std::sync::Arc;
        use std::sync::atomic::AtomicUsize;
        use std::sync::atomic::Ordering::SeqCst;

        let mut map = HandlerMap::new();

        struct FancyCaller;
        let acc = Arc::new(AtomicUsize::new(0));
        {
            let acc = acc.clone();
            map.insert(move |_: FancyCaller| {
                acc.fetch_add(1, SeqCst);
            });
        }

        map.call(FancyCaller);
        map.call(FancyCaller);
        map.call(FancyCaller);

        assert_eq!(acc.load(SeqCst), 3);
    }
}