usbdac_core/
async_volume.rs1use crate::{Error, Result, VolumeControl, VolumeState};
3use crossbeam_channel::{bounded, Sender, TrySendError};
4use parking_lot::{Condvar, Mutex};
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::Arc;
8use std::task::{Context, Poll, Waker};
9
10type Job = Box<dyn FnOnce(&VolumeControl) + Send>;
11
12#[derive(Clone)]
17pub struct AsyncVolumeControl {
18 sender: Sender<Job>,
19}
20
21impl AsyncVolumeControl {
22 pub(crate) fn new(control: VolumeControl) -> Result<Self> {
23 let (sender, receiver) = bounded::<Job>(32);
24 std::thread::Builder::new()
25 .name("usbdac-volume".into())
26 .spawn(move || {
27 for job in receiver {
28 job(&control);
29 }
30 })
31 .map_err(|e| Error::Control(format!("starting volume worker: {e}")))?;
32 Ok(Self { sender })
33 }
34
35 fn submit<T: Send + 'static>(
36 &self,
37 operation: impl FnOnce(&VolumeControl) -> Result<T> + Send + 'static,
38 ) -> Result<VolumeOperation<T>> {
39 let shared = Arc::new(Completion {
40 state: Mutex::new((None, None, false)),
41 ready: Condvar::new(),
42 });
43 let completion = Arc::clone(&shared);
44 let job: Job = Box::new(move |control| {
45 let result = operation(control);
46 let waker = {
47 let mut state = completion.state.lock();
48 state.0 = Some(result);
49 state.1.take()
50 };
51 completion.ready.notify_all();
52 if let Some(waker) = waker {
53 waker.wake();
54 }
55 });
56 self.sender.try_send(job).map_err(|error| match error {
57 TrySendError::Full(_) => Error::Busy,
58 TrySendError::Disconnected(_) => Error::InvalidState("volume worker stopped".into()),
59 })?;
60 Ok(VolumeOperation { shared })
61 }
62
63 pub fn get(&self) -> Result<VolumeOperation<VolumeState>> {
64 self.submit(VolumeControl::get)
65 }
66 pub fn set_db(&self, db: f64) -> Result<VolumeOperation<VolumeState>> {
67 self.submit(move |v| v.set_db(db))
68 }
69 pub fn set_fraction(&self, fraction: f64) -> Result<VolumeOperation<VolumeState>> {
70 self.submit(move |v| v.set_fraction(fraction))
71 }
72 pub fn step(&self, direction: i8, steps: u8) -> Result<VolumeOperation<VolumeState>> {
73 self.submit(move |v| v.step(direction, steps))
74 }
75 pub fn set_mute(&self, muted: bool) -> Result<VolumeOperation<VolumeState>> {
76 self.submit(move |v| v.set_mute(muted))
77 }
78 pub fn hand_back(&self) -> Result<VolumeOperation<bool>> {
79 self.submit(VolumeControl::hand_back)
80 }
81}
82
83struct Completion<T> {
84 state: Mutex<(Option<Result<T>>, Option<Waker>, bool)>,
85 ready: Condvar,
86}
87
88#[must_use]
92pub struct VolumeOperation<T> {
93 shared: Arc<Completion<T>>,
94}
95
96impl<T> VolumeOperation<T> {
97 pub fn try_result(&mut self) -> Option<Result<T>> {
98 let mut state = self.shared.state.lock();
99 if state.2 {
100 return Some(Err(consumed()));
101 }
102 let result = state.0.take();
103 if result.is_some() {
104 state.2 = true;
105 }
106 result
107 }
108 pub fn wait(self) -> Result<T> {
110 let mut state = self.shared.state.lock();
111 loop {
112 if state.2 {
113 return Err(consumed());
114 }
115 if let Some(result) = state.0.take() {
116 state.2 = true;
117 return result;
118 }
119 self.shared.ready.wait(&mut state);
120 }
121 }
122}
123
124impl<T> Future for VolumeOperation<T> {
125 type Output = Result<T>;
126 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
127 let mut state = self.shared.state.lock();
128 if state.2 {
129 return Poll::Ready(Err(consumed()));
130 }
131 if let Some(result) = state.0.take() {
132 state.2 = true;
133 Poll::Ready(result)
134 } else {
135 state.1 = Some(context.waker().clone());
136 Poll::Pending
137 }
138 }
139}
140
141fn consumed() -> Error {
142 Error::InvalidState("volume result was already consumed".into())
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148 #[test]
149 fn polling_then_waiting_returns_a_consumed_error() {
150 let mut operation = VolumeOperation {
151 shared: Arc::new(Completion {
152 state: Mutex::new((Some(Ok(7u8)), None, false)),
153 ready: Condvar::new(),
154 }),
155 };
156 assert_eq!(operation.try_result(), Some(Ok(7)));
157 assert!(matches!(operation.wait(), Err(Error::InvalidState(_))));
158 }
159}