data_router/rc_linker/
rc_linked.rs1use std::{cell::RefCell, rc::Rc};
2
3use crate::{
4 receive::{Receive, ReceiverResult},
5 view::{DeleteView, View},
6};
7
8#[derive(Clone)]
9pub struct RcLinked<R> {
10 pub(super) link: Rc<RefCell<Option<R>>>,
11}
12
13impl<R> RcLinked<R> {
14 pub fn get_receiver(&self) -> &RefCell<Option<R>> {
15 &self.link
16 }
17}
18
19impl<E, R: Receive<E>> Receive<E> for RcLinked<R> {
20 type Output = R::Output;
21
22 fn send(&mut self, event: E) -> ReceiverResult<E, Self::Output> {
23 match self.link.borrow_mut().as_mut() {
24 Some(t0) => t0.send(event),
25 None => ReceiverResult::Delete(event),
26 }
27 }
28}
29
30impl<E, R: View<E>> View<E> for RcLinked<R> {
31 fn view(&mut self, event: &E) -> Option<DeleteView> {
32 match self.link.borrow_mut().as_mut() {
33 Some(viewer) => viewer.view(event),
34 None => Some(DeleteView),
35 }
36 }
37}
38
39impl<R: std::fmt::Debug> std::fmt::Debug for RcLinked<R> {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 write!(
42 f,
43 "{{links: {}, receiver: {:?}}}",
44 Rc::strong_count(&self.link),
45 self.link
46 )
47 }
48}
49
50impl<R: std::fmt::Display> std::fmt::Display for RcLinked<R> {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 match self.link.try_borrow() {
53 Ok(r) => match r.as_ref() {
54 Some(v) => v.fmt(f),
55 None => write!(f, "<deleted>"),
56 },
57 Err(_) => write!(f, "<borrowed>"),
58 }
59 }
60}