pub fn read_message(stream: &mut TcpStream) -> Result<Vec<u8>, Error> {
    let mut buf : [u8; 2] = [0; 2];

    if let Err(_) = stream.read_exact(&mut buf) {
        return Err(Error::NetworkError);
    }

    let size = bytes_to_u16(&buf);
    if size == 0 {
        return Ok(Vec::new());
    }

    let mut payload : Vec<u8> = Vec::with_capacity(size as usize);

    let mut buf : [u8; 1024] = [0; 1024];
    let mut size_left = size as usize;
    loop {
        let min = std::cmp::min(size_left, 1024);

        if let Err(_) = stream.read_exact(&mut buf[..min]) {
            return Err(Error::PayloadError);
        }

        payload.extend_from_slice(&buf[..min]);

        size_left -= min;

        if size_left == 0 {
            break;
        }
    }

    Ok(payload)
}
/// Read a message from stream
///
/// message format is: [len u16 - payload]
Read a message from stream
message format is: [len u16 - payload]
Read a message from stream message format is : [ len u16 - payload ]
pub fn read_message(stream: &mut TcpStream) -> Result<Vec<u8>, Error> {
    let mut buf : [u8; 2] = [0; 2];
    if let Err(_) = stream.read_exact(&mut buf) {
        return Err(Error::NetworkError);
    }
    let size = bytes_to_u16(&buf);
    if size == 0 {
        return Ok(Vec::new());
    }
    let mut payload : Vec<u8> = Vec::with_capacity(size as usize);
    let mut buf : [u8; 1024] = [0; 1024];
    let mut size_left = size as usize;
    loop {
        let min = std::cmp::min(size_left, 1024);
        if let Err(_) = stream.read_exact(&mut buf[..min]) {
            return Err(Error::PayloadError);
        }
        payload.extend_from_slice(&buf[..min]);
        size_left -= min;
        if size_left == 0 {
            break;
        }
    }
    Ok(payload)
}
pub fn read_message ( stream : & mut TcpStream ) -> Result < Vec < u8 > , Error > { let mut buf : [ u8 ; 2 ] = [ 0 ; 2 ] ; if let Err ( _ ) = stream . read_exact ( & mut buf ) { return Err ( Error :: NetworkError ) ; } let size = bytes_to_u16 ( & buf ) ; if size == 0 { return Ok ( Vec :: new ( ) ) ; } let mut payload : Vec < u8 > = Vec :: with_capacity ( size as usize ) ; let mut buf : [ u8 ; 1024 ] = [ 0 ; 1024 ] ; let mut size_left = size as usize ; loop { let min = std :: cmp :: min ( size_left , 1024 ) ; if let Err ( _ ) = stream . read_exact ( & mut buf [ .. min ] ) { return Err ( Error :: PayloadError ) ; } payload . extend_from_slice ( & buf [ .. min ] ) ; size_left -= min ; if size_left == 0 { break ; } } Ok ( payload ) }
Read a message from stream
message format is: [len u16 - payload]
Read a message from stream message format is : [ len u16 - payload ]
stream
&mut TcpStream
stream
&mut TcpStream