use std::io::Result;
use std::task::{Poll, ready};
use crate::handshake::Request;
use crate::handshake::Response;
use crate::error::HandshakeError;
pub fn send_request<'h, 'b: 'h, F, IO, const N: usize>(
io: &mut IO,
buf: &mut [u8],
request: &Request<'h, 'b, N>,
mut write: F,
) -> Poll<Result<usize>>
where
F: FnMut(&mut IO, &[u8]) -> Poll<Result<usize>>,
{
let total = match request.encode(buf) {
Ok(n) => n,
Err(e) => return Poll::Ready(Err(e.into())),
};
let mut offset = 0;
while offset < total {
let n = ready!(write(io, &buf[offset..total]))?;
offset += n;
}
Poll::Ready(Ok(total))
}
pub unsafe fn recv_response<'h, 'b: 'h, F, IO, const N: usize>(
io: &mut IO,
buf: &mut [u8],
response: &mut Response<'h, 'b, N>,
mut read: F,
) -> Poll<Result<usize>>
where
F: FnMut(&mut IO, &mut [u8]) -> Poll<Result<usize>>,
{
let total = buf.len();
let mut offset = 0;
let buf_const: &'b [u8] = &*(buf as *const [u8]);
while offset < total {
let n = ready!(read(io, &mut buf[offset..]))?;
if n == 0 {
return Poll::Ready(Err(HandshakeError::NotEnoughData.into()));
}
offset += n;
match response.decode(&buf_const[..offset]) {
Ok(_) => return Poll::Ready(Ok(offset)),
Err(ref e) if *e == HandshakeError::NotEnoughData => continue,
Err(e) => return Poll::Ready(Err(e.into())),
}
}
Poll::Ready(Err(HandshakeError::NotEnoughCapacity.into()))
}