rosrust/api/
handlers.rs

1use crate::Message;
2use std::collections::HashMap;
3use std::marker::PhantomData;
4
5/// Handles all calls involved with a subscription
6///
7/// Each subscription is done in one thread, so there is no synchronization necessary between
8/// these calls.
9pub trait SubscriptionHandler<T>: Send + 'static {
10    /// Called before any message is accepted from a certain caller ID
11    ///
12    /// Contains the headers for handling the specific connection
13    fn connection(&mut self, headers: HashMap<String, String>);
14
15    /// Called upon receiving any message
16    fn message(&mut self, message: T, callerid: &str);
17}
18
19pub struct CallbackSubscriptionHandler<T, F, G> {
20    on_message: F,
21    on_connect: G,
22    _phantom: PhantomData<T>,
23}
24
25impl<T, F, G> CallbackSubscriptionHandler<T, F, G>
26where
27    T: Message,
28    F: Fn(T, &str) + Send + 'static,
29    G: Fn(HashMap<String, String>) + Send + 'static,
30{
31    pub fn new(on_message: F, on_connect: G) -> Self {
32        Self {
33            on_message,
34            on_connect,
35            _phantom: PhantomData,
36        }
37    }
38}
39
40impl<T, F, G> SubscriptionHandler<T> for CallbackSubscriptionHandler<T, F, G>
41where
42    T: Message,
43    F: Fn(T, &str) + Send + 'static,
44    G: Fn(HashMap<String, String>) + Send + 'static,
45{
46    fn connection(&mut self, headers: HashMap<String, String>) {
47        (self.on_connect)(headers)
48    }
49
50    fn message(&mut self, message: T, callerid: &str) {
51        (self.on_message)(message, callerid)
52    }
53}