alloy_sol_types/types/
enum.rs

1use crate::{abi::token::WordToken, Result, SolType, Word};
2use alloc::vec::Vec;
3
4/// A Solidity enum. This is always a wrapper around a [`u8`].
5///
6/// # Implementer's Guide
7///
8/// It should not be necessary to implement this trait manually. Instead, use
9/// the [`sol!`](crate::sol!) procedural macro to parse Solidity syntax into
10/// types that implement this trait.
11pub trait SolEnum: Sized + Copy + Into<u8> + TryFrom<u8, Error = crate::Error> {
12    /// The number of variants in the enum.
13    ///
14    /// This is generally between 1 and 256 inclusive.
15    const COUNT: usize;
16
17    /// Tokenize the enum.
18    #[inline]
19    fn tokenize(self) -> WordToken {
20        WordToken(Word::with_last_byte(self.into()))
21    }
22
23    /// ABI decode the enum from the given buffer.
24    #[inline]
25    fn abi_decode(data: &[u8], validate: bool) -> Result<Self> {
26        <crate::sol_data::Uint<8> as SolType>::abi_decode(data, validate).and_then(Self::try_from)
27    }
28
29    /// ABI encode the enum into the given buffer.
30    #[inline]
31    fn abi_encode_raw(self, out: &mut Vec<u8>) {
32        out.extend(self.tokenize().0);
33    }
34
35    /// ABI encode the enum.
36    #[inline]
37    fn abi_encode(self) -> Vec<u8> {
38        self.tokenize().0.to_vec()
39    }
40}