mysql_async/io/
socket.rs

1// Copyright (c) 2019 Anatoly Ikorsky
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9#![cfg(unix)]
10
11use pin_project::pin_project;
12use tokio::io::{Error, ErrorKind::Interrupted, ReadBuf};
13
14use std::{
15    io,
16    path::Path,
17    pin::Pin,
18    task::{Context, Poll},
19};
20use tokio::io::{AsyncRead, AsyncWrite};
21
22/// Unix domain socket connection on unix, or named pipe connection on windows.
23#[pin_project]
24#[derive(Debug)]
25pub(crate) struct Socket {
26    #[pin]
27    #[cfg(unix)]
28    inner: tokio::net::UnixStream,
29}
30
31impl Socket {
32    /// Connects a new socket.
33    #[cfg(unix)]
34    pub async fn new<P: AsRef<Path>>(path: P) -> Result<Socket, io::Error> {
35        Ok(Socket {
36            inner: tokio::net::UnixStream::connect(path).await?,
37        })
38    }
39}
40
41impl AsyncRead for Socket {
42    fn poll_read(
43        self: Pin<&mut Self>,
44        cx: &mut Context<'_>,
45        buf: &mut ReadBuf<'_>,
46    ) -> Poll<Result<(), Error>> {
47        let mut this = self.project();
48        with_interrupted!(this.inner.as_mut().poll_read(cx, buf))
49    }
50}
51
52impl AsyncWrite for Socket {
53    fn poll_write(
54        self: Pin<&mut Self>,
55        cx: &mut Context,
56        buf: &[u8],
57    ) -> Poll<Result<usize, Error>> {
58        let mut this = self.project();
59        with_interrupted!(this.inner.as_mut().poll_write(cx, buf))
60    }
61
62    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
63        let mut this = self.project();
64        with_interrupted!(this.inner.as_mut().poll_flush(cx))
65    }
66
67    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Error>> {
68        let mut this = self.project();
69        with_interrupted!(this.inner.as_mut().poll_shutdown(cx))
70    }
71}