Skip to main content

evm_selectors/
selector.rs

1use anyhow::Result;
2
3/// Describes a selector, which can either be:
4///     - 4 bytes for functions, errors, etc.
5///     - 32 bytes for events
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub enum Selector {
8    Four([u8; 4]),
9    ThirtyTwo([u8; 32]),
10}
11
12impl From<[u8; 4]> for Selector {
13    fn from(bytes: [u8; 4]) -> Self {
14        Self::Four(bytes)
15    }
16}
17
18impl From<[u8; 32]> for Selector {
19    fn from(bytes: [u8; 32]) -> Self {
20        Self::ThirtyTwo(bytes)
21    }
22}
23
24impl TryFrom<&[u8]> for Selector {
25    type Error = anyhow::Error;
26
27    fn try_from(bytes: &[u8]) -> Result<Self> {
28        Ok(match bytes.len() {
29            4 => Selector::Four(bytes.try_into().unwrap()),
30            32 => Selector::ThirtyTwo(bytes.try_into().unwrap()),
31            _ => {
32                return Err(anyhow::anyhow!(
33                    "Selector has invalid byte length: {}",
34                    bytes.len()
35                ));
36            }
37        })
38    }
39}