use dambi::Bytes;
use dope_futures::listener::Listener;
use dope_futures::stream::Stream;
use dope_runtime::{DefaultBackend, block_on, spawn};
use dope_transport::Tcp;

#[test]
fn writev_all_roundtrip() {
    let mut listener = Listener::<Tcp, DefaultBackend>::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();

    block_on(async move {
        let server = spawn(async move {
            let (mut s, _) = listener.accept().await.unwrap();

            let mut got = vec![0u8; 11];
            s.read_exact(&mut got).await.unwrap();
            assert_eq!(&got, b"hello world");

            let (res, _) = s
                .writev_all(vec![
                    Bytes::from_static(b"from-"),
                    Bytes::from_static(b"server"),
                ])
                .await;
            res.unwrap();
        });

        let mut c = Stream::<Tcp, DefaultBackend>::connect_with(addr)
            .await
            .unwrap();
        let (res, _) = c
            .writev_all(vec![
                Bytes::from_static(b"hello"),
                Bytes::from_static(b" "),
                Bytes::from_static(b"world"),
            ])
            .await;
        res.unwrap();

        let mut out = vec![0u8; 11];
        c.read_exact(&mut out).await.unwrap();
        assert_eq!(&out, b"from-server");

        server.await;
    });
}
