profile_traits/
generic_callback.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use base::generic_channel::SendResult;
6use serde::{Deserialize, Serialize};
7
8use crate::time::{ProfilerCategory, ProfilerChan};
9use crate::time_profile;
10
11#[derive(Clone, Debug, Serialize, Deserialize)]
12pub struct GenericCallback<T>
13where
14    T: Serialize + Send + 'static,
15{
16    callback: base::generic_channel::GenericCallback<T>,
17    time_profiler_chan: ProfilerChan,
18}
19
20impl<T> GenericCallback<T>
21where
22    T: for<'de> Deserialize<'de> + Serialize + Send + 'static,
23{
24    pub fn new<F: FnMut(Result<T, ipc_channel::Error>) + Send + 'static>(
25        time_profiler_chan: ProfilerChan,
26        callback: F,
27    ) -> Result<Self, ipc_channel::Error> {
28        Ok(GenericCallback {
29            callback: base::generic_channel::GenericCallback::new(callback)?,
30            time_profiler_chan,
31        })
32    }
33    pub fn send(&self, value: T) -> SendResult {
34        time_profile!(
35            ProfilerCategory::IpcReceiver,
36            None,
37            self.time_profiler_chan.clone(),
38            move || self.callback.send(value)
39        )
40    }
41}