hermes_async_runtime_components/channel_once/
impls.rs

1use cgp::prelude::*;
2use futures_channel::oneshot::{channel, Receiver, Sender};
3use hermes_runtime_components::traits::channel_once::{
4    ChannelOnceCreator, ChannelOnceUser, ProvideChannelOnceType,
5};
6
7use crate::channel::types::ChannelClosedError;
8use crate::channel_once::traits::{HasOneShotChannelType, OneShotChannelTypeProvider};
9
10pub struct ProvideOneShotChannelType;
11
12impl<Runtime> ProvideChannelOnceType<Runtime> for ProvideOneShotChannelType
13where
14    Runtime: Async,
15{
16    type SenderOnce<T> = Sender<T>
17    where
18        T: Async;
19
20    type ReceiverOnce<T> = Receiver<T>
21    where
22        T: Async;
23}
24
25impl<Runtime> OneShotChannelTypeProvider<Runtime> for ProvideOneShotChannelType
26where
27    Runtime: Async,
28{
29    fn from_oneshot_sender<T>(sender: Sender<T>) -> Self::SenderOnce<T>
30    where
31        T: Async,
32    {
33        sender
34    }
35
36    fn from_oneshot_receiver<T>(receiver: Receiver<T>) -> Self::ReceiverOnce<T>
37    where
38        T: Async,
39    {
40        receiver
41    }
42
43    fn to_oneshot_sender<T>(sender: Self::SenderOnce<T>) -> Sender<T>
44    where
45        T: Async,
46    {
47        sender
48    }
49
50    fn to_oneshot_receiver<T>(receiver: Self::ReceiverOnce<T>) -> Receiver<T>
51    where
52        T: Async,
53    {
54        receiver
55    }
56}
57
58impl<Runtime> ChannelOnceCreator<Runtime> for ProvideOneShotChannelType
59where
60    Runtime: HasOneShotChannelType,
61{
62    fn new_channel_once<T>() -> (Runtime::SenderOnce<T>, Runtime::ReceiverOnce<T>)
63    where
64        T: Async,
65    {
66        let (sender, receiver) = channel();
67
68        (
69            Runtime::from_oneshot_sender(sender),
70            Runtime::from_oneshot_receiver(receiver),
71        )
72    }
73}
74
75impl<Runtime> ChannelOnceUser<Runtime> for ProvideOneShotChannelType
76where
77    Runtime: HasOneShotChannelType + CanRaiseError<ChannelClosedError>,
78{
79    fn send_once<T>(sender: Runtime::SenderOnce<T>, value: T) -> Result<(), Runtime::Error>
80    where
81        T: Async,
82    {
83        Runtime::to_oneshot_sender(sender)
84            .send(value)
85            .map_err(|_| Runtime::raise_error(ChannelClosedError))
86    }
87
88    async fn receive_once<T>(receiver: Runtime::ReceiverOnce<T>) -> Result<T, Runtime::Error>
89    where
90        T: Async,
91    {
92        Runtime::to_oneshot_receiver(receiver)
93            .await
94            .map_err(|_| Runtime::raise_error(ChannelClosedError))
95    }
96}