Skip to main content

alloy_sol_types/types/
enum.rs

1use crate::{
2    Result, SolType, Word,
3    abi::{AbiDecoderConfig, token::WordToken},
4};
5use alloc::vec::Vec;
6
7/// A Solidity enum. This is always a wrapper around a [`u8`].
8///
9/// # Implementer's Guide
10///
11/// It should not be necessary to implement this trait manually. Instead, use
12/// the [`sol!`](crate::sol!) procedural macro to parse Solidity syntax into
13/// types that implement this trait.
14pub trait SolEnum: Sized + Copy + Into<u8> + TryFrom<u8, Error = crate::Error> {
15    /// The number of variants in the enum.
16    ///
17    /// This is generally between 1 and 256 inclusive.
18    const COUNT: usize;
19
20    /// Tokenize the enum.
21    #[inline]
22    fn tokenize(self) -> WordToken {
23        WordToken(Word::with_last_byte(self.into()))
24    }
25
26    /// ABI decode the enum from the given buffer.
27    #[inline]
28    fn abi_decode(data: &[u8]) -> Result<Self> {
29        <crate::sol_data::Uint<8> as SolType>::abi_decode(data).and_then(Self::try_from)
30    }
31
32    /// ABI-decodes the enum with a custom decoder configuration.
33    #[inline]
34    fn abi_decode_with_config(data: &[u8], config: AbiDecoderConfig) -> Result<Self> {
35        <crate::sol_data::Uint<8> as SolType>::abi_decode_with_config(data, config)
36            .and_then(Self::try_from)
37    }
38
39    /// ABI decode the enum from the given buffer, with validation.
40    ///
41    /// This is the same as [`abi_decode`](Self::abi_decode), as validation
42    /// is inherent in the `TryFrom<u8>` conversion.
43    #[inline]
44    // TODO: Deprecate in favor of a validating decoder configuration.
45    // #[deprecated(note = "use a validating decoder configuration")]
46    fn abi_decode_validate(data: &[u8]) -> Result<Self> {
47        Self::abi_decode_with_config(data, AbiDecoderConfig::new().validate(true))
48    }
49
50    /// ABI encode the enum into the given buffer.
51    #[inline]
52    fn abi_encode_raw(self, out: &mut Vec<u8>) {
53        out.extend(self.tokenize().0);
54    }
55
56    /// ABI encode the enum.
57    #[inline]
58    fn abi_encode(self) -> Vec<u8> {
59        self.tokenize().0.to_vec()
60    }
61}