borsh::de

Trait EnumExt

Source
pub trait EnumExt: BorshDeserialize {
    // Required method
    fn deserialize_variant<R: Read>(reader: &mut R, tag: u8) -> Result<Self>;
}
Expand description

Additional methods offered on enums which is used by [derive(BorshDeserialize)].

Required Methods§

Source

fn deserialize_variant<R: Read>(reader: &mut R, tag: u8) -> Result<Self>

Deserialises given variant of an enum from the reader.

This may be used to perform validation or filtering based on what variant is being deserialised.

use borsh::BorshDeserialize;
use borsh::de::EnumExt as _;

/// derive is only available if borsh is built with `features = ["derive"]`
#[derive(Debug, PartialEq, Eq, BorshDeserialize)]
enum MyEnum {
    Zero,
    One(u8),
    Many(Vec<u8>)
}

#[derive(Debug, PartialEq, Eq)]
struct OneOrZero(MyEnum);

impl borsh::de::BorshDeserialize for OneOrZero {
    fn deserialize_reader<R: borsh::io::Read>(
        reader: &mut R,
    ) -> borsh::io::Result<Self> {
        use borsh::de::EnumExt;
        let tag = u8::deserialize_reader(reader)?;
        if tag == 2 {
            Err(borsh::io::Error::new(
                borsh::io::ErrorKind::InvalidData,
                "MyEnum::Many not allowed here",
            ))
        } else {
            MyEnum::deserialize_variant(reader, tag).map(Self)
        }
    }
}

use borsh::from_slice;
let data = b"\0";
assert_eq!(MyEnum::Zero, from_slice::<MyEnum>(&data[..]).unwrap());
assert_eq!(MyEnum::Zero, from_slice::<OneOrZero>(&data[..]).unwrap().0);

let data = b"\x02\0\0\0\0";
assert_eq!(MyEnum::Many(Vec::new()), from_slice::<MyEnum>(&data[..]).unwrap());
assert!(from_slice::<OneOrZero>(&data[..]).is_err());

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§