Skip to main content

hazard3_sync/
pipe.rs

1//! Async byte stream pipe.
2
3use core::cell::{RefCell, UnsafeCell};
4use core::convert::Infallible;
5use core::future::{Future, poll_fn};
6use core::ops::Range;
7use core::pin::Pin;
8use core::task::{Context, Poll};
9
10use crate::blocking_mutex::Mutex;
11use crate::blocking_mutex::raw::RawMutex;
12use crate::ring_buffer::RingBuffer;
13use crate::waitqueue::WakerRegistration;
14
15/// Write-only access to a [`Pipe`].
16#[derive(Debug)]
17pub struct Writer<'p, M, const N: usize>
18where
19    M: RawMutex,
20{
21    pipe: &'p Pipe<M, N>,
22}
23
24impl<'p, M, const N: usize> Clone for Writer<'p, M, N>
25where
26    M: RawMutex,
27{
28    fn clone(&self) -> Self {
29        *self
30    }
31}
32
33impl<'p, M, const N: usize> Copy for Writer<'p, M, N> where M: RawMutex {}
34
35impl<'p, M, const N: usize> Writer<'p, M, N>
36where
37    M: RawMutex,
38{
39    /// Write some bytes to the pipe.
40    ///
41    /// See [`Pipe::write()`]
42    pub fn write<'a>(&'a self, buf: &'a [u8]) -> WriteFuture<'a, M, N> {
43        self.pipe.write(buf)
44    }
45
46    /// Write all bytes to the pipe.
47    ///
48    /// This method writes all bytes from `buf` into the pipe. See [`Pipe::write_all()`]
49    pub async fn write_all<'a>(&'a self, buf: &'a [u8]) {
50        self.pipe.write_all(buf).await;
51    }
52
53    /// Attempt to immediately write some bytes to the pipe.
54    ///
55    /// See [`Pipe::try_write()`]
56    pub fn try_write(&self, buf: &[u8]) -> Result<usize, TryWriteError> {
57        self.pipe.try_write(buf)
58    }
59}
60
61/// Future returned by [`Pipe::write`] and  [`Writer::write`].
62#[must_use = "futures do nothing unless you `.await` or poll them"]
63#[derive(Debug)]
64pub struct WriteFuture<'p, M, const N: usize>
65where
66    M: RawMutex,
67{
68    pipe: &'p Pipe<M, N>,
69    buf: &'p [u8],
70}
71
72impl<'p, M, const N: usize> Future for WriteFuture<'p, M, N>
73where
74    M: RawMutex,
75{
76    type Output = usize;
77
78    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
79        match self.pipe.try_write_with_context(Some(cx), self.buf) {
80            Ok(n) => Poll::Ready(n),
81            Err(TryWriteError::Full) => Poll::Pending,
82        }
83    }
84}
85
86impl<'p, M, const N: usize> Unpin for WriteFuture<'p, M, N> where M: RawMutex {}
87
88/// Read-only access to a [`Pipe`].
89#[derive(Debug)]
90pub struct Reader<'p, M, const N: usize>
91where
92    M: RawMutex,
93{
94    pipe: &'p Pipe<M, N>,
95}
96
97impl<'p, M, const N: usize> Reader<'p, M, N>
98where
99    M: RawMutex,
100{
101    /// Read some bytes from the pipe.
102    ///
103    /// See [`Pipe::read()`]
104    pub fn read<'a>(&'a self, buf: &'a mut [u8]) -> ReadFuture<'a, M, N> {
105        self.pipe.read(buf)
106    }
107
108    /// Attempt to immediately read some bytes from the pipe.
109    ///
110    /// See [`Pipe::try_read()`]
111    pub fn try_read(&self, buf: &mut [u8]) -> Result<usize, TryReadError> {
112        self.pipe.try_read(buf)
113    }
114
115    /// Return the contents of the internal buffer, filling it with more data from the inner reader if it is empty.
116    ///
117    /// If no bytes are currently available to read, this function waits until at least one byte is available.
118    ///
119    /// If the reader is at end-of-file (EOF), an empty slice is returned.
120    pub fn fill_buf(&mut self) -> FillBufFuture<'_, M, N> {
121        FillBufFuture { pipe: Some(self.pipe) }
122    }
123
124    /// Try returning contents of the internal buffer.
125    ///
126    /// If no bytes are currently available to read, this function returns `Err(TryReadError::Empty)`.
127    ///
128    /// If the reader is at end-of-file (EOF), an empty slice is returned.
129    pub fn try_fill_buf(&mut self) -> Result<&[u8], TryReadError> {
130        unsafe { self.pipe.try_fill_buf_with_context(None) }
131    }
132
133    /// Tell this buffer that `amt` bytes have been consumed from the buffer, so they should no longer be returned in calls to `fill_buf`.
134    pub fn consume(&mut self, amt: usize) {
135        self.pipe.consume(amt)
136    }
137}
138
139/// Future returned by [`Pipe::read`] and  [`Reader::read`].
140#[must_use = "futures do nothing unless you `.await` or poll them"]
141#[derive(Debug)]
142pub struct ReadFuture<'p, M, const N: usize>
143where
144    M: RawMutex,
145{
146    pipe: &'p Pipe<M, N>,
147    buf: &'p mut [u8],
148}
149
150impl<'p, M, const N: usize> Future for ReadFuture<'p, M, N>
151where
152    M: RawMutex,
153{
154    type Output = usize;
155
156    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
157        match self.pipe.try_read_with_context(Some(cx), self.buf) {
158            Ok(n) => Poll::Ready(n),
159            Err(TryReadError::Empty) => Poll::Pending,
160        }
161    }
162}
163
164impl<'p, M, const N: usize> Unpin for ReadFuture<'p, M, N> where M: RawMutex {}
165
166/// Future returned by [`Reader::fill_buf`].
167#[must_use = "futures do nothing unless you `.await` or poll them"]
168#[derive(Debug)]
169pub struct FillBufFuture<'p, M, const N: usize>
170where
171    M: RawMutex,
172{
173    pipe: Option<&'p Pipe<M, N>>,
174}
175
176impl<'p, M, const N: usize> Future for FillBufFuture<'p, M, N>
177where
178    M: RawMutex,
179{
180    type Output = &'p [u8];
181
182    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
183        let pipe = self.pipe.take().unwrap();
184        match unsafe { pipe.try_fill_buf_with_context(Some(cx)) } {
185            Ok(buf) => Poll::Ready(buf),
186            Err(TryReadError::Empty) => {
187                self.pipe = Some(pipe);
188                Poll::Pending
189            }
190        }
191    }
192}
193
194impl<'p, M, const N: usize> Unpin for FillBufFuture<'p, M, N> where M: RawMutex {}
195
196/// Error returned by [`try_read`](Pipe::try_read).
197#[derive(PartialEq, Eq, Clone, Copy, Debug)]
198#[cfg_attr(feature = "defmt", derive(defmt::Format))]
199pub enum TryReadError {
200    /// No data could be read from the pipe because it is currently
201    /// empty, and reading would require blocking.
202    Empty,
203}
204
205/// Error returned by [`try_write`](Pipe::try_write).
206#[derive(PartialEq, Eq, Clone, Copy, Debug)]
207#[cfg_attr(feature = "defmt", derive(defmt::Format))]
208pub enum TryWriteError {
209    /// No data could be written to the pipe because it is
210    /// currently full, and writing would require blocking.
211    Full,
212}
213
214#[derive(Debug)]
215struct PipeState<const N: usize> {
216    buffer: RingBuffer<N>,
217    read_waker: WakerRegistration,
218    write_waker: WakerRegistration,
219}
220
221#[repr(transparent)]
222#[derive(Debug)]
223struct Buffer<const N: usize>(UnsafeCell<[u8; N]>);
224
225impl<const N: usize> Buffer<N> {
226    unsafe fn get<'a>(&self, r: Range<usize>) -> &'a [u8] {
227        let p = self.0.get() as *const u8;
228        core::slice::from_raw_parts(p.add(r.start), r.end - r.start)
229    }
230
231    unsafe fn get_mut<'a>(&self, r: Range<usize>) -> &'a mut [u8] {
232        let p = self.0.get() as *mut u8;
233        core::slice::from_raw_parts_mut(p.add(r.start), r.end - r.start)
234    }
235}
236
237unsafe impl<const N: usize> Send for Buffer<N> {}
238unsafe impl<const N: usize> Sync for Buffer<N> {}
239
240/// A bounded byte-oriented pipe for communicating between asynchronous tasks
241/// with backpressure.
242///
243/// The pipe will buffer up to the provided number of bytes. Once the
244/// buffer is full, attempts to `write` new bytes will wait until buffer space is freed up.
245///
246/// All data written will become available in the same order as it was written.
247#[derive(Debug)]
248pub struct Pipe<M, const N: usize>
249where
250    M: RawMutex,
251{
252    buf: Buffer<N>,
253    inner: Mutex<M, RefCell<PipeState<N>>>,
254}
255
256impl<M, const N: usize> Pipe<M, N>
257where
258    M: RawMutex,
259{
260    /// Establish a new bounded pipe. For example, to create one with a NoopMutex:
261    ///
262    /// ```
263    /// use hazard3_sync::pipe::Pipe;
264    /// use hazard3_sync::blocking_mutex::raw::NoopRawMutex;
265    ///
266    /// // Declare a bounded pipe, with a buffer of 256 bytes.
267    /// let mut pipe = Pipe::<NoopRawMutex, 256>::new();
268    /// ```
269    pub const fn new() -> Self {
270        Self {
271            buf: Buffer(UnsafeCell::new([0; N])),
272            inner: Mutex::new(RefCell::new(PipeState {
273                buffer: RingBuffer::new(),
274                read_waker: WakerRegistration::new(),
275                write_waker: WakerRegistration::new(),
276            })),
277        }
278    }
279
280    fn lock<R>(&self, f: impl FnOnce(&mut PipeState<N>) -> R) -> R {
281        self.inner.lock(|rc| f(&mut *rc.borrow_mut()))
282    }
283
284    fn try_read_with_context(&self, cx: Option<&mut Context<'_>>, buf: &mut [u8]) -> Result<usize, TryReadError> {
285        self.inner.lock(|rc: &RefCell<PipeState<N>>| {
286            let s = &mut *rc.borrow_mut();
287
288            if s.buffer.is_full() {
289                s.write_waker.wake();
290            }
291
292            let available = unsafe { self.buf.get(s.buffer.pop_buf()) };
293            if available.is_empty() {
294                if let Some(cx) = cx {
295                    s.read_waker.register(cx.waker());
296                }
297                return Err(TryReadError::Empty);
298            }
299
300            let n = available.len().min(buf.len());
301            buf[..n].copy_from_slice(&available[..n]);
302            s.buffer.pop(n);
303            Ok(n)
304        })
305    }
306
307    // safety: While the returned slice is alive,
308    // no `read` or `consume` methods in the pipe must be called.
309    unsafe fn try_fill_buf_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<&[u8], TryReadError> {
310        self.inner.lock(|rc: &RefCell<PipeState<N>>| {
311            let s = &mut *rc.borrow_mut();
312
313            if s.buffer.is_full() {
314                s.write_waker.wake();
315            }
316
317            let available = unsafe { self.buf.get(s.buffer.pop_buf()) };
318            if available.is_empty() {
319                if let Some(cx) = cx {
320                    s.read_waker.register(cx.waker());
321                }
322                return Err(TryReadError::Empty);
323            }
324
325            Ok(available)
326        })
327    }
328
329    fn consume(&self, amt: usize) {
330        self.inner.lock(|rc: &RefCell<PipeState<N>>| {
331            let s = &mut *rc.borrow_mut();
332            let available = s.buffer.pop_buf();
333            assert!(amt <= available.len());
334            s.buffer.pop(amt);
335        })
336    }
337
338    fn try_write_with_context(&self, cx: Option<&mut Context<'_>>, buf: &[u8]) -> Result<usize, TryWriteError> {
339        self.inner.lock(|rc: &RefCell<PipeState<N>>| {
340            let s = &mut *rc.borrow_mut();
341
342            if s.buffer.is_empty() {
343                s.read_waker.wake();
344            }
345
346            let available = unsafe { self.buf.get_mut(s.buffer.push_buf()) };
347            if available.is_empty() {
348                if let Some(cx) = cx {
349                    s.write_waker.register(cx.waker());
350                }
351                return Err(TryWriteError::Full);
352            }
353
354            let n = available.len().min(buf.len());
355            available[..n].copy_from_slice(&buf[..n]);
356            s.buffer.push(n);
357
358            if s.buffer.is_full() {
359                s.read_waker.wake();
360            }
361
362            Ok(n)
363        })
364    }
365
366    /// Split this pipe into a BufRead-capable reader and a writer.
367    ///
368    /// The reader and writer borrow the current pipe mutably, so it is not
369    /// possible to use it directly while they exist. This is needed because
370    /// implementing `BufRead` requires there is a single reader.
371    ///
372    /// The writer is cloneable, the reader is not.
373    pub fn split(&mut self) -> (Reader<'_, M, N>, Writer<'_, M, N>) {
374        (Reader { pipe: self }, Writer { pipe: self })
375    }
376
377    /// Write some bytes to the pipe.
378    ///
379    /// This method writes a nonzero amount of bytes from `buf` into the pipe, and
380    /// returns the amount of bytes written.
381    ///
382    /// If it is not possible to write a nonzero amount of bytes because the pipe's buffer is full,
383    /// this method will wait until it isn't. See [`try_write`](Self::try_write) for a variant that
384    /// returns an error instead of waiting.
385    ///
386    /// It is not guaranteed that all bytes in the buffer are written, even if there's enough
387    /// free space in the pipe buffer for all. In other words, it is possible for `write` to return
388    /// without writing all of `buf` (returning a number less than `buf.len()`) and still leave
389    /// free space in the pipe buffer. You should always `write` in a loop, or use helpers like
390    /// `write_all` from the `embedded-io` crate.
391    pub fn write<'a>(&'a self, buf: &'a [u8]) -> WriteFuture<'a, M, N> {
392        WriteFuture { pipe: self, buf }
393    }
394
395    /// Write all bytes to the pipe.
396    ///
397    /// This method writes all bytes from `buf` into the pipe
398    pub async fn write_all(&self, mut buf: &[u8]) {
399        while !buf.is_empty() {
400            let n = self.write(buf).await;
401            buf = &buf[n..];
402        }
403    }
404
405    /// Attempt to immediately write some bytes to the pipe.
406    ///
407    /// This method will either write a nonzero amount of bytes to the pipe immediately,
408    /// or return an error if the pipe is full. See [`write`](Self::write) for a variant
409    /// that waits instead of returning an error. This method might not write all the provided data
410    /// even if there is enough space in the pipe due to implementation details. See
411    /// [Self::try_write_all] for a method which ensures that all bytes are written unless
412    /// an overflow occurs.
413    pub fn try_write(&self, buf: &[u8]) -> Result<usize, TryWriteError> {
414        self.try_write_with_context(None, buf)
415    }
416
417    /// Attempt to immediately write all provided bytes into the pipe.
418    ///
419    /// This method will try to write all bytes of the buffer into the pipe immediately,
420    /// or return an error if the pipe is full.
421    pub fn try_write_all(&self, mut buf: &[u8]) -> Result<(), TryWriteError> {
422        while !buf.is_empty() {
423            let n = self.try_write(buf)?;
424            buf = &buf[n..];
425        }
426        Ok(())
427    }
428
429    /// Read some bytes from the pipe.
430    ///
431    /// This method reads a nonzero amount of bytes from the pipe into `buf` and
432    /// returns the amount of bytes read.
433    ///
434    /// If it is not possible to read a nonzero amount of bytes because the pipe's buffer is empty,
435    /// this method will wait until it isn't. See [`try_read`](Self::try_read) for a variant that
436    /// returns an error instead of waiting.
437    ///
438    /// It is not guaranteed that all bytes in the buffer are read, even if there's enough
439    /// space in `buf` for all. In other words, it is possible for `read` to return
440    /// without filling `buf` (returning a number less than `buf.len()`) and still leave bytes
441    /// in the pipe buffer. You should always `read` in a loop, or use helpers like
442    /// `read_exact` from the `embedded-io` crate.
443    pub fn read<'a>(&'a self, buf: &'a mut [u8]) -> ReadFuture<'a, M, N> {
444        ReadFuture { pipe: self, buf }
445    }
446
447    /// Attempt to immediately read some bytes from the pipe.
448    ///
449    /// This method will either read a nonzero amount of bytes from the pipe immediately,
450    /// or return an error if the pipe is empty. See [`read`](Self::read) for a variant
451    /// that waits instead of returning an error.
452    pub fn try_read(&self, buf: &mut [u8]) -> Result<usize, TryReadError> {
453        self.try_read_with_context(None, buf)
454    }
455
456    /// Clear the data in the pipe's buffer.
457    pub fn clear(&self) {
458        self.inner.lock(|rc: &RefCell<PipeState<N>>| {
459            let s = &mut *rc.borrow_mut();
460
461            s.buffer.clear();
462            s.write_waker.wake();
463        })
464    }
465
466    /// Wait until the pipe is full (no free space in the buffer)
467    pub async fn wait_full(&self) {
468        poll_fn(|cx| {
469            self.inner.lock(|rc: &RefCell<PipeState<N>>| {
470                let s = &mut *rc.borrow_mut();
471
472                s.read_waker.register(cx.waker());
473            });
474
475            if self.is_full() { Poll::Ready(()) } else { Poll::Pending }
476        })
477        .await;
478    }
479
480    /// Return whether the pipe is full (no free space in the buffer)
481    pub fn is_full(&self) -> bool {
482        self.len() == N
483    }
484
485    /// Return whether the pipe is empty (no data buffered)
486    pub fn is_empty(&self) -> bool {
487        self.len() == 0
488    }
489
490    /// Total byte capacity.
491    ///
492    /// This is the same as the `N` generic param.
493    pub const fn capacity(&self) -> usize {
494        N
495    }
496
497    /// Used byte capacity.
498    pub fn len(&self) -> usize {
499        self.lock(|c| c.buffer.len())
500    }
501
502    /// Free byte capacity.
503    ///
504    /// This is equivalent to `capacity() - len()`
505    pub fn free_capacity(&self) -> usize {
506        N - self.len()
507    }
508}
509
510impl<M: RawMutex, const N: usize> embedded_io_async::ErrorType for Pipe<M, N> {
511    type Error = Infallible;
512}
513
514impl<M: RawMutex, const N: usize> embedded_io_async::Read for Pipe<M, N> {
515    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
516        Ok(Pipe::read(self, buf).await)
517    }
518}
519
520impl<M: RawMutex, const N: usize> embedded_io_async::Write for Pipe<M, N> {
521    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
522        Ok(Pipe::write(self, buf).await)
523    }
524
525    async fn flush(&mut self) -> Result<(), Self::Error> {
526        Ok(())
527    }
528}
529
530impl<M: RawMutex, const N: usize> embedded_io_async::ErrorType for &Pipe<M, N> {
531    type Error = Infallible;
532}
533
534impl<M: RawMutex, const N: usize> embedded_io_async::Read for &Pipe<M, N> {
535    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
536        Ok(Pipe::read(self, buf).await)
537    }
538}
539
540impl<M: RawMutex, const N: usize> embedded_io_async::Write for &Pipe<M, N> {
541    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
542        Ok(Pipe::write(self, buf).await)
543    }
544
545    async fn flush(&mut self) -> Result<(), Self::Error> {
546        Ok(())
547    }
548}
549
550impl<M: RawMutex, const N: usize> embedded_io_async::ErrorType for Reader<'_, M, N> {
551    type Error = Infallible;
552}
553
554impl<M: RawMutex, const N: usize> embedded_io_async::Read for Reader<'_, M, N> {
555    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
556        Ok(Reader::read(self, buf).await)
557    }
558}
559
560impl<M: RawMutex, const N: usize> embedded_io_async::BufRead for Reader<'_, M, N> {
561    async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> {
562        Ok(Reader::fill_buf(self).await)
563    }
564
565    fn consume(&mut self, amt: usize) {
566        Reader::consume(self, amt)
567    }
568}
569
570impl<M: RawMutex, const N: usize> embedded_io_async::ErrorType for Writer<'_, M, N> {
571    type Error = Infallible;
572}
573
574impl<M: RawMutex, const N: usize> embedded_io_async::Write for Writer<'_, M, N> {
575    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
576        Ok(Writer::write(self, buf).await)
577    }
578
579    async fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
580        Ok(Writer::write_all(self, buf).await)
581    }
582
583    async fn flush(&mut self) -> Result<(), Self::Error> {
584        Ok(())
585    }
586}
587
588//
589// Type-erased variants
590//
591
592pub(crate) trait DynamicPipe {
593    fn write<'a>(&'a self, buf: &'a [u8]) -> DynamicWriteFuture<'a>;
594    fn read<'a>(&'a self, buf: &'a mut [u8]) -> DynamicReadFuture<'a>;
595
596    fn try_read(&self, buf: &mut [u8]) -> Result<usize, TryReadError>;
597    fn try_write(&self, buf: &[u8]) -> Result<usize, TryWriteError>;
598
599    fn try_write_with_context(&self, cx: Option<&mut Context<'_>>, buf: &[u8]) -> Result<usize, TryWriteError>;
600    fn try_read_with_context(&self, cx: Option<&mut Context<'_>>, buf: &mut [u8]) -> Result<usize, TryReadError>;
601
602    fn consume(&self, amt: usize);
603    unsafe fn try_fill_buf_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<&[u8], TryReadError>;
604}
605
606impl<M, const N: usize> DynamicPipe for Pipe<M, N>
607where
608    M: RawMutex,
609{
610    fn consume(&self, amt: usize) {
611        Pipe::consume(self, amt)
612    }
613
614    unsafe fn try_fill_buf_with_context(&self, cx: Option<&mut Context<'_>>) -> Result<&[u8], TryReadError> {
615        Pipe::try_fill_buf_with_context(self, cx)
616    }
617
618    fn write<'a>(&'a self, buf: &'a [u8]) -> DynamicWriteFuture<'a> {
619        Pipe::write(self, buf).into()
620    }
621
622    fn read<'a>(&'a self, buf: &'a mut [u8]) -> DynamicReadFuture<'a> {
623        Pipe::read(self, buf).into()
624    }
625
626    fn try_read(&self, buf: &mut [u8]) -> Result<usize, TryReadError> {
627        Pipe::try_read(self, buf)
628    }
629
630    fn try_write(&self, buf: &[u8]) -> Result<usize, TryWriteError> {
631        Pipe::try_write(self, buf)
632    }
633
634    fn try_write_with_context(&self, cx: Option<&mut Context<'_>>, buf: &[u8]) -> Result<usize, TryWriteError> {
635        Pipe::try_write_with_context(self, cx, buf)
636    }
637
638    fn try_read_with_context(&self, cx: Option<&mut Context<'_>>, buf: &mut [u8]) -> Result<usize, TryReadError> {
639        Pipe::try_read_with_context(self, cx, buf)
640    }
641}
642
643/// Write-only access to the dynamic pipe.
644pub struct DynamicWriter<'p> {
645    pipe: &'p dyn DynamicPipe,
646}
647
648impl<'p> Clone for DynamicWriter<'p> {
649    fn clone(&self) -> Self {
650        *self
651    }
652}
653
654impl<'p> Copy for DynamicWriter<'p> {}
655
656impl<'p> DynamicWriter<'p> {
657    /// Write some bytes to the pipe.
658    ///
659    /// See [`Pipe::write()`]
660    pub fn write<'a>(&'a self, buf: &'a [u8]) -> DynamicWriteFuture<'a> {
661        self.pipe.write(buf)
662    }
663
664    /// Attempt to immediately write some bytes to the pipe.
665    ///
666    /// See [`Pipe::try_write()`]
667    pub fn try_write(&self, buf: &[u8]) -> Result<usize, TryWriteError> {
668        self.pipe.try_write(buf)
669    }
670}
671
672impl<'p, M, const N: usize> From<Writer<'p, M, N>> for DynamicWriter<'p>
673where
674    M: RawMutex,
675{
676    fn from(value: Writer<'p, M, N>) -> Self {
677        Self { pipe: value.pipe }
678    }
679}
680
681/// Future returned by [`DynamicWriter::write`].
682#[must_use = "futures do nothing unless you `.await` or poll them"]
683pub struct DynamicWriteFuture<'p> {
684    pipe: &'p dyn DynamicPipe,
685    buf: &'p [u8],
686}
687
688impl<'p> Future for DynamicWriteFuture<'p> {
689    type Output = usize;
690
691    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
692        match self.pipe.try_write_with_context(Some(cx), self.buf) {
693            Ok(n) => Poll::Ready(n),
694            Err(TryWriteError::Full) => Poll::Pending,
695        }
696    }
697}
698
699impl<'p> Unpin for DynamicWriteFuture<'p> {}
700
701impl<'p, M, const N: usize> From<WriteFuture<'p, M, N>> for DynamicWriteFuture<'p>
702where
703    M: RawMutex,
704{
705    fn from(value: WriteFuture<'p, M, N>) -> Self {
706        Self {
707            pipe: value.pipe,
708            buf: value.buf,
709        }
710    }
711}
712
713/// Read-only access to a dynamic pipe.
714pub struct DynamicReader<'p> {
715    pipe: &'p dyn DynamicPipe,
716}
717
718impl<'p> DynamicReader<'p> {
719    /// Read some bytes from the pipe.
720    ///
721    /// See [`Pipe::read()`]
722    pub fn read<'a>(&'a self, buf: &'a mut [u8]) -> DynamicReadFuture<'a> {
723        self.pipe.read(buf)
724    }
725
726    /// Attempt to immediately read some bytes from the pipe.
727    ///
728    /// See [`Pipe::try_read()`]
729    pub fn try_read(&self, buf: &mut [u8]) -> Result<usize, TryReadError> {
730        self.pipe.try_read(buf)
731    }
732
733    /// Return the contents of the internal buffer, filling it with more data from the inner reader if it is empty.
734    ///
735    /// If no bytes are currently available to read, this function waits until at least one byte is available.
736    ///
737    /// If the reader is at end-of-file (EOF), an empty slice is returned.
738    pub fn fill_buf(&mut self) -> DynamicFillBufFuture<'_> {
739        DynamicFillBufFuture { pipe: Some(self.pipe) }
740    }
741
742    /// Try returning contents of the internal buffer.
743    ///
744    /// If no bytes are currently available to read, this function returns `Err(TryReadError::Empty)`.
745    ///
746    /// If the reader is at end-of-file (EOF), an empty slice is returned.
747    pub fn try_fill_buf(&mut self) -> Result<&[u8], TryReadError> {
748        unsafe { self.pipe.try_fill_buf_with_context(None) }
749    }
750
751    /// Tell this buffer that `amt` bytes have been consumed from the buffer, so they should no longer be returned in calls to `fill_buf`.
752    pub fn consume(&mut self, amt: usize) {
753        self.pipe.consume(amt)
754    }
755}
756
757impl<'p, M, const N: usize> From<Reader<'p, M, N>> for DynamicReader<'p>
758where
759    M: RawMutex,
760{
761    fn from(value: Reader<'p, M, N>) -> Self {
762        Self { pipe: value.pipe }
763    }
764}
765
766/// Future returned by [`Pipe::read`] and  [`Reader::read`].
767#[must_use = "futures do nothing unless you `.await` or poll them"]
768pub struct DynamicReadFuture<'p> {
769    pipe: &'p dyn DynamicPipe,
770    buf: &'p mut [u8],
771}
772
773impl<'p> Future for DynamicReadFuture<'p> {
774    type Output = usize;
775
776    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
777        match self.pipe.try_read_with_context(Some(cx), self.buf) {
778            Ok(n) => Poll::Ready(n),
779            Err(TryReadError::Empty) => Poll::Pending,
780        }
781    }
782}
783
784impl<'p> Unpin for DynamicReadFuture<'p> {}
785
786impl<'p, M, const N: usize> From<ReadFuture<'p, M, N>> for DynamicReadFuture<'p>
787where
788    M: RawMutex,
789{
790    fn from(value: ReadFuture<'p, M, N>) -> Self {
791        Self {
792            pipe: value.pipe,
793            buf: value.buf,
794        }
795    }
796}
797
798/// Future returned by [`DynamicReader::fill_buf`].
799#[must_use = "futures do nothing unless you `.await` or poll them"]
800pub struct DynamicFillBufFuture<'p> {
801    pipe: Option<&'p dyn DynamicPipe>,
802}
803
804impl<'p> Future for DynamicFillBufFuture<'p> {
805    type Output = &'p [u8];
806
807    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
808        let pipe = self.pipe.take().unwrap();
809        match unsafe { pipe.try_fill_buf_with_context(Some(cx)) } {
810            Ok(buf) => Poll::Ready(buf),
811            Err(TryReadError::Empty) => {
812                self.pipe = Some(pipe);
813                Poll::Pending
814            }
815        }
816    }
817}
818
819impl<'p> Unpin for DynamicFillBufFuture<'p> {}
820
821impl<'p, M, const N: usize> From<FillBufFuture<'p, M, N>> for DynamicFillBufFuture<'p>
822where
823    M: RawMutex,
824{
825    fn from(value: FillBufFuture<'p, M, N>) -> Self {
826        Self {
827            pipe: value.pipe.map(|p| p as &dyn DynamicPipe),
828        }
829    }
830}
831
832#[cfg(test)]
833mod tests {
834    use futures_executor::ThreadPool;
835    use futures_util::task::SpawnExt;
836    use static_cell::StaticCell;
837
838    use super::*;
839    use crate::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
840
841    #[test]
842    fn writing_once() {
843        let c = Pipe::<NoopRawMutex, 3>::new();
844        assert!(c.try_write(&[1]).is_ok());
845        assert_eq!(c.free_capacity(), 2);
846    }
847
848    #[test]
849    fn writing_when_full() {
850        let c = Pipe::<NoopRawMutex, 3>::new();
851        assert_eq!(c.try_write(&[42]), Ok(1));
852        assert_eq!(c.try_write(&[43]), Ok(1));
853        assert_eq!(c.try_write(&[44]), Ok(1));
854        assert_eq!(c.try_write(&[45]), Err(TryWriteError::Full));
855        assert_eq!(c.free_capacity(), 0);
856    }
857
858    #[test]
859    fn write_read_across_rollover() {
860        let c = Pipe::<NoopRawMutex, 3>::new();
861        assert_eq!(c.try_write(&[1, 2]).unwrap(), 2);
862        assert_eq!(c.free_capacity(), 1);
863        let mut buf = [0; 1];
864        c.try_read(&mut buf).expect("trying to read pipe failed");
865        assert_eq!(buf, [1]);
866        assert_eq!(c.free_capacity(), 2);
867        // Write across rollover, only one byte is written.
868        assert_eq!(c.try_write(&[3, 4]).unwrap(), 1);
869        assert_eq!(c.free_capacity(), 1);
870        // Write remaining byte.
871        assert_eq!(c.try_write(&[4]).unwrap(), 1);
872        assert_eq!(c.free_capacity(), 0);
873        let mut buf = [0; 3];
874        // Read across rollover, only two bytes are read.
875        assert_eq!(c.try_read(&mut buf).expect("trying to read pipe failed"), 2);
876        assert_eq!(buf, [2, 3, 0]);
877        assert_eq!(c.free_capacity(), 2);
878        // Read remaining byte.
879        assert_eq!(c.try_read(&mut buf).expect("trying to read pipe failed"), 1);
880        assert_eq!(buf[0], 4);
881        assert_eq!(c.free_capacity(), 3);
882    }
883
884    #[test]
885    fn write_all_across_rollover() {
886        let c = Pipe::<NoopRawMutex, 6>::new();
887        assert_eq!(c.try_write(&[1, 2, 3, 4, 5]).unwrap(), 5);
888        assert_eq!(c.free_capacity(), 1);
889        let mut buf = [0; 3];
890        c.try_read(&mut buf).expect("trying to read pipe failed");
891        assert_eq!(buf, [1, 2, 3]);
892        assert_eq!(c.free_capacity(), 4);
893        assert!(c.try_write_all(&[6, 7, 8]).is_ok());
894        assert_eq!(c.free_capacity(), 1);
895        c.try_read(&mut buf).expect("trying to read pipe failed");
896        assert_eq!(buf, [4, 5, 6]);
897        assert_eq!(c.free_capacity(), 4);
898    }
899
900    #[test]
901    fn receiving_once_with_one_send() {
902        let c = Pipe::<NoopRawMutex, 3>::new();
903        assert!(c.try_write(&[42]).is_ok());
904        let mut buf = [0; 16];
905        assert_eq!(c.try_read(&mut buf), Ok(1));
906        assert_eq!(buf[0], 42);
907        assert_eq!(c.free_capacity(), 3);
908    }
909
910    #[test]
911    fn receiving_when_empty() {
912        let c = Pipe::<NoopRawMutex, 3>::new();
913        let mut buf = [0; 16];
914        assert_eq!(c.try_read(&mut buf), Err(TryReadError::Empty));
915        assert_eq!(c.free_capacity(), 3);
916    }
917
918    #[test]
919    fn simple_send_and_receive() {
920        let c = Pipe::<NoopRawMutex, 3>::new();
921        assert!(c.try_write(&[42]).is_ok());
922        let mut buf = [0; 16];
923        assert_eq!(c.try_read(&mut buf), Ok(1));
924        assert_eq!(buf[0], 42);
925    }
926
927    #[test]
928    fn read_buf() {
929        let mut c = Pipe::<NoopRawMutex, 3>::new();
930        let (mut r, w) = c.split();
931        assert!(w.try_write(&[42, 43]).is_ok());
932        let buf = r.try_fill_buf().unwrap();
933        assert_eq!(buf, &[42, 43]);
934        let buf = r.try_fill_buf().unwrap();
935        assert_eq!(buf, &[42, 43]);
936        r.consume(1);
937        let buf = r.try_fill_buf().unwrap();
938        assert_eq!(buf, &[43]);
939        r.consume(1);
940        assert_eq!(r.try_fill_buf(), Err(TryReadError::Empty));
941        assert_eq!(w.try_write(&[44, 45, 46]), Ok(1));
942        assert_eq!(w.try_write(&[45, 46]), Ok(2));
943        let buf = r.try_fill_buf().unwrap();
944        assert_eq!(buf, &[44]); // only one byte due to wraparound.
945        r.consume(1);
946        let buf = r.try_fill_buf().unwrap();
947        assert_eq!(buf, &[45, 46]);
948        assert!(w.try_write(&[47]).is_ok());
949        let buf = r.try_fill_buf().unwrap();
950        assert_eq!(buf, &[45, 46, 47]);
951        r.consume(3);
952    }
953
954    #[test]
955    fn writer_is_cloneable() {
956        let mut c = Pipe::<NoopRawMutex, 3>::new();
957        let (_r, w) = c.split();
958        #[allow(clippy::clone_on_copy)]
959        let _ = w.clone();
960    }
961
962    #[test]
963    fn dynamic_dispatch_pipe() {
964        let mut c = Pipe::<NoopRawMutex, 3>::new();
965        let (r, w) = c.split();
966        let (mut r, w): (DynamicReader<'_>, DynamicWriter<'_>) = (r.into(), w.into());
967
968        assert!(w.try_write(&[42, 43]).is_ok());
969        let buf = r.try_fill_buf().unwrap();
970        assert_eq!(buf, &[42, 43]);
971        let buf = r.try_fill_buf().unwrap();
972        assert_eq!(buf, &[42, 43]);
973        r.consume(1);
974        let buf = r.try_fill_buf().unwrap();
975        assert_eq!(buf, &[43]);
976        r.consume(1);
977        assert_eq!(r.try_fill_buf(), Err(TryReadError::Empty));
978        assert_eq!(w.try_write(&[44, 45, 46]), Ok(1));
979        assert_eq!(w.try_write(&[45, 46]), Ok(2));
980        let buf = r.try_fill_buf().unwrap();
981        assert_eq!(buf, &[44]); // only one byte due to wraparound.
982        r.consume(1);
983        let buf = r.try_fill_buf().unwrap();
984        assert_eq!(buf, &[45, 46]);
985        assert!(w.try_write(&[47]).is_ok());
986        let buf = r.try_fill_buf().unwrap();
987        assert_eq!(buf, &[45, 46, 47]);
988        r.consume(3);
989    }
990
991    #[futures_test::test]
992    async fn receiver_receives_given_try_write_async() {
993        let executor = ThreadPool::new().unwrap();
994
995        static CHANNEL: StaticCell<Pipe<CriticalSectionRawMutex, 3>> = StaticCell::new();
996        let c = &*CHANNEL.init(Pipe::new());
997        let c2 = c;
998        let f = async move {
999            assert_eq!(c2.try_write(&[42]), Ok(1));
1000        };
1001        executor.spawn(f).unwrap();
1002        let mut buf = [0; 16];
1003        assert_eq!(c.read(&mut buf).await, 1);
1004        assert_eq!(buf[0], 42);
1005    }
1006
1007    #[futures_test::test]
1008    async fn sender_send_completes_if_capacity() {
1009        let c = Pipe::<CriticalSectionRawMutex, 1>::new();
1010        c.write(&[42]).await;
1011        let mut buf = [0; 16];
1012        assert_eq!(c.read(&mut buf).await, 1);
1013        assert_eq!(buf[0], 42);
1014    }
1015}