1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use std::cell::UnsafeCell;
use std::rc::Rc;
use std::os::raw::c_void;
use crate::priv_traits::*;
use crate::{Stream, StreamRc};
pub fn stream<'a, T: 'a>() -> (Sender<'a, T>, Stream<'a,T>){
let se = Sender::new();
let st = Stream::new(se.inner.clone());
(se, st)
}
pub struct SenderInner<'a, T>{
sink: Option<Rc<UnsafeCell<dyn SinkInner<'a,T> + 'a>>>,
}
impl<'a, T> SenderInner<'a, T>{
pub fn new() -> SenderInner<'a,T>{
SenderInner{ sink: None }
}
}
impl<'a, T> SenderInner<'a, T>{
#[inline]
pub fn send(&mut self, t: T){
let done = if let Some(ref sink) = self.sink{
unsafe{ (*sink.get()).call(t).is_err() }
}else{
false
};
if done { self.sink = None }
}
#[inline]
pub fn send_all<I: IntoIterator<Item=T>>(&mut self, it: I){
let done = if let Some(ref sink) = self.sink{
it.into_iter().any(|t|unsafe{ (*sink.get()).call(t).is_err() })
}else{
false
};
if done { self.sink = None }
}
}
impl<'a, T> StreamInner<'a,T> for SenderInner<'a, T>{
#[inline]
fn push(&mut self, st: Rc<UnsafeCell<dyn SinkInner<'a,T> + 'a>>){
self.sink = Some(st);
}
#[inline]
fn send(&mut self, t: T){
(*self).send(t)
}
}
impl<'a, T> Remove for SenderInner<'a, T>{
fn remove_raw(&mut self, st: *const c_void){
let done = if let Some(ref sink) = self.sink{
if sink.get() as *const c_void == st{
true
}else{
panic!("Trying to remove a sink with a different address");
}
}else{
false
};
if done { self.sink = None }
}
}
impl<'a, T> SinkInner<'a,T> for SenderInner<'a, T>{
#[inline]
fn call(&mut self, t: T) -> Result<(),()>{
self.send(t);
Ok(())
}
#[inline]
fn is_alive(&self) -> bool {
true
}
}
#[derive(Clone)]
pub struct Sender<'a, T>{
inner: Rc<UnsafeCell<SenderInner<'a, T>>>,
}
impl<'a, T> Sender<'a, T>{
pub fn new() -> Sender<'a,T>{
Sender{ inner: Rc::new(UnsafeCell::new(SenderInner::new())) }
}
pub fn push(&mut self, st: Rc<UnsafeCell<dyn SinkInner<'a,T> + 'a>>){
unsafe{ (*self.inner.get()).push(st) }
}
pub fn remove_raw(&mut self, st: *const c_void){
unsafe{ (*self.inner.get()).remove_raw(st) }
}
pub fn num_receivers(&self) -> usize{
if unsafe{ (*self.inner.get()).sink.is_some() } {
1
}else{
0
}
}
}
impl<'a, T> Sender<'a, T>{
#[inline]
pub fn send(&self, t: T){
unsafe{(*self.inner.get()).send(t)}
}
#[inline]
pub fn send_all<I: IntoIterator<Item = T>>(&self, it: I){
unsafe{(*self.inner.get()).send_all(it)}
}
}
impl<'a, T: 'a> From<StreamRc<'a,T>> for Stream<'a,T>{
fn from(st: StreamRc<'a,T>) -> Stream<'a,T>{
Stream::from_parent(st, Rc::new(UnsafeCell::new(SenderInner::new())))
}
}