1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//! TCP implementation on the standard stack for embedded-nal-async

use crate::conversion;
use std::io::Error;

impl embedded_nal_async::TcpConnect for crate::Stack {
    type Error = Error;

    type Connection<'a> = TcpConnection;

    async fn connect<'a>(
        &'a self,
        addr: embedded_nal_async::SocketAddr,
    ) -> Result<Self::Connection<'a>, Error> {
        async_std::net::TcpStream::connect(async_std::net::SocketAddr::from(
            conversion::SocketAddr::from(addr),
        ))
        .await
        .map(TcpConnection)
    }
}

pub struct TcpConnection(async_std::net::TcpStream);

impl embedded_io_async::ErrorType for TcpConnection {
    type Error = Error;
}

impl embedded_io_async::Read for TcpConnection {
    async fn read(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
        use async_std::io::ReadExt;
        self.0.read(buffer).await
    }

    async fn read_exact(
        &mut self,
        buffer: &mut [u8],
    ) -> Result<(), embedded_io_async::ReadExactError<Error>> {
        use async_std::io::ReadExt;
        self.0.read_exact(buffer).await.map_err(|e| match e.kind() {
            std::io::ErrorKind::UnexpectedEof => embedded_io_async::ReadExactError::UnexpectedEof,
            _ => embedded_io_async::ReadExactError::Other(e),
        })
    }
}
impl embedded_io_async::Write for TcpConnection {
    async fn write(&mut self, buffer: &[u8]) -> Result<usize, Error> {
        use async_std::io::WriteExt;
        self.0.write(buffer).await
    }

    async fn flush(&mut self) -> Result<(), Error> {
        use async_std::io::WriteExt;
        self.0.flush().await
    }

    async fn write_all(&mut self, buffer: &[u8]) -> Result<(), Error> {
        use async_std::io::WriteExt;
        self.0.write_all(buffer).await
    }
}