Skip to main content

hdmi_hal_async/scdc/
mod.rs

1use crate::ddc::{DdcBus, DdcCapabilities, DdcError, DdcHandle, SCDC, SendDdcBus, SendDdcHandle};
2
3/// Async raw register access to the SCDC register map over DDC/I²C.
4///
5/// This is the async counterpart to `hdmi_hal::scdc::ScdcTransport`, with the same
6/// contract, restated here, and two clauses only async code needs: calls made at the same
7/// time from one task (in [`read_block`](Self::read_block)'s "One transaction") and
8/// [Cancellation](#cancellation).
9///
10/// SCDC is a bidirectional channel used for FRL link training initiation, scrambling
11/// control, and CED (Character Error Detection) reporting. Any code that needs to touch
12/// the SCDC register map does so through this trait.
13///
14/// The trait operates at the raw register level: a one-byte address and a one-byte
15/// value. Typed register wrappers, named constants, and multi-register sequences belong
16/// in the protocol crate, not here.
17///
18/// Every method is required. A transport that can read several registers in one DDC/I²C
19/// transaction implements [`read_block`](Self::read_block) with that transaction; one
20/// that cannot implements it with [`read_block_bytewise`], so the choice is visible in its
21/// code. Here, a bus that can read only one register per transaction:
22///
23/// ```
24/// use core::convert::Infallible;
25/// use hdmi_hal_async::scdc::{ScdcTransport, read_block_bytewise};
26///
27/// /// A bus whose controller reads one register per transaction.
28/// struct OneRegisterBus {
29///     registers: [u8; 256], // stands in for the sink
30/// }
31///
32/// impl ScdcTransport for OneRegisterBus {
33///     type Error = Infallible;
34///
35///     async fn read(&self, reg: u8) -> Result<u8, Infallible> {
36///         Ok(self.registers[reg as usize])
37///     }
38///
39///     async fn write(&mut self, reg: u8, value: u8) -> Result<(), Infallible> {
40///         self.registers[reg as usize] = value;
41///         Ok(())
42///     }
43///
44///     /// One register at a time: not one transaction.
45///     async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), Infallible> {
46///         read_block_bytewise(self, reg, buf).await
47///     }
48/// }
49/// ```
50///
51/// A simulated sink, a register array that holds still while it is read, conforms with a
52/// plain copy of its registers into `buf` instead.
53///
54/// # Errors
55///
56/// After any method returns an error, an implementation should leave the transport usable
57/// for the next call, recovering the bus itself if a transfer failed midway (for example a
58/// held data line after a NACK). One that cannot says so in its documentation: what an
59/// error leaves behind, and how to recover (for example, by constructing the transport
60/// again).
61///
62/// # Cancellation
63///
64/// Any of these futures may be dropped before it completes, for example by a
65/// deadline in the caller. What a dropped call has done is then unknown:
66///
67/// - a dropped [`read`](Self::read) returns no value, and whether its transaction reached
68///   the bus is unknown;
69/// - after a dropped [`read_block`](Self::read_block), the contents of `buf` are
70///   unspecified;
71/// - after a dropped [`write`](Self::write), the write may or may not have reached the
72///   sink, so a caller that needs to know reads the register back.
73///
74/// An implementation should leave the transport usable for the next call, recovering
75/// the bus itself if the transfer was cut short (for example by clearing a held bus
76/// before the next transaction). One that cannot must say so in its documentation: what
77/// a cancelled call leaves behind, and how to recover (for example, by constructing the
78/// transport again).
79///
80/// A caller that needs to stop early can avoid the question: check the deadline or cancel
81/// signal before each call and stop there, rather than dropping a future mid-flight. No
82/// transaction is then cut short, whatever the transport does.
83pub trait ScdcTransport {
84    /// Error type returned by transport operations, classified by [`DdcError::kind`]
85    /// (implemented for [`Infallible`](core::convert::Infallible), `()` and
86    /// [`DdcErrorKind`](crate::ddc::DdcErrorKind)). Over a [`DdcBus`], [`ScdcOverDdc`] is the
87    /// transport.
88    type Error: DdcError;
89
90    /// Read a single byte from the given SCDC register address.
91    async fn read(&self, reg: u8) -> Result<u8, Self::Error>;
92
93    /// Write a single byte to the given SCDC register address.
94    async fn write(&mut self, reg: u8, value: u8) -> Result<(), Self::Error>;
95
96    /// Read consecutive SCDC registers, starting at `reg`, into `buf`.
97    ///
98    /// Related registers, such as the status flags or the character error counters, are
99    /// read together, in one transaction, so that the transport does not split them;
100    /// whether the sink keeps them consistent during that transaction is the sink's
101    /// (see "No snapshot promised"). The contract:
102    ///
103    /// - **What it reads.** `buf[i]` is register `reg + i`.
104    /// - **One transaction.** The whole buffer is read as one combined transfer to the
105    ///   layer below — on the DDC bus, the register offset written, a repeated START,
106    ///   `buf.len()` bytes read, STOP — or an error is returned. An implementation never
107    ///   splits the read into several transfers, and never falls back to one register at
108    ///   a time. Where the layer below is an OS bus driver, the transfer is handed to it
109    ///   whole; a driver known to split it on the wire is named in the transport's
110    ///   documentation, as the bytewise exception is. Calls made at the same time through
111    ///   shared references do not interleave on the bus. That includes calls polled
112    ///   together from one task (`join!`), which reach even a transport that is not
113    ///   `Sync`: an implementation serializes them, waiting for the bus, and never panics
114    ///   (a `RefCell` borrowed across an `.await` would); one that cannot serialize returns
115    ///   an error for the second call instead, and says so. [`read_block_bytewise`] is
116    ///   the one exception to the first two rules, and a transport that uses it says so.
117    /// - **No snapshot promised.** One transaction does not mean the sink returns a
118    ///   consistent snapshot: whether it holds its registers still during a read is up to
119    ///   the sink.
120    /// - **Length limit.** An implementation may have a maximum length, if it documents
121    ///   it, of at least 16 bytes; a longer buffer is an error, not split. A caller that
122    ///   needs a longer read splits it itself — parts of up to 16 bytes fit every
123    ///   conforming transport — knowing the parts are separate transactions.
124    /// - **Empty buffer.** `Ok`, with no bus activity.
125    /// - **On error,** the contents of `buf` are unspecified (see the trait's "Errors" for
126    ///   the transport itself).
127    /// - **Past `0xFF`.** The caller does not read past register `0xFF`. If it does, the
128    ///   result is unspecified, but the call returns, `Ok` or an error, and never panics:
129    ///   [`read_block_bytewise`] wraps to `0x00`; a real burst read leaves it to the sink.
130    async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), Self::Error>;
131}
132
133/// Implements [`ScdcTransport::read_block`] with one [`read`](ScdcTransport::read) per
134/// byte, for a transport that cannot read several registers in one transaction.
135///
136/// This is the documented exception to `read_block`'s "one transaction" rule: each byte
137/// is its own transaction, so a value the sink updates between two of them can be read
138/// half before and half after the update, and another caller's transaction can land in
139/// between. A transport that uses it should say so in its documentation.
140///
141/// Reads stop at the first error, which is returned. An empty buffer reads nothing. A
142/// read past register `0xFF` wraps to `0x00`.
143///
144/// A [`SendScdcTransport`] uses it too: through the blanket implementation, the
145/// transport is an `ScdcTransport`, and the returned future is `Send`.
146pub async fn read_block_bytewise<T: ScdcTransport + ?Sized>(
147    transport: &T,
148    reg: u8,
149    buf: &mut [u8],
150) -> Result<(), T::Error> {
151    let mut addr = reg;
152    for byte in buf {
153        *byte = transport.read(addr).await?;
154        addr = addr.wrapping_add(1);
155    }
156    Ok(())
157}
158
159/// [`ScdcTransport`] with `Send` futures, for code that spawns link training on a
160/// multi-threaded executor.
161///
162/// `ScdcTransport`'s `async fn`s promise nothing about their futures, so code generic over
163/// `T: ScdcTransport` cannot spawn a future that calls them, however `T` is bounded. This
164/// trait has the same methods and contract, each returning a future that is `Send`, and
165/// errors that are `Send` too: a spawned task returns them. Implementations still write
166/// `async fn`; the compiler checks that each future is `Send`.
167///
168/// The transport is `Sync` as well as `Send`: [`read`](Self::read) takes `&self`, and a
169/// future holding `&self` is only `Send` when `Self` is `Sync`. A transport that keeps
170/// interior state for reads uses a `Sync` type for it (an atomic or a lock rather than a
171/// `Cell`).
172///
173/// Every `SendScdcTransport` is an `ScdcTransport`, through a blanket implementation, so
174/// it works with everything written against `ScdcTransport` as well (its `read_block`
175/// included); a type implements one of the two (implementing both conflicts with
176/// the blanket implementation). A `SendScdcTransport` type has both traits' methods, so
177/// with both traits in scope a method call on it is ambiguous: import only the trait the
178/// code is bounded by, or call `SendScdcTransport::read(…)`.
179///
180/// Bound generic code by `SendScdcTransport` alone. Adding `+ ScdcTransport`, which it
181/// implies anyway, makes the compiler use that bound instead of the blanket
182/// implementation, and the futures are no longer known to be `Send`.
183pub trait SendScdcTransport: Send + Sync {
184    /// Error type returned by transport operations, classified by [`DdcError::kind`]. Over a
185    /// [`SendDdcBus`], [`SendScdcOverDdc`] is the transport.
186    type Error: DdcError + Send;
187
188    /// See [`ScdcTransport::read`].
189    fn read(&self, reg: u8) -> impl Future<Output = Result<u8, Self::Error>> + Send;
190
191    /// See [`ScdcTransport::write`].
192    fn write(&mut self, reg: u8, value: u8)
193    -> impl Future<Output = Result<(), Self::Error>> + Send;
194
195    /// See [`ScdcTransport::read_block`], whose contract it has. A transport that cannot
196    /// burst-read implements it with [`read_block_bytewise`]:
197    ///
198    /// ```
199    /// use hdmi_hal_async::scdc::{SendScdcTransport, read_block_bytewise};
200    /// # struct Backend;
201    /// # impl SendScdcTransport for Backend {
202    /// #     type Error = ();
203    /// #     async fn read(&self, _reg: u8) -> Result<u8, ()> { Ok(0) }
204    /// #     async fn write(&mut self, _reg: u8, _value: u8) -> Result<(), ()> { Ok(()) }
205    /// async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), ()> {
206    ///     read_block_bytewise(self, reg, buf).await
207    /// }
208    /// # }
209    /// ```
210    fn read_block(
211        &self,
212        reg: u8,
213        buf: &mut [u8],
214    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
215}
216
217impl<T: SendScdcTransport> ScdcTransport for T {
218    type Error = <T as SendScdcTransport>::Error;
219
220    fn read(&self, reg: u8) -> impl Future<Output = Result<u8, Self::Error>> {
221        <T as SendScdcTransport>::read(self, reg)
222    }
223
224    fn write(&mut self, reg: u8, value: u8) -> impl Future<Output = Result<(), Self::Error>> {
225        <T as SendScdcTransport>::write(self, reg, value)
226    }
227
228    fn read_block(&self, reg: u8, buf: &mut [u8]) -> impl Future<Output = Result<(), Self::Error>> {
229        <T as SendScdcTransport>::read_block(self, reg, buf)
230    }
231}
232
233/// Whether a bus with these capabilities can serve SCDC: reach it, write an offset and a
234/// value, and read `min_read` registers after a one-byte offset in one `write_read`.
235fn serves_scdc(caps: &DdcCapabilities, min_read: u16) -> bool {
236    let (write_part, read_part) = caps.write_read_max();
237    caps.reaches(SCDC) && caps.write_max() >= 2 && write_part >= 1 && read_part >= min_read
238}
239
240/// [`ScdcTransport`] over a [`DdcBus`]: the sink's SCDC at [`SCDC`] (0x54).
241///
242/// The async counterpart to `hdmi_hal::scdc::ScdcOverDdc`, with the same behaviour:
243/// [`read`](ScdcTransport::read) and [`read_block`](ScdcTransport::read_block) are one
244/// [`write_read`](DdcBus::write_read) each, [`write`](ScdcTransport::write) one
245/// [`write`](DdcBus::write); `read_block`'s length limit is the bus's read limit for
246/// `write_read`, and the bus refuses a longer read; constructed with
247/// [`bytewise`](Self::bytewise), `read_block` reads one register per transaction
248/// ([`read_block_bytewise`]). It holds a [`DdcHandle`] to the bus (`&B`, `Rc<B>`, `Arc<B>`,
249/// or a `Copy` view that is its own handle), so other users share the bus. Its errors are
250/// the bus's.
251///
252/// It implements [`ScdcTransport`] only. Code bounded by [`SendScdcTransport`] (for example
253/// a client generic over the `Send` twins) takes [`SendScdcOverDdc`]: one generic type
254/// cannot implement both traits, since `SendScdcTransport`'s blanket implementation
255/// already provides `ScdcTransport`. Over a [`SendDdcBus`], this plain adapter's futures are
256/// still `Send` wherever the compiler sees its concrete type.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub struct ScdcOverDdc<H> {
259    bus: H,
260    bytewise: bool,
261}
262
263impl<H: DdcHandle> ScdcOverDdc<H> {
264    /// SCDC over `bus`, with `read_block` in one transaction; the handle back when the bus
265    /// does not reach [`SCDC`], cannot write an offset and a value, or cannot read 16
266    /// registers after a one-byte offset in one `write_read`.
267    pub fn new(bus: H) -> Result<Self, H> {
268        if serves_scdc(&bus.bus().capabilities(), 16) {
269            Ok(ScdcOverDdc {
270                bus,
271                bytewise: false,
272            })
273        } else {
274            Err(bus)
275        }
276    }
277
278    /// SCDC over `bus`, with `read_block` one register per transaction; the handle back when
279    /// the bus does not reach [`SCDC`], cannot write an offset and a value, or cannot read
280    /// one register after a one-byte offset.
281    pub fn bytewise(bus: H) -> Result<Self, H> {
282        if serves_scdc(&bus.bus().capabilities(), 1) {
283            Ok(ScdcOverDdc {
284                bus,
285                bytewise: true,
286            })
287        } else {
288            Err(bus)
289        }
290    }
291
292    /// Whether `read_block` reads one register per transaction.
293    pub fn is_bytewise(&self) -> bool {
294        self.bytewise
295    }
296
297    /// The bus handle.
298    pub fn into_inner(self) -> H {
299        self.bus
300    }
301}
302
303impl<H: DdcHandle> ScdcTransport for ScdcOverDdc<H> {
304    type Error = <H::Bus as DdcBus>::Error;
305
306    async fn read(&self, reg: u8) -> Result<u8, Self::Error> {
307        let mut value = [0u8];
308        self.bus.bus().write_read(SCDC, &[reg], &mut value).await?;
309        Ok(value[0])
310    }
311
312    async fn write(&mut self, reg: u8, value: u8) -> Result<(), Self::Error> {
313        self.bus.bus().write(SCDC, &[reg, value]).await
314    }
315
316    async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), Self::Error> {
317        if self.bytewise {
318            read_block_bytewise(self, reg, buf).await
319        } else {
320            self.bus.bus().write_read(SCDC, &[reg], buf).await
321        }
322    }
323}
324
325/// [`SendScdcTransport`] over a [`SendDdcBus`]: [`ScdcOverDdc`] for code bounded by the
326/// `Send` twins.
327///
328/// The same behaviour as [`ScdcOverDdc`], implementing [`SendScdcTransport`] (and through
329/// its blanket implementation [`ScdcTransport`]), for a [`SendDdcHandle`]: a `Send + Sync`
330/// handle to a [`SendDdcBus`] (`&B`, `Arc<B>`, or a `Copy` view that is its own handle). A client that requires
331/// `SendScdcTransport` of its transport takes this type.
332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
333pub struct SendScdcOverDdc<H> {
334    bus: H,
335    bytewise: bool,
336}
337
338impl<H: SendDdcHandle> SendScdcOverDdc<H> {
339    /// See [`ScdcOverDdc::new`].
340    pub fn new(bus: H) -> Result<Self, H> {
341        if serves_scdc(&SendDdcBus::capabilities(bus.bus()), 16) {
342            Ok(SendScdcOverDdc {
343                bus,
344                bytewise: false,
345            })
346        } else {
347            Err(bus)
348        }
349    }
350
351    /// See [`ScdcOverDdc::bytewise`].
352    pub fn bytewise(bus: H) -> Result<Self, H> {
353        if serves_scdc(&SendDdcBus::capabilities(bus.bus()), 1) {
354            Ok(SendScdcOverDdc {
355                bus,
356                bytewise: true,
357            })
358        } else {
359            Err(bus)
360        }
361    }
362
363    /// Whether `read_block` reads one register per transaction.
364    pub fn is_bytewise(&self) -> bool {
365        self.bytewise
366    }
367
368    /// The bus handle.
369    pub fn into_inner(self) -> H {
370        self.bus
371    }
372}
373
374impl<H: SendDdcHandle> SendScdcTransport for SendScdcOverDdc<H> {
375    type Error = <H::Bus as SendDdcBus>::Error;
376
377    async fn read(&self, reg: u8) -> Result<u8, Self::Error> {
378        let mut value = [0u8];
379        SendDdcBus::write_read(self.bus.bus(), SCDC, &[reg], &mut value).await?;
380        Ok(value[0])
381    }
382
383    async fn write(&mut self, reg: u8, value: u8) -> Result<(), Self::Error> {
384        SendDdcBus::write(self.bus.bus(), SCDC, &[reg, value]).await
385    }
386
387    async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), Self::Error> {
388        if self.bytewise {
389            read_block_bytewise(self, reg, buf).await
390        } else {
391            SendDdcBus::write_read(self.bus.bus(), SCDC, &[reg], buf).await
392        }
393    }
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399    use core::cell::Cell;
400    use core::sync::atomic::{AtomicU32, Ordering};
401
402    /// A failed read, carrying its register.
403    #[derive(Debug, Clone, Copy, PartialEq)]
404    struct Fail(u8);
405
406    impl DdcError for Fail {
407        fn kind(&self) -> crate::ddc::DdcErrorKind {
408            crate::ddc::DdcErrorKind::Other
409        }
410    }
411
412    struct MockTransport {
413        registers: [u8; 256],
414        reads: Cell<u32>,
415        fail_at: Option<u8>,
416    }
417
418    impl MockTransport {
419        fn new() -> Self {
420            Self {
421                registers: [0u8; 256],
422                reads: Cell::new(0),
423                fail_at: None,
424            }
425        }
426
427        /// A transport whose every register holds its own address.
428        fn filled() -> Self {
429            let mut t = Self::new();
430            for (i, r) in t.registers.iter_mut().enumerate() {
431                *r = i as u8;
432            }
433            t
434        }
435    }
436
437    impl ScdcTransport for MockTransport {
438        type Error = Fail;
439
440        async fn read(&self, reg: u8) -> Result<u8, Self::Error> {
441            if self.fail_at == Some(reg) {
442                return Err(Fail(reg));
443            }
444            self.reads.set(self.reads.get() + 1);
445            Ok(self.registers[reg as usize])
446        }
447
448        async fn write(&mut self, reg: u8, value: u8) -> Result<(), Self::Error> {
449            self.registers[reg as usize] = value;
450            Ok(())
451        }
452
453        async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), Self::Error> {
454            read_block_bytewise(self, reg, buf).await
455        }
456    }
457
458    #[pollster::test]
459    async fn write_then_read_returns_written_value() {
460        let mut t = MockTransport::new();
461        t.write(0x20, 0xAB).await.unwrap();
462        assert_eq!(t.read(0x20).await.unwrap(), 0xAB);
463    }
464
465    #[pollster::test]
466    async fn unwritten_register_reads_zero() {
467        let t = MockTransport::new();
468        assert_eq!(t.read(0x31).await.unwrap(), 0x00);
469    }
470
471    #[pollster::test]
472    async fn write_is_register_specific() {
473        let mut t = MockTransport::new();
474        t.write(0x01, 0xFF).await.unwrap();
475        assert_eq!(t.read(0x00).await.unwrap(), 0x00);
476        assert_eq!(t.read(0x02).await.unwrap(), 0x00);
477    }
478
479    #[pollster::test]
480    async fn write_overwrites_previous_value() {
481        let mut t = MockTransport::new();
482        t.write(0x20, 0x01).await.unwrap();
483        t.write(0x20, 0x02).await.unwrap();
484        assert_eq!(t.read(0x20).await.unwrap(), 0x02);
485    }
486
487    #[pollster::test]
488    async fn bytewise_reads_consecutive_registers() {
489        let t = MockTransport::filled();
490        let mut buf = [0u8; 3];
491        t.read_block(0x40, &mut buf).await.unwrap();
492        assert_eq!(buf, [0x40, 0x41, 0x42]);
493        assert_eq!(t.reads.get(), 3);
494    }
495
496    #[pollster::test]
497    async fn bytewise_empty_buffer_reads_nothing() {
498        let t = MockTransport::filled();
499        t.read_block(0x40, &mut []).await.unwrap();
500        assert_eq!(t.reads.get(), 0);
501    }
502
503    #[pollster::test]
504    async fn bytewise_stops_at_first_error() {
505        let mut t = MockTransport::filled();
506        t.fail_at = Some(0x41);
507        let mut buf = [0u8; 3];
508        assert_eq!(t.read_block(0x40, &mut buf).await, Err(Fail(0x41)));
509        assert_eq!(buf, [0x40, 0x00, 0x00]);
510        assert_eq!(t.reads.get(), 1);
511    }
512
513    #[pollster::test]
514    async fn bytewise_wraps_past_0xff() {
515        let t = MockTransport::filled();
516        let mut buf = [0u8; 2];
517        t.read_block(0xFF, &mut buf).await.unwrap();
518        assert_eq!(buf, [0xFF, 0x00]);
519    }
520
521    #[pollster::test]
522    async fn write_then_read_block() {
523        let mut t = MockTransport::new();
524        t.write(0x20, 0xAB).await.unwrap();
525        let mut buf = [0u8; 1];
526        t.read_block(0x20, &mut buf).await.unwrap();
527        assert_eq!(buf, [0xAB]);
528    }
529
530    /// Implements only the `Send` twin, with `read_block` through `read_block_bytewise`.
531    /// Counts reads in an atomic, since the twin needs `Sync`.
532    struct SendMockTransport {
533        registers: [u8; 256],
534        reads: AtomicU32,
535        fail_at: Option<u8>,
536    }
537
538    impl SendMockTransport {
539        fn filled() -> Self {
540            let mut registers = [0u8; 256];
541            for (i, r) in registers.iter_mut().enumerate() {
542                *r = i as u8;
543            }
544            Self {
545                registers,
546                reads: AtomicU32::new(0),
547                fail_at: None,
548            }
549        }
550
551        fn reads(&self) -> u32 {
552            self.reads.load(Ordering::Relaxed)
553        }
554    }
555
556    impl SendScdcTransport for SendMockTransport {
557        type Error = Fail;
558
559        async fn read(&self, reg: u8) -> Result<u8, Self::Error> {
560            if self.fail_at == Some(reg) {
561                return Err(Fail(reg));
562            }
563            self.reads.fetch_add(1, Ordering::Relaxed);
564            Ok(self.registers[reg as usize])
565        }
566
567        async fn write(&mut self, reg: u8, value: u8) -> Result<(), Self::Error> {
568            self.registers[reg as usize] = value;
569            Ok(())
570        }
571
572        async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), Self::Error> {
573            read_block_bytewise(self, reg, buf).await
574        }
575    }
576
577    /// A `Send` twin generic over another, with `read_block` through `read_block_bytewise`:
578    /// it compiles only if the helper's future is `Send` for every `T: SendScdcTransport`,
579    /// not only for a concrete type.
580    struct Forwarding<T>(T);
581
582    impl<T: SendScdcTransport> SendScdcTransport for Forwarding<T> {
583        type Error = T::Error;
584
585        async fn read(&self, reg: u8) -> Result<u8, Self::Error> {
586            SendScdcTransport::read(&self.0, reg).await
587        }
588
589        async fn write(&mut self, reg: u8, value: u8) -> Result<(), Self::Error> {
590            SendScdcTransport::write(&mut self.0, reg, value).await
591        }
592
593        async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), Self::Error> {
594            read_block_bytewise(self, reg, buf).await
595        }
596    }
597
598    /// Implements only the `Send` twin with its own `read_block`, as a transport that
599    /// reads a block in one transaction does.
600    struct BlockReadingTransport;
601
602    impl SendScdcTransport for BlockReadingTransport {
603        type Error = ();
604
605        async fn read(&self, _reg: u8) -> Result<u8, Self::Error> {
606            Err(())
607        }
608
609        async fn write(&mut self, _reg: u8, _value: u8) -> Result<(), Self::Error> {
610            Err(())
611        }
612
613        async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), Self::Error> {
614            buf.fill(reg);
615            Ok(())
616        }
617    }
618
619    /// Writes, then reads back one register and a block, through `ScdcTransport`, as code
620    /// written against the plain trait does.
621    async fn round_trip_plain<T: ScdcTransport>(
622        t: &mut T,
623        buf: &mut [u8],
624    ) -> (
625        Result<(), T::Error>,
626        Result<u8, T::Error>,
627        Result<(), T::Error>,
628    ) {
629        let written = t.write(0x20, 0xAB).await;
630        let read = t.read(0x20).await;
631        let block = t.read_block(0x20, buf).await;
632        (written, read, block)
633    }
634
635    /// The compiler proves this `Send` bound for every `T: SendScdcTransport`, not only
636    /// for the mock; with `ScdcTransport` in its place it would not compile.
637    fn spawnable<'a, T: SendScdcTransport>(
638        t: &'a T,
639        buf: &'a mut [u8],
640    ) -> impl Future<Output = Result<(), T::Error>> + Send + 'a {
641        SendScdcTransport::read_block(t, 0x40, buf)
642    }
643
644    fn assert_send<T: Send>(value: T) -> T {
645        value
646    }
647
648    #[pollster::test]
649    async fn send_twin_is_usable_as_scdc_transport() {
650        let mut t = SendMockTransport::filled();
651        let mut buf = [0u8; 2];
652        let (written, read, block) = round_trip_plain(&mut t, &mut buf).await;
653        assert_eq!((written, read, block), (Ok(()), Ok(0xAB), Ok(())));
654        assert_eq!(buf, [0xAB, 0x21]);
655        assert_eq!(t.reads(), 3);
656    }
657
658    #[pollster::test]
659    async fn send_twin_futures_are_send_in_generic_code() {
660        let t = SendMockTransport::filled();
661        let mut buf = [0u8; 3];
662        assert_send(spawnable(&t, &mut buf)).await.unwrap();
663        assert_eq!(buf, [0x40, 0x41, 0x42]);
664    }
665
666    #[pollster::test]
667    async fn bytewise_through_a_generic_send_twin() {
668        let mut t = Forwarding(SendMockTransport::filled());
669        let mut buf = [0u8; 2];
670        assert_send(spawnable(&t, &mut buf)).await.unwrap();
671        assert_eq!(buf, [0x40, 0x41]);
672        assert_eq!(t.0.reads(), 2);
673        // And through the plain trait, as code written against `ScdcTransport` uses it.
674        let (written, read, block) = round_trip_plain(&mut t, &mut buf).await;
675        assert_eq!((written, read, block), (Ok(()), Ok(0xAB), Ok(())));
676        assert_eq!(buf, [0xAB, 0x21]);
677    }
678
679    #[pollster::test]
680    async fn bytewise_on_an_unsized_transport() {
681        // `?Sized`: `ScdcTransport` has `async fn`s, so it has no `dyn` form, but a
682        // transport can still be unsized, here one whose registers are a slice.
683        struct Regs<R: ?Sized>(R);
684        impl ScdcTransport for Regs<[u8]> {
685            type Error = ();
686            async fn read(&self, reg: u8) -> Result<u8, ()> {
687                self.0.get(reg as usize).copied().ok_or(())
688            }
689            async fn write(&mut self, _reg: u8, _value: u8) -> Result<(), ()> {
690                Err(())
691            }
692            async fn read_block(&self, reg: u8, buf: &mut [u8]) -> Result<(), ()> {
693                read_block_bytewise(self, reg, buf).await
694            }
695        }
696        let t: &mut Regs<[u8]> = &mut Regs([0x10, 0x11, 0x12]);
697        let mut buf = [0u8; 2];
698        read_block_bytewise(t, 0x01, &mut buf).await.unwrap();
699        assert_eq!(buf, [0x11, 0x12]);
700        assert_eq!(t.read_block(0x02, &mut buf).await, Err(()));
701        assert_eq!(t.write(0x00, 0xAB).await, Err(()));
702    }
703
704    #[pollster::test]
705    async fn send_twin_bytewise_stops_at_first_error() {
706        let mut t = SendMockTransport::filled();
707        t.fail_at = Some(0x41);
708        let mut buf = [0u8; 3];
709        assert_eq!(
710            SendScdcTransport::read_block(&t, 0x40, &mut buf).await,
711            Err(Fail(0x41))
712        );
713        assert_eq!(buf, [0x40, 0x00, 0x00]);
714        assert_eq!(t.reads(), 1);
715    }
716
717    #[pollster::test]
718    async fn send_twin_bytewise_wraps_past_0xff() {
719        let t = SendMockTransport::filled();
720        let mut buf = [0u8; 2];
721        SendScdcTransport::read_block(&t, 0xFF, &mut buf)
722            .await
723            .unwrap();
724        assert_eq!(buf, [0xFF, 0x00]);
725    }
726
727    #[pollster::test]
728    async fn send_twin_read_block_is_used_through_scdc_transport() {
729        let mut t = BlockReadingTransport;
730        let mut buf = [0u8; 2];
731        let (written, read, block) = round_trip_plain(&mut t, &mut buf).await;
732        assert_eq!((written, read, block), (Err(()), Err(()), Ok(())));
733        assert_eq!(buf, [0x20, 0x20]);
734    }
735
736    extern crate alloc;
737    use crate::ddc::{DdcErrorKind, EddcTarget};
738    use alloc::rc::Rc;
739    use alloc::sync::Arc;
740    use core::sync::atomic::AtomicU8;
741
742    /// A `Send` DDC bus over an SCDC register file, counting transactions.
743    struct Bus {
744        caps: DdcCapabilities,
745        registers: [AtomicU8; 256],
746        write_reads: AtomicU32,
747        fail: Option<DdcErrorKind>,
748    }
749
750    impl Bus {
751        fn scdc(read_limit: u16) -> Self {
752            Self::with(
753                DdcCapabilities::none()
754                    .with_address_reachable(SCDC, true)
755                    .with_write_max(2)
756                    .with_write_read_max(1, read_limit),
757            )
758        }
759
760        fn with(caps: DdcCapabilities) -> Self {
761            Bus {
762                caps,
763                registers: core::array::from_fn(|i| AtomicU8::new(i as u8)),
764                write_reads: AtomicU32::new(0),
765                fail: None,
766            }
767        }
768    }
769
770    impl SendDdcBus for Bus {
771        type Error = DdcErrorKind;
772
773        fn capabilities(&self) -> DdcCapabilities {
774            self.caps
775        }
776
777        async fn write(&self, _addr: u8, bytes: &[u8]) -> Result<(), DdcErrorKind> {
778            if let Some(kind) = self.fail {
779                return Err(kind);
780            }
781            self.registers[usize::from(bytes[0])].store(bytes[1], Ordering::Relaxed);
782            Ok(())
783        }
784
785        async fn write_read(
786            &self,
787            _addr: u8,
788            bytes: &[u8],
789            buf: &mut [u8],
790        ) -> Result<(), DdcErrorKind> {
791            if let Some(kind) = self.fail {
792                return Err(kind);
793            }
794            if buf.len() > usize::from(self.caps.write_read_max().1) {
795                return Err(DdcErrorKind::Unsupported);
796            }
797            self.write_reads.fetch_add(1, Ordering::Relaxed);
798            for (i, b) in buf.iter_mut().enumerate() {
799                let reg = usize::from(bytes[0].wrapping_add(i as u8));
800                *b = self.registers[reg].load(Ordering::Relaxed);
801            }
802            Ok(())
803        }
804
805        async fn read(&self, _addr: u8, _buf: &mut [u8]) -> Result<(), DdcErrorKind> {
806            Err(DdcErrorKind::Unsupported)
807        }
808
809        async fn read_segmented(
810            &self,
811            _: EddcTarget,
812            _: u8,
813            _: u8,
814            _: &mut [u8],
815        ) -> Result<(), DdcErrorKind> {
816            Err(DdcErrorKind::Unsupported)
817        }
818    }
819
820    /// A client that requires `SendScdcTransport` of its transport, as a client generic over
821    /// the `Send` twins does.
822    struct SendClient<T>(T);
823
824    impl<T: SendScdcTransport> SendClient<T> {
825        fn update_flags(&self) -> impl Future<Output = Result<u8, T::Error>> + Send + '_ {
826            SendScdcTransport::read(&self.0, 0x10)
827        }
828    }
829
830    #[pollster::test]
831    async fn plain_adapter_reads_and_writes_at_0x54() {
832        let bus = Bus::scdc(32);
833        let mut scdc = ScdcOverDdc::new(&bus).ok().unwrap();
834        assert!(!scdc.is_bytewise());
835        scdc.write(0x20, 0x03).await.unwrap();
836        assert_eq!(scdc.read(0x20).await, Ok(0x03));
837        let mut ced = [0u8; 7];
838        scdc.read_block(0x50, &mut ced).await.unwrap();
839        assert_eq!(ced, [0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56]);
840        assert_eq!(bus.write_reads.load(Ordering::Relaxed), 2);
841        assert!(core::ptr::eq(scdc.into_inner(), &bus));
842    }
843
844    #[pollster::test]
845    async fn plain_adapter_bytewise_and_errors() {
846        let bus = Bus::scdc(1);
847        assert!(ScdcOverDdc::new(&bus).is_err());
848        let scdc = ScdcOverDdc::bytewise(&bus).ok().unwrap();
849        assert!(scdc.is_bytewise());
850        let mut buf = [0u8; 3];
851        scdc.read_block(0x40, &mut buf).await.unwrap();
852        assert_eq!(buf, [0x40, 0x41, 0x42]);
853        assert_eq!(bus.write_reads.load(Ordering::Relaxed), 3);
854
855        let mut failing = Bus::scdc(32);
856        failing.fail = Some(DdcErrorKind::Busy);
857        let mut scdc = ScdcOverDdc::new(&failing).ok().unwrap();
858        assert_eq!(scdc.read(0x21).await, Err(DdcErrorKind::Busy));
859        assert_eq!(scdc.write(0x30, 0x01).await, Err(DdcErrorKind::Busy));
860    }
861
862    #[pollster::test]
863    async fn plain_adapter_leaves_reads_beyond_the_bus_limit_to_the_bus() {
864        let bus = Bus::scdc(16);
865        let scdc = ScdcOverDdc::new(&bus).ok().unwrap();
866        let mut long = [0u8; 17];
867        assert_eq!(
868            scdc.read_block(0x00, &mut long).await,
869            Err(DdcErrorKind::Unsupported)
870        );
871    }
872
873    #[pollster::test]
874    async fn adapters_refuse_a_bus_that_cannot_serve_scdc() {
875        let no_scdc = Arc::new(Bus::with(
876            DdcCapabilities::general().with_address_reachable(SCDC, false),
877        ));
878        assert!(ScdcOverDdc::new(&*no_scdc).is_err());
879        assert!(SendScdcOverDdc::new(Arc::clone(&no_scdc)).is_err());
880        assert!(SendScdcOverDdc::bytewise(Arc::clone(&no_scdc)).is_err());
881        let short_reads = Arc::new(Bus::scdc(15));
882        assert!(SendScdcOverDdc::new(Arc::clone(&short_reads)).is_err());
883        assert!(SendScdcOverDdc::bytewise(short_reads).is_ok());
884        let no_reads = Bus::scdc(0);
885        assert!(ScdcOverDdc::bytewise(&no_reads).is_err());
886        let mut buf = [0u8; 1];
887        assert_eq!(
888            SendDdcBus::read(&no_reads, SCDC, &mut buf).await,
889            Err(DdcErrorKind::Unsupported)
890        );
891        assert_eq!(
892            SendDdcBus::read_segmented(&no_reads, EddcTarget::Edid, 0, 0, &mut buf).await,
893            Err(DdcErrorKind::Unsupported)
894        );
895        assert_eq!(Fail(0).kind(), DdcErrorKind::Other);
896    }
897
898    /// Generic over every `SendDdcBus`: the client bounded by `SendScdcTransport` takes the
899    /// `Send` adapter over an `Arc`, and its future is `Send`.
900    fn spawn_client<B: SendDdcBus + 'static>(
901        bus: Arc<B>,
902    ) -> impl Future<Output = Result<u8, B::Error>> + Send {
903        let client = SendClient(SendScdcOverDdc::new(bus).ok().expect("serves SCDC"));
904        async move { client.update_flags().await }
905    }
906
907    #[pollster::test]
908    async fn send_adapter_serves_a_client_bounded_by_the_send_twin() {
909        let bus = Arc::new(Bus::scdc(32));
910        assert_eq!(assert_send(spawn_client(Arc::clone(&bus))).await, Ok(0x10));
911
912        let mut scdc = SendScdcOverDdc::bytewise(Arc::clone(&bus)).ok().unwrap();
913        assert!(scdc.is_bytewise());
914        SendScdcTransport::write(&mut scdc, 0x20, 0x07)
915            .await
916            .unwrap();
917        let mut buf = [0u8; 2];
918        SendScdcTransport::read_block(&scdc, 0x20, &mut buf)
919            .await
920            .unwrap();
921        assert_eq!(buf, [0x07, 0x21]);
922        let whole = SendScdcOverDdc::new(Arc::clone(&bus)).ok().unwrap();
923        assert!(!whole.is_bytewise());
924        SendScdcTransport::read_block(&whole, 0x20, &mut buf)
925            .await
926            .unwrap();
927        assert!(Arc::ptr_eq(&scdc.into_inner(), &bus));
928        assert!(Arc::ptr_eq(&whole.into_inner(), &bus));
929    }
930
931    /// A firmware-style bus that is not `Send`.
932    struct LocalBus(Cell<u8>, DdcCapabilities);
933
934    impl DdcBus for LocalBus {
935        type Error = ();
936        fn capabilities(&self) -> DdcCapabilities {
937            self.1
938        }
939        async fn write(&self, _addr: u8, bytes: &[u8]) -> Result<(), ()> {
940            self.0.set(bytes[1]);
941            Ok(())
942        }
943        async fn write_read(&self, _addr: u8, _bytes: &[u8], buf: &mut [u8]) -> Result<(), ()> {
944            buf.fill(self.0.get());
945            Ok(())
946        }
947        async fn read(&self, _addr: u8, _buf: &mut [u8]) -> Result<(), ()> {
948            Err(())
949        }
950        async fn read_segmented(
951            &self,
952            _: EddcTarget,
953            _: u8,
954            _: u8,
955            _: &mut [u8],
956        ) -> Result<(), ()> {
957            Err(())
958        }
959    }
960
961    #[pollster::test]
962    async fn plain_adapter_shares_a_bus_that_is_not_send() {
963        let serves = DdcCapabilities::none()
964            .with_address_reachable(SCDC, true)
965            .with_write_max(2)
966            .with_write_read_max(1, 16);
967        let refused = Rc::new(LocalBus(Cell::new(0), DdcCapabilities::none()));
968        assert!(ScdcOverDdc::new(refused).is_err());
969        let bus = Rc::new(LocalBus(Cell::new(0), serves));
970        let mut scdc = ScdcOverDdc::new(Rc::clone(&bus)).ok().unwrap();
971        scdc.write(0x20, 0x05).await.unwrap();
972        assert_eq!(scdc.read(0x20).await, Ok(0x05));
973        let mut buf = [0u8; 1];
974        assert_eq!(bus.read(SCDC, &mut buf).await, Err(()));
975        assert_eq!(
976            bus.read_segmented(EddcTarget::Edid, 0, 0, &mut buf).await,
977            Err(())
978        );
979    }
980
981    /// A `Copy` view of the test bus that is its own handle.
982    #[derive(Clone, Copy)]
983    struct View<'a>(&'a Bus);
984
985    impl SendDdcBus for View<'_> {
986        type Error = DdcErrorKind;
987        fn capabilities(&self) -> DdcCapabilities {
988            SendDdcBus::capabilities(self.0)
989        }
990        async fn write(&self, addr: u8, bytes: &[u8]) -> Result<(), DdcErrorKind> {
991            SendDdcBus::write(self.0, addr, bytes).await
992        }
993        async fn write_read(
994            &self,
995            addr: u8,
996            bytes: &[u8],
997            buf: &mut [u8],
998        ) -> Result<(), DdcErrorKind> {
999            SendDdcBus::write_read(self.0, addr, bytes, buf).await
1000        }
1001        async fn read(&self, addr: u8, buf: &mut [u8]) -> Result<(), DdcErrorKind> {
1002            SendDdcBus::read(self.0, addr, buf).await
1003        }
1004        async fn read_segmented(
1005            &self,
1006            target: crate::ddc::EddcTarget,
1007            segment: u8,
1008            offset: u8,
1009            buf: &mut [u8],
1010        ) -> Result<(), DdcErrorKind> {
1011            SendDdcBus::read_segmented(self.0, target, segment, offset, buf).await
1012        }
1013    }
1014
1015    impl DdcHandle for View<'_> {
1016        type Bus = Self;
1017        fn bus(&self) -> &Self {
1018            self
1019        }
1020    }
1021
1022    impl SendDdcHandle for View<'_> {
1023        type Bus = Self;
1024        fn bus(&self) -> &Self {
1025            self
1026        }
1027    }
1028
1029    #[pollster::test]
1030    async fn both_adapters_take_a_copy_handle_by_value() {
1031        let bus = Bus::scdc(32);
1032        let view = View(&bus);
1033        let plain = ScdcOverDdc::new(view).ok().unwrap();
1034        assert_eq!(ScdcTransport::read(&plain, 0x07).await, Ok(0x07));
1035        let send = SendScdcOverDdc::new(view).ok().unwrap();
1036        assert_eq!(SendScdcTransport::read(&send, 0x08).await, Ok(0x08));
1037        // A reference handle still works.
1038        let by_ref = SendScdcOverDdc::new(&bus).ok().unwrap();
1039        assert_eq!(SendScdcTransport::read(&by_ref, 0x09).await, Ok(0x09));
1040        // The view forwards every call to its bus.
1041        assert_eq!(
1042            SendDdcBus::write(&view, SCDC, &[0x30, 0x01]).await,
1043            SendDdcBus::write(&bus, SCDC, &[0x30, 0x01]).await
1044        );
1045        let (mut through_view, mut direct) = ([0u8; 1], [0u8; 1]);
1046        assert_eq!(
1047            SendDdcBus::read(&view, SCDC, &mut through_view).await,
1048            SendDdcBus::read(&bus, SCDC, &mut direct).await
1049        );
1050        assert_eq!(
1051            SendDdcBus::read_segmented(&view, EddcTarget::Edid, 0, 0, &mut through_view).await,
1052            SendDdcBus::read_segmented(&bus, EddcTarget::Edid, 0, 0, &mut direct).await
1053        );
1054        assert_eq!(through_view, direct);
1055    }
1056}