|
| 1 | +use std::{ops::Deref, sync::Arc}; |
| 2 | + |
| 3 | +use atomic_refcell::{AtomicRef, AtomicRefCell}; |
| 4 | + |
| 5 | +struct State<T> { |
| 6 | + value: T, |
| 7 | + dropped: bool, |
| 8 | +} |
| 9 | + |
| 10 | +struct Shared<T> { |
| 11 | + value: AtomicRefCell<State<T>>, |
| 12 | + notify: tokio::sync::Notify, |
| 13 | +} |
| 14 | + |
| 15 | +pub struct Sender<T>(Arc<Shared<T>>); |
| 16 | + |
| 17 | +pub struct Receiver<T>(Arc<Shared<T>>); |
| 18 | + |
| 19 | +impl<T> Sender<T> { |
| 20 | + pub fn new(value: T) -> Self { |
| 21 | + Self(Arc::new(Shared { |
| 22 | + value: AtomicRefCell::new(State { |
| 23 | + value, |
| 24 | + dropped: false, |
| 25 | + }), |
| 26 | + notify: tokio::sync::Notify::new(), |
| 27 | + })) |
| 28 | + } |
| 29 | + |
| 30 | + pub fn send_if_modified<F>(&self, modify: F) -> bool |
| 31 | + where |
| 32 | + F: FnOnce(&mut T) -> bool, |
| 33 | + { |
| 34 | + let mut state = self.0.value.borrow_mut(); |
| 35 | + let modified = modify(&mut state.value); |
| 36 | + if modified { |
| 37 | + self.0.notify.notify_waiters(); |
| 38 | + } |
| 39 | + modified |
| 40 | + } |
| 41 | + |
| 42 | + pub fn borrow(&self) -> impl Deref<Target = T> + '_ { |
| 43 | + AtomicRef::map(self.0.value.borrow(), |state| &state.value) |
| 44 | + } |
| 45 | + |
| 46 | + pub fn subscribe(&self) -> Receiver<T> { |
| 47 | + Receiver(self.0.clone()) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl<T> Drop for Sender<T> { |
| 52 | + fn drop(&mut self) { |
| 53 | + self.0.value.borrow_mut().dropped = true; |
| 54 | + self.0.notify.notify_waiters(); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl<T> Receiver<T> { |
| 59 | + pub async fn changed(&self) -> Result<(), error::RecvError> { |
| 60 | + self.0.notify.notified().await; |
| 61 | + if self.0.value.borrow().dropped { |
| 62 | + Err(error::RecvError(())) |
| 63 | + } else { |
| 64 | + Ok(()) |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + pub fn borrow(&self) -> impl Deref<Target = T> + '_ { |
| 69 | + AtomicRef::map(self.0.value.borrow(), |state| &state.value) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +pub mod error { |
| 74 | + use std::{error::Error, fmt}; |
| 75 | + |
| 76 | + /// Error produced when receiving a change notification. |
| 77 | + #[derive(Debug, Clone)] |
| 78 | + pub struct RecvError(pub(super) ()); |
| 79 | + |
| 80 | + impl fmt::Display for RecvError { |
| 81 | + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 82 | + write!(fmt, "channel closed") |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + impl Error for RecvError {} |
| 87 | +} |
0 commit comments