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
use crate::TlsStream;

use rustls::{ConnectionCommon, SideData};
use tokio_uring::BufResult;

use std::{
    cell::UnsafeCell,
    ops::{Deref, DerefMut},
    rc::Rc,
};

#[derive(Debug)]
pub struct ReadHalf<C> {
    pub(crate) inner: Rc<UnsafeCell<TlsStream<C>>>,
}

#[derive(Debug)]
pub struct WriteHalf<C> {
    pub(crate) inner: Rc<UnsafeCell<TlsStream<C>>>,
}

impl<C, SD: SideData + 'static> ReadHalf<C>
where
    C: DerefMut + Deref<Target = ConnectionCommon<SD>>,
{
    pub async fn read<B: tokio_uring::buf::IoBufMut>(&mut self, buf: B) -> BufResult<usize, B> {
        let inner = unsafe { &mut *self.inner.get() };
        return inner.read(buf).await;
    }
}

impl<C, SD: SideData + 'static> WriteHalf<C>
where
    C: DerefMut + Deref<Target = ConnectionCommon<SD>>,
{
    pub async fn write<B: tokio_uring::buf::IoBuf>(&mut self, buf: B) -> BufResult<usize, B> {
        let inner = unsafe { &mut *self.inner.get() };
        return inner.write(buf).await;
    }

    pub async fn write_all<B: tokio_uring::buf::IoBuf>(&mut self, buf: B) -> BufResult<(), B> {
        let inner = unsafe { &mut *self.inner.get() };
        return inner.write_all(buf).await;
    }
}

pub fn split<C: DerefMut + Deref<Target = ConnectionCommon<SD>>, SD: SideData + 'static>(
    stream: TlsStream<C>,
) -> (ReadHalf<C>, WriteHalf<C>) {
    let shared = Rc::new(UnsafeCell::new(stream));
    (
        ReadHalf {
            inner: shared.clone(),
        },
        WriteHalf { inner: shared },
    )
}