1#![doc(html_favicon_url = "https://qaul.org/favicon.ico")]
7#![doc(html_logo_url = "https://qaul.org/img/qaul_icon-128.png")]
8
9use async_std::{
10 sync::{Arc, RwLock},
11 task,
12};
13use async_trait::async_trait;
14use ratman_netmod::{Endpoint, Error as NetError, Frame, Result as NetResult, Target};
15
16pub(crate) mod io;
21pub struct MemMod {
28 io: Arc<RwLock<Option<io::Io>>>,
30}
31
32impl MemMod {
33 pub fn new() -> Arc<Self> {
35 Arc::new(Self {
36 io: Default::default(),
37 })
38 }
39
40 pub fn make_pair() -> (Arc<Self>, Arc<Self>) {
42 let (a, b) = (MemMod::new(), MemMod::new());
43 a.link(&b);
44 (a, b)
45 }
46
47 pub fn linked(&self) -> bool {
50 task::block_on(async { self.io.read().await.is_some() })
51 }
52
53 pub fn link(&self, pair: &MemMod) {
59 if self.linked() || pair.linked() {
60 panic!("Attempted to link an already linked MemMod.");
61 }
62 let (my_io, their_io) = io::Io::make_pair();
63
64 self.set_io_async(my_io);
65 pair.set_io_async(their_io);
66 }
67
68 pub(crate) fn link_raw(&mut self, io: io::Io) {
73 if self.linked() {
74 panic!("Attempted to link an already linked MemMod.");
75 }
76 self.set_io_async(io);
77 }
78
79 pub fn split(&self) {
81 self.set_io_async(None);
84 }
85
86 fn set_io_async<I: Into<Option<io::Io>>>(&self, val: I) {
87 task::block_on(async { *self.io.write().await = val.into() });
88 }
89}
90
91#[async_trait]
92impl Endpoint for MemMod {
93 fn size_hint(&self) -> usize {
95 ::std::u32::MAX as usize
96 }
97
98 async fn send(&self, frame: Frame, _: Target) -> NetResult<()> {
105 let io = self.io.read().await;
106 match *io {
107 None => Err(NetError::NotSupported),
108 Some(ref io) => Ok(io.out.send(frame).await.unwrap()),
109 }
110 }
111
112 async fn next(&self) -> NetResult<(Frame, Target)> {
113 let io = self.io.read().await;
114 match *io {
115 None => Err(NetError::NotSupported),
116 Some(ref io) => match io.inc.recv().await {
117 Ok(f) => Ok((f, Target::default())),
118 Err(_) => Err(NetError::ConnectionLost),
119 },
120 }
121 }
122}