1pub mod rc_linked;
2
3use std::{
4 cell::{Ref, RefCell, RefMut},
5 ops::Deref,
6 rc::Rc,
7};
8
9use self::rc_linked::RcLinked;
10
11#[derive(PartialEq, Eq, Clone)]
12pub struct RcLinker<R> {
13 receiver: Rc<RefCell<Option<R>>>,
14}
15
16impl<R> RcLinker<R> {
17 pub fn new(receiver: R) -> Self {
18 Self {
19 receiver: Rc::new(RefCell::new(Some(receiver))),
20 }
21 }
22
23 pub fn get_receiver(&self) -> &RefCell<Option<R>> {
24 self
25 }
26
27 pub fn borrow(&self) -> Ref<Option<R>> {
28 self.receiver.borrow()
29 }
30
31 pub fn borrow_mut(&self) -> RefMut<Option<R>> {
32 self.receiver.borrow_mut()
33 }
34
35 pub fn linked(&self) -> RcLinked<R> {
36 RcLinked {
37 link: self.receiver.clone(),
38 }
39 }
40}
41
42impl<R> Deref for RcLinker<R> {
43 type Target = RefCell<Option<R>>;
44
45 fn deref(&self) -> &Self::Target {
46 &self.receiver
47 }
48}
49
50impl<R> Drop for RcLinker<R> {
51 fn drop(&mut self) {
52 *self.receiver.borrow_mut() = None;
53 }
54}
55
56impl<R: Default> Default for RcLinker<R> {
57 fn default() -> Self {
58 Self::new(R::default())
59 }
60}
61
62impl<R: std::fmt::Debug> std::fmt::Debug for RcLinker<R> {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 write!(
65 f,
66 "{{links: {}, receiver: {:?}}}",
67 Rc::strong_count(&self.receiver),
68 self.receiver
69 )
70 }
71}
72
73impl<R: std::fmt::Display> std::fmt::Display for RcLinker<R> {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 match self.receiver.try_borrow() {
76 Ok(r) => match r.as_ref() {
77 Some(v) => v.fmt(f),
78 None => write!(f, "<deleted>"),
79 },
80 Err(_) => write!(f, "<borrowed>"),
81 }
82 }
83}