bincode-org / bincode

A binary encoder / decoder implementation in Rust.
MIT License
2.69k stars 272 forks source link

What's wrong with my struct/code? #722

Closed IoIxD closed 2 months ago

IoIxD commented 2 months ago

struct:

#[repr(C)]
#[derive(Clone, Encode, Decode)]
pub struct BoxDimensions {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

#[repr(C)]
#[derive(Decode, Encode)]
pub struct FetchedColliders {
    packet_type: PacketType,
    pub vec: Vec<BoxDimensions>,
}

deserialization function:

pub fn deserialize<'a, T>(mut bytes: BufReader<&TcpStream>) -> Result<T, Box<dyn std::error::Error>>
where
    T: Decode,
{
    Ok(bincode::decode_from_reader(&mut bytes, config::standard())?)
}

function that calls it:

 pub fn colliders(&mut self) -> Result<Vec<BoxDimensions>, Box<dyn std::error::Error>> {
        let tcp = Self::tcp()?;

        let mut reader = BufReader::new(&tcp);
        let mut writer = BufWriter::new(&tcp);

        writer.write(&[PacketType::FetchCollidersPacket as u8])?;
        writer.write_all(&serialize(FetchColliders::new())?)?;

        writer.flush();

        let vec: Vec<BoxDimensions> = deserialize(reader)?;
        Ok(vec.clone())
    }

On both 1.0, and 2.0, I get an "unexpected eof" error, even though I confirmed that after flushing the writer, I can in fact read the struct with reader.read_to_end; I even tried just saving the result of that function to a vec and then passing it to bincode::decode_from_slice , but I get the same error.

IoIxD commented 2 months ago

Realized this is a duplicate of #695