Skip to main content

spiritlevel_async/
scdc.rs

1//! The sink-side operations the procedures make, async: [`TmdsScdc`] and its `Send` twin
2//! [`SendTmdsScdc`].
3//!
4//! The counterpart of [`spiritlevel::TmdsScdc`]: the same eight operations, with the same
5//! meaning and the same obligations on an implementation, each an `async fn`. With the
6//! `culvert-async` feature, it is implemented for culvert-async's client.
7
8use crate::{DdcError, ScramblingStatus, SinkTmdsConfig, TmdsConfigReading, UpdateError};
9
10/// The sink's SCDC registers, as the TMDS procedures use them, async.
11///
12/// Each method has the contract of its namesake in [`spiritlevel::TmdsScdc`], whose
13/// documentation says which procedure step makes each call, which register each touches and
14/// what each returns; here the methods are `async`.
15///
16/// # Errors
17///
18/// [`Error`](Self::Error) is a [`DdcError`]: its kind tells the procedures which failures to
19/// poll through and which to stop on, as with the sync trait. An operation made of a read and
20/// a write returns [`UpdateError`], saying which of the two failed.
21///
22/// # Bounded calls
23///
24/// Each call completes in bounded time. The procedures read the cancel flag between calls,
25/// not during one, so a call that never returns (a transfer the bus never finishes) cannot be
26/// cancelled. An implementation bounds its calls and reports a transfer that does not finish
27/// as an error of kind [`DdcErrorKind::Timeout`](crate::DdcErrorKind::Timeout).
28///
29/// # Cancellation
30///
31/// If a call's future is dropped before it completes, whether a write reached the sink is
32/// unknown, and a caller that needs to know reads the register back. The procedures never
33/// drop one: they are stopped through the driver's cancel flag. The clause matters only to
34/// other code that calls the trait.
35///
36/// # `Send`
37///
38/// The futures are not required to be `Send`, so implementations for single-threaded
39/// executors may hold `!Send` state across an `.await`. Code that spawns a procedure on a
40/// multi-threaded executor bounds its SCDC implementation by [`SendTmdsScdc`] instead.
41#[allow(
42    async_fn_in_trait,
43    reason = "the plain trait serves single-threaded executors; Send futures are the twin's, SendTmdsScdc"
44)]
45pub trait TmdsScdc {
46    /// The error of one transfer, classified by [`DdcError::kind`].
47    type Error: DdcError;
48
49    /// See [`spiritlevel::TmdsScdc::write_tmds_config`].
50    async fn write_tmds_config(&mut self, config: SinkTmdsConfig) -> Result<(), Self::Error>;
51
52    /// See [`spiritlevel::TmdsScdc::update_tmds_config`].
53    ///
54    /// # Errors
55    ///
56    /// [`UpdateError::Read`] when the read failed (nothing written), [`UpdateError::Write`]
57    /// when the write failed.
58    async fn update_tmds_config(
59        &mut self,
60        config: SinkTmdsConfig,
61    ) -> Result<(), UpdateError<Self::Error>>;
62
63    /// See [`spiritlevel::TmdsScdc::read_tmds_config`].
64    async fn read_tmds_config(&mut self) -> Result<TmdsConfigReading, Self::Error>;
65
66    /// See [`spiritlevel::TmdsScdc::read_scrambling_status`].
67    async fn read_scrambling_status(&mut self) -> Result<ScramblingStatus, Self::Error>;
68
69    /// See [`spiritlevel::TmdsScdc::read_sink_version`].
70    async fn read_sink_version(&mut self) -> Result<u8, Self::Error>;
71
72    /// See [`spiritlevel::TmdsScdc::write_source_version`].
73    async fn write_source_version(&mut self, version: u8) -> Result<(), Self::Error>;
74
75    /// See [`spiritlevel::TmdsScdc::clear_frl_rate`].
76    async fn clear_frl_rate(&mut self) -> Result<(), Self::Error>;
77
78    /// See [`spiritlevel::TmdsScdc::clear_flt_update`].
79    ///
80    /// # Errors
81    ///
82    /// [`UpdateError::Read`] when the read failed (nothing known, nothing written),
83    /// [`UpdateError::Write`] when the flag was set and the clear failed.
84    async fn clear_flt_update(&mut self) -> Result<bool, UpdateError<Self::Error>>;
85}
86
87/// [`TmdsScdc`] with `Send` futures, for code that spawns TMDS bring-up on a multi-threaded
88/// executor.
89///
90/// The same methods and contract, bounded calls and cancellation included, each returning a
91/// future that is `Send`, and errors that are `Send` too; `Send` is a supertrait, since the
92/// futures borrow the implementation mutably. Every `SendTmdsScdc` is a `TmdsScdc`, through a
93/// blanket implementation, so the driver takes either; a type implements one of the two.
94///
95/// Bound generic code by `SendTmdsScdc` alone: with `S: SendTmdsScdc + TmdsScdc` the
96/// compiler uses the explicit `TmdsScdc` bound instead of the blanket implementation, and the
97/// futures are no longer known to be `Send`. With both traits in scope a method call on a
98/// `SendTmdsScdc` type is ambiguous: import only the trait the code is bounded by, or call
99/// `SendTmdsScdc::read_tmds_config(…)`.
100pub trait SendTmdsScdc: Send {
101    /// The error of one transfer, classified by [`DdcError::kind`].
102    type Error: DdcError + Send;
103
104    /// See [`TmdsScdc::write_tmds_config`].
105    fn write_tmds_config(
106        &mut self,
107        config: SinkTmdsConfig,
108    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
109
110    /// See [`TmdsScdc::update_tmds_config`].
111    fn update_tmds_config(
112        &mut self,
113        config: SinkTmdsConfig,
114    ) -> impl Future<Output = Result<(), UpdateError<Self::Error>>> + Send;
115
116    /// See [`TmdsScdc::read_tmds_config`].
117    fn read_tmds_config(
118        &mut self,
119    ) -> impl Future<Output = Result<TmdsConfigReading, Self::Error>> + Send;
120
121    /// See [`TmdsScdc::read_scrambling_status`].
122    fn read_scrambling_status(
123        &mut self,
124    ) -> impl Future<Output = Result<ScramblingStatus, Self::Error>> + Send;
125
126    /// See [`TmdsScdc::read_sink_version`].
127    fn read_sink_version(&mut self) -> impl Future<Output = Result<u8, Self::Error>> + Send;
128
129    /// See [`TmdsScdc::write_source_version`].
130    fn write_source_version(
131        &mut self,
132        version: u8,
133    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
134
135    /// See [`TmdsScdc::clear_frl_rate`].
136    fn clear_frl_rate(&mut self) -> impl Future<Output = Result<(), Self::Error>> + Send;
137
138    /// See [`TmdsScdc::clear_flt_update`].
139    fn clear_flt_update(
140        &mut self,
141    ) -> impl Future<Output = Result<bool, UpdateError<Self::Error>>> + Send;
142}
143
144impl<T: SendTmdsScdc> TmdsScdc for T {
145    type Error = <T as SendTmdsScdc>::Error;
146
147    fn write_tmds_config(
148        &mut self,
149        config: SinkTmdsConfig,
150    ) -> impl Future<Output = Result<(), Self::Error>> {
151        <T as SendTmdsScdc>::write_tmds_config(self, config)
152    }
153
154    fn update_tmds_config(
155        &mut self,
156        config: SinkTmdsConfig,
157    ) -> impl Future<Output = Result<(), UpdateError<Self::Error>>> {
158        <T as SendTmdsScdc>::update_tmds_config(self, config)
159    }
160
161    fn read_tmds_config(&mut self) -> impl Future<Output = Result<TmdsConfigReading, Self::Error>> {
162        <T as SendTmdsScdc>::read_tmds_config(self)
163    }
164
165    fn read_scrambling_status(
166        &mut self,
167    ) -> impl Future<Output = Result<ScramblingStatus, Self::Error>> {
168        <T as SendTmdsScdc>::read_scrambling_status(self)
169    }
170
171    fn read_sink_version(&mut self) -> impl Future<Output = Result<u8, Self::Error>> {
172        <T as SendTmdsScdc>::read_sink_version(self)
173    }
174
175    fn write_source_version(
176        &mut self,
177        version: u8,
178    ) -> impl Future<Output = Result<(), Self::Error>> {
179        <T as SendTmdsScdc>::write_source_version(self, version)
180    }
181
182    fn clear_frl_rate(&mut self) -> impl Future<Output = Result<(), Self::Error>> {
183        <T as SendTmdsScdc>::clear_frl_rate(self)
184    }
185
186    fn clear_flt_update(&mut self) -> impl Future<Output = Result<bool, UpdateError<Self::Error>>> {
187        <T as SendTmdsScdc>::clear_flt_update(self)
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::DdcErrorKind;
195    use core::pin::pin;
196    use core::task::{Context, Poll, Waker};
197
198    /// Polls a future that completes without waiting, as the doubles' futures do.
199    fn ready<F: Future>(future: F) -> F::Output {
200        let mut cx = Context::from_waker(Waker::noop());
201        match pin!(future).poll(&mut cx) {
202            Poll::Ready(output) => output,
203            Poll::Pending => panic!("the double's future waited"),
204        }
205    }
206
207    /// A call that reached the twin, with its argument.
208    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
209    enum Call {
210        WriteTmdsConfig(SinkTmdsConfig),
211        UpdateTmdsConfig(SinkTmdsConfig),
212        ReadTmdsConfig,
213        ReadScramblingStatus,
214        ReadSinkVersion,
215        WriteSourceVersion(u8),
216        ClearFrlRate,
217        ClearFltUpdate,
218    }
219
220    /// A `SendTmdsScdc` that records each call and answers with fixed values.
221    struct Recorder {
222        calls: [Option<Call>; 8],
223        count: usize,
224    }
225
226    impl Recorder {
227        fn new() -> Self {
228            Self {
229                calls: [None; 8],
230                count: 0,
231            }
232        }
233
234        fn record(&mut self, call: Call) {
235            self.calls[self.count] = Some(call);
236            self.count += 1;
237        }
238    }
239
240    impl SendTmdsScdc for Recorder {
241        type Error = DdcErrorKind;
242
243        async fn write_tmds_config(&mut self, config: SinkTmdsConfig) -> Result<(), Self::Error> {
244            self.record(Call::WriteTmdsConfig(config));
245            Ok(())
246        }
247
248        async fn update_tmds_config(
249            &mut self,
250            config: SinkTmdsConfig,
251        ) -> Result<(), UpdateError<Self::Error>> {
252            self.record(Call::UpdateTmdsConfig(config));
253            Err(UpdateError::Write(DdcErrorKind::Timeout))
254        }
255
256        async fn read_tmds_config(&mut self) -> Result<TmdsConfigReading, Self::Error> {
257            self.record(Call::ReadTmdsConfig);
258            Ok(TmdsConfigReading::new(
259                SinkTmdsConfig::new(true, false),
260                0xF1,
261            ))
262        }
263
264        async fn read_scrambling_status(&mut self) -> Result<ScramblingStatus, Self::Error> {
265            self.record(Call::ReadScramblingStatus);
266            Ok(ScramblingStatus::new(true, 0x81))
267        }
268
269        async fn read_sink_version(&mut self) -> Result<u8, Self::Error> {
270            self.record(Call::ReadSinkVersion);
271            Ok(1)
272        }
273
274        async fn write_source_version(&mut self, version: u8) -> Result<(), Self::Error> {
275            self.record(Call::WriteSourceVersion(version));
276            Err(DdcErrorKind::Detached)
277        }
278
279        async fn clear_frl_rate(&mut self) -> Result<(), Self::Error> {
280            self.record(Call::ClearFrlRate);
281            Ok(())
282        }
283
284        async fn clear_flt_update(&mut self) -> Result<bool, UpdateError<Self::Error>> {
285            self.record(Call::ClearFltUpdate);
286            Ok(true)
287        }
288    }
289
290    /// Every method through the plain trait alone, as the driver calls them.
291    fn exercise<S: TmdsScdc<Error = DdcErrorKind>>(scdc: &mut S) {
292        assert_eq!(
293            ready(scdc.write_tmds_config(SinkTmdsConfig::new(true, true))),
294            Ok(())
295        );
296        assert_eq!(
297            ready(scdc.update_tmds_config(SinkTmdsConfig::new(false, true))),
298            Err(UpdateError::Write(DdcErrorKind::Timeout))
299        );
300        let reading = ready(scdc.read_tmds_config()).unwrap();
301        assert_eq!(
302            (reading.config, reading.raw),
303            (SinkTmdsConfig::new(true, false), 0xF1)
304        );
305        let status = ready(scdc.read_scrambling_status()).unwrap();
306        assert_eq!((status.set, status.raw()), (true, 0x81));
307        assert_eq!(ready(scdc.read_sink_version()), Ok(1));
308        assert_eq!(
309            ready(scdc.write_source_version(1)),
310            Err(DdcErrorKind::Detached)
311        );
312        assert_eq!(ready(scdc.clear_frl_rate()), Ok(()));
313        assert_eq!(ready(scdc.clear_flt_update()), Ok(true));
314    }
315
316    #[test]
317    fn every_call_through_the_plain_trait_reaches_the_twin() {
318        let mut scdc = Recorder::new();
319        exercise(&mut scdc);
320        assert_eq!(
321            scdc.calls,
322            [
323                Some(Call::WriteTmdsConfig(SinkTmdsConfig::new(true, true))),
324                Some(Call::UpdateTmdsConfig(SinkTmdsConfig::new(false, true))),
325                Some(Call::ReadTmdsConfig),
326                Some(Call::ReadScramblingStatus),
327                Some(Call::ReadSinkVersion),
328                Some(Call::WriteSourceVersion(1)),
329                Some(Call::ClearFrlRate),
330                Some(Call::ClearFltUpdate),
331            ]
332        );
333    }
334}