sheave_core/writers/
handshake.rs

1use std::{
2    future::Future,
3    io::Result as IOResult,
4    pin::Pin,
5    task::{
6        Context as FutureContext,
7        Poll
8    }
9};
10use tokio::io::AsyncWrite;
11use crate::handshake::Handshake;
12
13#[doc(hidden)]
14#[derive(Debug)]
15pub struct HandshakeWriter<'a, W: AsyncWrite> {
16    writer: Pin<&'a mut W>,
17    handshake: &'a Handshake
18}
19
20#[doc(hidden)]
21impl<W: AsyncWrite> Future for HandshakeWriter<'_, W> {
22    type Output = IOResult<()>;
23
24    fn poll(mut self: Pin<&mut Self>, cx: &mut FutureContext<'_>) -> Poll<Self::Output> {
25        let handshake_bytes = self.handshake.get_bytes();
26        self.writer.as_mut().poll_write(cx, handshake_bytes).map_ok(|_| ())
27    }
28}
29
30/// Writes actual handshake data into streams.
31///
32/// # Examples
33///
34/// ```rust
35/// use std::{
36///     io::Result as IOResult,
37///     pin::{
38///         Pin,
39///         pin
40///     },
41///     time::Duration
42/// };
43/// use sheave_core::{
44///     handshake::{
45///         Handshake,
46///         Version
47///     },
48///     writers::write_handshake
49/// };
50///
51/// #[tokio::main]
52/// async fn main() -> IOResult<()> {
53///     let mut writer: Pin<&mut Vec<u8>> = pin!(Vec::new());
54///     let handshake = Handshake::new(Duration::default(), Version::UNSIGNED);
55///     write_handshake(writer.as_mut(), &handshake).await?;
56///     assert_eq!(handshake.get_bytes(), writer.as_slice());
57///     Ok(())
58/// }
59/// ```
60pub fn write_handshake<'a, W: AsyncWrite>(writer: Pin<&'a mut W>, handshake: &'a Handshake) -> HandshakeWriter<'a, W> {
61    HandshakeWriter { writer, handshake }
62}
63
64#[cfg(test)]
65mod tests {
66    use std::{
67        pin::pin,
68        time::Duration
69    };
70    use crate::handshake::{
71        Handshake,
72        Version
73    };
74    use super::*;
75
76    #[tokio::test]
77    async fn read_unsigned() {
78        let mut writer: Pin<&mut Vec<u8>> = pin!(Vec::new());
79        let handshake = Handshake::new(Duration::default(), Version::UNSIGNED);
80        let result = write_handshake(writer.as_mut(), &handshake).await;
81        assert!(result.is_ok());
82        assert_eq!(handshake.get_bytes(), writer.as_slice())
83    }
84}