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 malloc_size_of_derive::MallocSizeOf;
7use serde::{Deserialize, Serialize};
8
9use crate::time::{ProfilerCategory, ProfilerChan};
10use crate::time_profile;
11
12#[derive(Clone, Debug, Serialize, Deserialize, MallocSizeOf)]
13pub struct GenericCallback<T>
14where
15    T: Serialize + Send + 'static,
16{
17    callback: base::generic_channel::GenericCallback<T>,
18    time_profiler_chan: ProfilerChan,
19}
20
21impl<T> GenericCallback<T>
22where
23    T: for<'de> Deserialize<'de> + Serialize + Send + 'static,
24{
25    pub fn new<F: FnMut(Result<T, ipc_channel::Error>) + Send + 'static>(
26        time_profiler_chan: ProfilerChan,
27        callback: F,
28    ) -> Result<Self, ipc_channel::Error> {
29        Ok(GenericCallback {
30            callback: base::generic_channel::GenericCallback::new(callback)?,
31            time_profiler_chan,
32        })
33    }
34    pub fn send(&self, value: T) -> SendResult {
35        time_profile!(
36            ProfilerCategory::IpcReceiver,
37            None,
38            self.time_profiler_chan.clone(),
39            move || self.callback.send(value)
40        )
41    }
42}