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]) -> Result<Self> {
26 <crate::sol_data::Uint<8> as SolType>::abi_decode(data).and_then(Self::try_from)
27 }
28
29 /// ABI decode the enum from the given buffer, with validation.
30 ///
31 /// This is the same as [`abi_decode`](Self::abi_decode), as validation
32 /// is inherent in the `TryFrom<u8>` conversion.
33 #[inline]
34 fn abi_decode_validate(data: &[u8]) -> Result<Self> {
35 // Validation is inherent in the `TryFrom` impl generated by `sol!`
36 Self::abi_decode(data)
37 }
38
39 /// ABI encode the enum into the given buffer.
40 #[inline]
41 fn abi_encode_raw(self, out: &mut Vec<u8>) {
42 out.extend(self.tokenize().0);
43 }
44
45 /// ABI encode the enum.
46 #[inline]
47 fn abi_encode(self) -> Vec<u8> {
48 self.tokenize().0.to_vec()
49 }
50}