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

Additional methods offered on enums which uses [derive(BorshDeserialize)].

Required Methods§

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

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(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::maybestd::io::Read>(
        reader: &mut R,
    ) -> borsh::maybestd::io::Result<Self> {
        use borsh::de::EnumExt;
        let tag = u8::deserialize_reader(reader)?;
        if tag == 2 {
            Err(borsh::maybestd::io::Error::new(
                borsh::maybestd::io::ErrorKind::InvalidInput,
                "MyEnum::Many not allowed here",
            ))
        } else {
            MyEnum::deserialize_variant(reader, tag).map(Self)
        }
    }
}

let data = b"\0";
assert_eq!(MyEnum::Zero, MyEnum::try_from_slice(&data[..]).unwrap());
assert_eq!(MyEnum::Zero, OneOrZero::try_from_slice(&data[..]).unwrap().0);

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

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

§

impl EnumExt for AssociatedTokenAccountInstruction

§

fn deserialize_variant<R>( reader: &mut R, variant_idx: u8 ) -> Result<AssociatedTokenAccountInstruction, Error>
where R: Read,

§

impl EnumExt for Field

§

fn deserialize_variant<R>( reader: &mut R, variant_idx: u8 ) -> Result<Field, Error>
where R: Read,

Implementors§