async_native_tls/
std_adapter.rs1use std::io::{self, Read, Write};
2use std::marker::Unpin;
3use std::pin::Pin;
4use std::task::{Context, Poll};
5
6use crate::runtime::{AsyncRead, AsyncWrite};
7
8#[derive(Debug)]
9pub(crate) struct StdAdapter<S> {
10 pub(crate) inner: S,
11 pub(crate) context: *mut (),
12}
13
14unsafe impl<S: Send> Send for StdAdapter<S> {}
16unsafe impl<S: Sync> Sync for StdAdapter<S> {}
17
18impl<S> StdAdapter<S>
19where
20 S: Unpin,
21{
22 pub(crate) fn with_context<F, R>(&mut self, f: F) -> R
23 where
24 F: FnOnce(&mut Context<'_>, Pin<&mut S>) -> R,
25 {
26 unsafe {
27 assert!(!self.context.is_null());
28 let waker = &mut *(self.context as *mut _);
29 f(waker, Pin::new(&mut self.inner))
30 }
31 }
32}
33
34#[cfg(feature = "runtime-async-std")]
35impl<S> Read for StdAdapter<S>
36where
37 S: AsyncRead + Unpin,
38{
39 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
40 match self.with_context(|ctx, stream| stream.poll_read(ctx, buf)) {
41 Poll::Ready(r) => r,
42 Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)),
43 }
44 }
45}
46
47#[cfg(feature = "runtime-tokio")]
48impl<S> Read for StdAdapter<S>
49where
50 S: AsyncRead + Unpin,
51{
52 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
53 let mut buf = tokio::io::ReadBuf::new(buf);
54 match self.with_context(|ctx, stream| stream.poll_read(ctx, &mut buf)) {
55 Poll::Ready(r) => r.map(|_| buf.filled().len()),
56 Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)),
57 }
58 }
59}
60
61impl<S> Write for StdAdapter<S>
62where
63 S: AsyncWrite + Unpin,
64{
65 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
66 match self.with_context(|ctx, stream| stream.poll_write(ctx, buf)) {
67 Poll::Ready(r) => r,
68 Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)),
69 }
70 }
71
72 fn flush(&mut self) -> io::Result<()> {
73 match self.with_context(|ctx, stream| stream.poll_flush(ctx)) {
74 Poll::Ready(r) => r,
75 Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)),
76 }
77 }
78}