Skip to main content

profile_traits/
generic_channel.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 serde::{Deserialize, Serialize};
6use servo_base::generic_channel;
7
8use crate::time::{ProfilerCategory, ProfilerChan};
9use crate::time_profile;
10
11pub struct GenericReceiver<T>
12where
13    T: for<'de> Deserialize<'de> + Serialize,
14{
15    receiver: generic_channel::GenericReceiver<T>,
16    time_profile_chan: ProfilerChan,
17}
18
19impl<T> GenericReceiver<T>
20where
21    T: for<'de> Deserialize<'de> + Serialize,
22{
23    pub(crate) fn new(
24        receiver: generic_channel::GenericReceiver<T>,
25        time_profile_chan: ProfilerChan,
26    ) -> Self {
27        Self {
28            receiver,
29            time_profile_chan,
30        }
31    }
32
33    pub fn recv(&self) -> Result<T, generic_channel::ReceiveError> {
34        time_profile!(
35            ProfilerCategory::IpcReceiver,
36            None,
37            self.time_profile_chan.clone(),
38            move || self.receiver.recv(),
39        )
40    }
41
42    pub fn try_recv(&self) -> Result<T, generic_channel::TryReceiveError> {
43        self.receiver.try_recv()
44    }
45
46    pub fn into_inner(self) -> generic_channel::GenericReceiver<T> {
47        self.receiver
48    }
49}
50
51pub fn channel<T>(
52    time_profile_chan: ProfilerChan,
53) -> Option<(generic_channel::GenericSender<T>, GenericReceiver<T>)>
54where
55    T: for<'de> Deserialize<'de> + Serialize,
56{
57    let (sender, receiver) = generic_channel::channel()?;
58    let profiled_receiver = GenericReceiver {
59        receiver,
60        time_profile_chan,
61    };
62    Some((sender, profiled_receiver))
63}