/rust/registry/src/index.crates.io-1949cf8c6b5b557f/hyper-1.9.0/src/common/watch.rs
Line | Count | Source |
1 | | //! An SPSC broadcast channel. |
2 | | //! |
3 | | //! - The value can only be a `usize`. |
4 | | //! - The consumer is only notified if the value is different. |
5 | | //! - The value `0` is reserved for closed. |
6 | | |
7 | | use atomic_waker::AtomicWaker; |
8 | | use std::sync::{ |
9 | | atomic::{AtomicUsize, Ordering}, |
10 | | Arc, |
11 | | }; |
12 | | use std::task; |
13 | | |
14 | | type Value = usize; |
15 | | |
16 | | pub(crate) const CLOSED: usize = 0; |
17 | | |
18 | 0 | pub(crate) fn channel(initial: Value) -> (Sender, Receiver) { |
19 | 0 | debug_assert!( |
20 | 0 | initial != CLOSED, |
21 | | "watch::channel initial state of 0 is reserved" |
22 | | ); |
23 | | |
24 | 0 | let shared = Arc::new(Shared { |
25 | 0 | value: AtomicUsize::new(initial), |
26 | 0 | waker: AtomicWaker::new(), |
27 | 0 | }); |
28 | | |
29 | 0 | ( |
30 | 0 | Sender { |
31 | 0 | shared: shared.clone(), |
32 | 0 | }, |
33 | 0 | Receiver { shared }, |
34 | 0 | ) |
35 | 0 | } |
36 | | |
37 | | pub(crate) struct Sender { |
38 | | shared: Arc<Shared>, |
39 | | } |
40 | | |
41 | | pub(crate) struct Receiver { |
42 | | shared: Arc<Shared>, |
43 | | } |
44 | | |
45 | | struct Shared { |
46 | | value: AtomicUsize, |
47 | | waker: AtomicWaker, |
48 | | } |
49 | | |
50 | | impl Sender { |
51 | 0 | pub(crate) fn send(&mut self, value: Value) { |
52 | 0 | if self.shared.value.swap(value, Ordering::SeqCst) != value { |
53 | 0 | self.shared.waker.wake(); |
54 | 0 | } |
55 | 0 | } |
56 | | } |
57 | | |
58 | | impl Drop for Sender { |
59 | 0 | fn drop(&mut self) { |
60 | 0 | self.send(CLOSED); |
61 | 0 | } |
62 | | } |
63 | | |
64 | | impl Receiver { |
65 | 0 | pub(crate) fn load(&mut self, cx: &mut task::Context<'_>) -> Value { |
66 | 0 | self.shared.waker.register(cx.waker()); |
67 | 0 | self.shared.value.load(Ordering::SeqCst) |
68 | 0 | } |
69 | | |
70 | 0 | pub(crate) fn peek(&self) -> Value { |
71 | 0 | self.shared.value.load(Ordering::Relaxed) |
72 | 0 | } |
73 | | } |