BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / latest.rs

latest.rs

latest.rs 2.2 KiB Download Raw
1use std::sync::{Condvar, Mutex};
2
3struct Slot<T> {
4 newest: Option<T>,
5 closed: bool,
6 dropped: u64,
7}
8
9/// A one-place mailbox: a new value replaces an unread one, so a slow reader always gets the newest and nothing queues up.
10pub struct Latest<T> {
11 slot: Mutex<Slot<T>>,
12 wake: Condvar,
13}
14
15impl<T> Default for Latest<T> {
16 fn default() -> Self {
17 Latest { slot: Mutex::new(Slot { newest: None, closed: false, dropped: 0 }), wake: Condvar::new() }
18 }
19}
20
21impl<T> Latest<T> {
22 pub fn put(&self, value: T) {
23 let mut slot = self.slot.lock().expect("latest slot lock");
24 if slot.newest.replace(value).is_some() {
25 slot.dropped += 1;
26 }
27 drop(slot);
28 self.wake.notify_one();
29 }
30
31 /// Waits for a value; `None` once the slot is closed.
32 pub fn take(&self) -> Option<T> {
33 let mut slot = self.slot.lock().expect("latest slot lock");
34 loop {
35 if slot.closed {
36 return None;
37 }
38 if let Some(value) = slot.newest.take() {
39 return Some(value);
40 }
41 slot = self.wake.wait(slot).expect("latest slot lock");
42 }
43 }
44
45 pub fn close(&self) {
46 self.slot.lock().expect("latest slot lock").closed = true;
47 self.wake.notify_all();
48 }
49
50 pub fn dropped(&self) -> u64 {
51 self.slot.lock().expect("latest slot lock").dropped
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use std::sync::Arc;
58 use std::time::Duration;
59
60 use super::*;
61
62 #[test]
63 fn the_reader_gets_the_newest_value_and_older_ones_are_counted_as_dropped() {
64 let latest = Latest::default();
65 for value in 1..=3 {
66 latest.put(value);
67 }
68 assert_eq!(latest.take(), Some(3));
69 assert_eq!(latest.dropped(), 2);
70 }
71
72 #[test]
73 fn closing_wakes_a_waiting_reader() {
74 let latest = Arc::new(Latest::<u8>::default());
75 let reader = {
76 let latest = latest.clone();
77 std::thread::spawn(move || latest.take())
78 };
79 std::thread::sleep(Duration::from_millis(20));
80 latest.close();
81 assert_eq!(reader.join().unwrap(), None);
82 }
83}