embedded_platform/
io.rs

1//! Common IO primitives.
2//!
3//! These primitives are closely mirroring the definitions in
4//! [`tokio-io`](https://docs.rs/tokio-io).  A big difference is that these definitions are not tied
5//! to `std::io::Error`, but instead allow for custom error types, and also don't require
6//! allocation.
7
8use core::fmt;
9use core::pin;
10use core::task;
11
12pub mod read;
13pub mod read_exact;
14pub mod shutdown;
15pub mod write;
16pub mod write_all;
17
18pub trait Read: fmt::Debug {
19    type Error: ReadError;
20
21    fn poll_read(
22        self: pin::Pin<&mut Self>,
23        cx: &mut task::Context<'_>,
24        buffer: &mut [u8],
25    ) -> task::Poll<Result<usize, Self::Error>>;
26}
27
28pub trait ReadError: fmt::Debug {
29    fn eof() -> Self;
30}
31
32pub trait Write: fmt::Debug {
33    type Error: WriteError;
34
35    fn poll_write(
36        self: pin::Pin<&mut Self>,
37        cx: &mut task::Context<'_>,
38        bytes: &[u8],
39    ) -> task::Poll<Result<usize, Self::Error>>;
40
41    fn poll_shutdown(
42        self: pin::Pin<&mut Self>,
43        cx: &mut task::Context<'_>,
44    ) -> task::Poll<Result<(), Self::Error>>;
45}
46
47impl<A: ?Sized + Write + Unpin> Write for &mut A {
48    type Error = A::Error;
49
50    fn poll_write(
51        mut self: pin::Pin<&mut Self>,
52        cx: &mut task::Context<'_>,
53        bytes: &[u8],
54    ) -> task::Poll<Result<usize, Self::Error>> {
55        pin::Pin::new(&mut **self).poll_write(cx, bytes)
56    }
57
58    fn poll_shutdown(
59        mut self: pin::Pin<&mut Self>,
60        cx: &mut task::Context<'_>,
61    ) -> task::Poll<Result<(), Self::Error>> {
62        pin::Pin::new(&mut **self).poll_shutdown(cx)
63    }
64}
65
66pub trait WriteError: fmt::Debug {
67    fn write_zero() -> Self;
68}
69
70pub trait ReadExt: Read {
71    fn read<'a>(&'a mut self, buffer: &'a mut [u8]) -> read::Read<'a, Self>
72    where
73        Self: Unpin,
74    {
75        read::read(self, buffer)
76    }
77
78    fn read_exact<'a>(&'a mut self, buffer: &'a mut [u8]) -> read_exact::ReadExact<'a, Self>
79    where
80        Self: Unpin,
81    {
82        read_exact::read_exact(self, buffer)
83    }
84}
85
86impl<A> ReadExt for A where A: Read {}
87
88pub trait WriteExt: Write {
89    fn write<'a>(&'a mut self, bytes: &'a [u8]) -> write::Write<'a, Self>
90    where
91        Self: Unpin,
92    {
93        write::write(self, bytes)
94    }
95
96    fn write_all<'a>(&'a mut self, bytes: &'a [u8]) -> write_all::WriteAll<'a, Self>
97    where
98        Self: Unpin,
99    {
100        write_all::write_all(self, bytes)
101    }
102
103    fn shutdown(&mut self) -> shutdown::Shutdown<Self>
104    where
105        Self: Unpin,
106    {
107        shutdown::shutdown(self)
108    }
109}
110
111impl<A> WriteExt for A where A: WriteExt {}