data_router/arc_linker/
arc_linked.rs

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