stream.rs

 1use std::{
 2    io::{Read, Result, Write},
 3    os::windows::io::{AsSocket, BorrowedSocket},
 4    path::Path,
 5};
 6
 7use async_io::IoSafe;
 8use windows::Win32::Networking::WinSock::connect;
 9
10use crate::{
11    socket::UnixSocket,
12    util::{init, map_ret, sockaddr_un},
13};
14
15pub struct UnixStream(UnixSocket);
16
17unsafe impl IoSafe for UnixStream {}
18
19impl UnixStream {
20    pub fn new(socket: UnixSocket) -> Self {
21        Self(socket)
22    }
23
24    pub fn connect<P: AsRef<Path>>(path: P) -> Result<Self> {
25        init();
26        unsafe {
27            let inner = UnixSocket::new()?;
28            let (addr, len) = sockaddr_un(path)?;
29
30            map_ret(connect(
31                inner.as_raw(),
32                &addr as *const _ as *const _,
33                len as i32,
34            ))?;
35            Ok(Self(inner))
36        }
37    }
38}
39
40impl Read for UnixStream {
41    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
42        self.0.recv(buf)
43    }
44}
45
46impl Write for UnixStream {
47    fn write(&mut self, buf: &[u8]) -> Result<usize> {
48        self.0.send(buf)
49    }
50
51    fn flush(&mut self) -> Result<()> {
52        Ok(())
53    }
54}
55
56impl AsSocket for UnixStream {
57    fn as_socket(&self) -> BorrowedSocket<'_> {
58        unsafe { BorrowedSocket::borrow_raw(self.0.as_raw().0 as _) }
59    }
60}