Bincode - deserialization of Enum

Hello.
I have a problem with the deserialization of Enum.
I have four bytes (value = 0xFF FF FF FF) and I have to deserialize them to MessageType::AUTH.
#[repr(u32)] and #[repr(C)]- it doesn't give a success.

Code 1:

use bincode::*; // version: 1.3.3
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum MessageType //u32 
{ 
  RES  = 0xAA,
  AUTH = 0xFFFFFFFF,
  CMD  = 0xFFFFFFFE
}
let buf = vec![255, 255, 255, 255];
let msg_type: MessageType = bincode::deserialize(&buf[..]).unwrap();

Error:

panicked at 'called `Result::unwrap()` on an `Err` value: Custom("invalid value: integer `4294967295`, expected variant index 0 <= i < 3")'

Code 2:

use bincode::{config, Decode, Encode}; // version: 2.0.0-rc.1
#[derive(Encode, Decode, PartialEq, Debug)]
enum MessageType  //u32
{ 
  RES  = 0xAA,
  AUTH = 0xFFFFFFFF,
  CMD  = 0xFFFFFFFE
}

let buf = vec![255, 255, 255, 255];
let (msg_type, size): (MessageType, usize) = bincode::decode_from_slice(&buf[..], bincode::config::standard()).unwrap();

Error:

panicked at 'called `Result::unwrap()` on an `Err` value: InvalidIntegerType { expected: U32, found: Reserved }'

You can use serde_repr to serialize an enum with its value, instead of the default variant index.

    #[derive(serde_repr::Serialize_repr, serde_repr::Deserialize_repr, PartialEq, Debug)]
    #[repr(u32)]
    enum MessageType
    {
        RES = 0xAA,
        AUTH = 0xFFFFFFFF,
        CMD = 0xFFFFFFFE,
    }

Rustexplorer

3 Likes