rw_cell/broadcast/cloneable.rs
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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
//! This approach uses [`Mutex::lock`] when calling the [`Writer::share`],
//! [`Writer::subscribe`] and [`Reader::clone`] methods
//!
//! # Example
//!
//!```
//! let (mut tx, rx) = rw_cell::broadcast::cloneable::new("Not good, but ok");
//!
//! assert_eq!(tx.read(), &"Not good, but ok");
//!
//! let mut rx1 = tx.subscribe();
//! let mut rx2 = rx.clone();
//!
//! assert_eq!(rx1.read_with_is_new(), (&"Not good, but ok", false));
//! assert_eq!(rx2.read_with_is_new(), (&"Not good, but ok", false));
//!
//! tx.share("Not good");
//! assert_eq!(rx1.read_with_is_new(), (&"Not good", true));
//! assert_eq!(rx2.read_with_is_new(), (&"Not good", true));
//!
//! tx.share("ok");
//! assert_eq!(rx1.read(), &"ok");
//! assert_eq!(rx2.read(), &"ok");
//! ```
use std::sync::{Arc, Mutex};
use crate::option::OptionCell;
type Cells<T> = Arc<Mutex<Vec<Cell<T>>>>;
type Cell<T> = Arc<OptionCell<Arc<T>>>;
/// Distribute value between all readers
pub struct Writer<T> {
cells: Cells<T>,
val: Arc<T>,
}
impl<T> Writer<T> {
/// Create new distributor
fn new(val: T) -> Writer<T> {
Self {
cells: Arc::new(Mutex::new(vec![])),
val: Arc::new(val),
}
}
/// Write val and distribute it between all readers
///
/// # Example
///
/// ```
/// let (mut tx, rx) = rw_cell::broadcast::cloneable::new("Not good, but ok");
/// let mut rx1 = tx.subscribe();
/// let mut rx2 = rx.clone();
///
/// tx.share("Not good");
///
/// assert_eq!(rx1.read_with_is_new(), (&"Not good", true));
/// assert_eq!(rx2.read_with_is_new(), (&"Not good", true));
/// ```
pub fn share(&mut self, val: T) {
let mut cells = self.cells
.lock()
.unwrap();
self.val = Arc::new(val);
cells.retain(|cell| {
let is_single_ref = Arc::strong_count(cell) != 1;
if is_single_ref {
cell.replace(self.val.clone());
}
is_single_ref
});
}
/// Return a reference to the value from the cell
///
/// # Example
///
/// ```
/// let (mut tx, rx) = rw_cell::broadcast::cloneable::new("Not good, but ok");
///
/// assert_eq!(tx.read(), &"Not good, but ok");
/// ```
pub fn read(&self) -> &T {
&self.val
}
/// Return new [`Reader`] for read data from cell
pub fn subscribe(&mut self) -> Reader<T> {
let cell = Arc::new(OptionCell::new(self.val.clone()));
self.cells
.lock()
.unwrap()
.push(cell.clone());
Reader::new(self.cells.clone(), cell)
}
}
/// Struct for read data from cell with non-copy and non-lock
pub struct Reader<T> {
cells: Cells<T>,
cell: Cell<T>,
val: Arc<T>
}
impl<T> Clone for Reader<T> {
fn clone(&self) -> Self {
let mut cells = self.cells
.lock()
.unwrap();
let self_cell_ptr = &raw const *self.cell;
let self_cell_idx = cells
.iter()
.enumerate()
.find_map(|(idx, cell)| (self_cell_ptr == &raw const **cell).then_some(idx))
.expect("Undefined self cell in cells");
let clone_cell = if let Some(val) = cells[self_cell_idx].take() {
cells[self_cell_idx].replace(val.clone());
Arc::new(OptionCell::new(val))
} else {
Arc::new(OptionCell::new(self.val.clone()))
};
cells.push(clone_cell.clone());
Reader::new(self.cells.clone(), clone_cell)
}
}
impl<T> Reader<T> {
fn new(cells: Cells<T>, cell: Cell<T>) -> Reader<T> {
Self {
val: cell.take().unwrap(),
cells,
cell,
}
}
/// Returns a tuple of value references and a boolean value, whether new or not
///
/// # Examples
///
/// ```
/// let (mut tx, mut rx) = rw_cell::broadcast::cloneable::new("Not good, but ok");
///
/// assert_eq!(rx.read_with_is_new(), (&"Not good, but ok", false));
///
/// tx.share("Not good");
///
/// assert_eq!(rx.read_with_is_new(), (&"Not good", true));
pub fn read_with_is_new(&mut self) -> (&T, bool) {
match self.cell.take() {
None => (&*self.val, false),
Some(val) => {
self.val = val;
(&*self.val, true)
}
}
}
/// Return a reference to the value from the cell
///
/// # Examples
///
/// ```
/// let (mut tx, mut rx) = rw_cell::broadcast::cloneable::new("Not good, but ok");
///
/// assert_eq!(rx.read(), &"Not good, but ok");
///
/// tx.share("ok");
///
/// assert_eq!(rx.read(), &"ok");
pub fn read(&mut self) -> &T {
match self.cell.take() {
None => &self.val,
Some(val) => {
self.val = val;
&self.val
}
}
}
}
/// Create new cell with [`Writer`] and [`Reader`]
///
/// # Examples
///
/// ```
/// let (mut tx, mut rx) = rw_cell::broadcast::cloneable::new("Not good");
/// assert_eq!(rx.read(), &"Not good");
///
/// tx.share("But ok");
/// assert_eq!(rx.read_with_is_new(), (&"But ok", true));
/// ```
pub fn new<T>(val: T) -> (Writer<T>, Reader<T>) {
let mut tx = Writer::new(val);
let rx = tx.subscribe();
(tx, rx)
}
pub fn default<T>() -> (Writer<T>, Reader<T>)
where
T: Default
{
let mut tx = Writer::new(T::default());
let rx = tx.subscribe();
(tx, rx)
}
#[cfg(test)]
mod test {
use std::thread::JoinHandle;
use crate::broadcast;
use crate::broadcast::cloneable::{Writer, Reader};
#[test]
fn test_remove_reader() {
let (mut tx, rx) = broadcast::cloneable::new("Good");
let _rx1 = tx.subscribe();
let _rx2 = rx.clone();
assert_eq!(tx.cells.lock().unwrap().len(), 3);
drop(_rx1);
tx.share("Only one");
assert_eq!(tx.cells.lock().unwrap().len(), 2);
}
#[test]
fn test_clone() {
let (mut tx, mut rx0) = broadcast::cloneable::new("Good");
let mut rx1 = rx0.clone();
assert_eq!(rx1.read(), &"Good");
let mut rx2 = rx0.clone();
let mut rx3 = rx1.clone();
tx.share("Ok");
let mut rx4 = rx3.clone();
assert_eq!(rx0.read(), &"Ok");
assert_eq!(rx1.read(), &"Ok");
assert_eq!(rx2.read(), &"Ok");
assert_eq!(rx3.read(), &"Ok");
assert_eq!(rx4.read(), &"Ok");
}
#[test]
fn test_write_read() {
let mut tx = Writer::new("Not good, but ok");
let mut rx1 = tx.subscribe();
let mut rx2 = tx.subscribe();
assert_eq!(tx.read(), &"Not good, but ok");
assert_eq!(rx1.read_with_is_new(), (&"Not good, but ok", false));
assert_eq!(rx2.read_with_is_new(), (&"Not good, but ok", false));
tx.share("Not good");
assert_eq!(rx1.read_with_is_new(), (&"Not good", true));
assert_eq!(rx2.read_with_is_new(), (&"Not good", true));
tx.share("ok");
let mut rx3 = rx2.clone();
assert_eq!(rx1.read(), &"ok");
assert_eq!(rx2.read(), &"ok");
assert_eq!(rx3.read(), &"ok");
}
#[test]
fn is_work() -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
let (mut tx, rx0) = broadcast::cloneable::new(vec!["Ukraine".to_string(); 1000]);
let rx1 = rx0.clone();
let rx2 = tx.subscribe();
let rx3 = tx.subscribe();
std::thread::spawn(move || loop {
for i in 0usize.. {
match i % 6 {
0 => tx.share(vec!["Slovakia".to_string(); 1001]),
1 => tx.share(vec!["Estonia".to_string(); 1001]),
2 => tx.share(vec!["Czechia".to_string(); 1001]),
3 => tx.share(vec!["United Kingdom".to_string(); 1001]),
4 => tx.share(vec!["Lithuania".to_string(); 1001]),
5 => tx.share(vec!["Latvia".to_string(); 1001]),
val => println!("val: {:?}, Not good, but ok", val)
}
}
});
let count_iter = 1_000_000;
let h0 = create_thread_read(rx0, count_iter);
let h1 = create_thread_read(rx1, count_iter);
let h2 = create_thread_read(rx2, count_iter);
let h3 = create_thread_read(rx3, count_iter);
let res0 = h0.join()?;
let res1 = h1.join()?;
let res2 = h2.join()?;
let res3 = h3.join()?;
println!("Slovakia: {}", res0.0 + res1.0 + res2.0 + res3.0);
println!("Estonia: {}", res0.1 + res1.1 + res2.1 + res3.1);
println!("Czechia: {}", res0.2 + res1.2 + res2.2 + res3.2);
println!("United Kingdom: {}", res0.3 + res1.3 + res2.3 + res3.3);
println!("Lithuania: {}", res0.4 + res1.4 + res2.4 + res3.4);
println!("Latvia: {}", res0.5 + res1.5 + res2.5 + res3.5);
println!("Ukraine: {}", res0.6 + res1.6 + res2.6 + res3.6);
Ok(())
}
fn create_thread_read(
mut rw: Reader<Vec<String>>,
count_iter: usize
) -> JoinHandle<(i32, i32, i32, i32, i32, i32, i32)> {
let mut slovakia = 0;
let mut estonia = 0;
let mut czechia = 0;
let mut united_kingdom = 0;
let mut lithuania = 0;
let mut latvia = 0;
let mut ukraine = 0;
std::thread::spawn(move || {
for _ in 0..count_iter {
match rw.read() {
val if val.first() == Some(&"Slovakia".to_string()) => slovakia += 1,
val if val.first() == Some(&"Estonia".to_string()) => estonia += 1,
val if val.first() == Some(&"Czechia".to_string()) => czechia += 1,
val if val.first() == Some(&"United Kingdom".to_string()) => united_kingdom += 1,
val if val.first() == Some(&"Lithuania".to_string()) => lithuania += 1,
val if val.first() == Some(&"Latvia".to_string()) => latvia += 1,
val if val.first() == Some(&"Ukraine".to_string()) => ukraine += 1,
val => println!("val: {:?}, Not good, but ok", val.first())
}
}
(slovakia, estonia, czechia, united_kingdom, lithuania, latvia, ukraine)
})
}
}