Skip to main content

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 malloc_size_of_derive::MallocSizeOf;
6use serde::{Deserialize, Serialize};
7use servo_base::generic_channel::{SendError, SendResult};
8
9use crate::generic_channel::GenericReceiver;
10use crate::time::ProfilerChan;
11
12#[derive(Debug, Serialize, Deserialize, MallocSizeOf)]
13pub struct GenericCallback<T>(servo_base::generic_channel::GenericCallback<T>)
14where
15    T: Serialize + Send + 'static;
16
17impl<T> GenericCallback<T>
18where
19    T: for<'de> Deserialize<'de> + Serialize + Send + 'static,
20{
21    pub fn new<F: FnMut(Result<T, SendError>) + Send + 'static>(
22        callback: F,
23    ) -> Result<Self, SendError> {
24        Ok(GenericCallback(
25            servo_base::generic_channel::GenericCallback::new(callback)?,
26        ))
27    }
28
29    pub fn new_blocking(
30        time_profiler_chan: ProfilerChan,
31    ) -> Result<(Self, GenericReceiver<T>), SendError> {
32        let (callback, receiver) = servo_base::generic_channel::GenericCallback::new_blocking()?;
33        Ok((
34            GenericCallback(callback),
35            GenericReceiver::new(receiver, time_profiler_chan),
36        ))
37    }
38
39    pub fn send(&self, value: T) -> SendResult {
40        self.0.send(value)
41    }
42}
43
44impl<T> Clone for GenericCallback<T>
45where
46    T: Serialize + Send + 'static,
47{
48    fn clone(&self) -> Self {
49        Self(self.0.clone())
50    }
51}