libjuice_rs/agent/
handler.rs

1use crate::agent::State;
2
3/// Closures based event handler.
4///
5/// Any closure from given handler can be invoked in any thread, usually from dedicated internal
6/// libjuice thread.
7///
8/// # Example
9/// ```
10/// # use libjuice_rs::Handler;
11/// let h: Handler = Handler::default()
12///     .state_handler(|s| println!("State changed to: {:?}", s))
13///     .candidate_handler(|c| println!("Local candidate: {:?}", c))
14///     .gathering_done_handler(||println!("Gathering done!"))
15///     .recv_handler(|packet| println!("Received packet of length: {}", packet.len()));
16/// ```
17#[derive(Default)]
18pub struct Handler {
19    /// ICE state change handler
20    on_state_change: Option<Box<dyn FnMut(State) + Send + 'static>>,
21    /// Local ICE candidate handler
22    on_candidate: Option<Box<dyn FnMut(String) + Send + 'static>>,
23    /// Gathering stage finish handler
24    on_gathering_done: Option<Box<dyn FnMut() + Send + 'static>>,
25    /// Incoming packet
26    on_recv: Option<Box<dyn FnMut(&[u8]) + Send + 'static>>,
27}
28
29impl Handler {
30    /// Set ICE state change handler
31    pub fn state_handler<F>(mut self, f: F) -> Self
32    where
33        F: FnMut(State),
34        F: Send + Sync + 'static,
35    {
36        self.on_state_change = Some(Box::new(f));
37        self
38    }
39
40    /// Set local candidate handler
41    pub fn candidate_handler<F>(mut self, f: F) -> Self
42    where
43        F: FnMut(String),
44        F: Send + 'static,
45    {
46        self.on_candidate = Some(Box::new(f));
47        self
48    }
49
50    /// Set gathering done handler
51    pub fn gathering_done_handler<F>(mut self, f: F) -> Self
52    where
53        F: FnMut(),
54        F: Send + 'static,
55    {
56        self.on_gathering_done = Some(Box::new(f));
57        self
58    }
59
60    /// Set incoming packet handler
61    pub fn recv_handler<F>(mut self, f: F) -> Self
62    where
63        F: FnMut(&[u8]),
64        F: Send + 'static,
65    {
66        self.on_recv = Some(Box::new(f));
67        self
68    }
69
70    pub(crate) fn on_state_changed(&mut self, state: State) {
71        if let Some(f) = &mut self.on_state_change {
72            f(state)
73        }
74    }
75
76    pub(crate) fn on_candidate(&mut self, candidate: String) {
77        if let Some(f) = &mut self.on_candidate {
78            f(candidate)
79        }
80    }
81
82    pub(crate) fn on_gathering_done(&mut self) {
83        if let Some(f) = &mut self.on_gathering_done {
84            f()
85        }
86    }
87
88    pub(crate) fn on_recv(&mut self, packet: &[u8]) {
89        if let Some(f) = &mut self.on_recv {
90            f(packet)
91        }
92    }
93}