revm_bytecode/opcode/
parse.rs

1//! Parsing opcodes from strings.
2//!
3//! This module provides a function to parse opcodes from strings.
4//! It is a utility function that needs to be enabled with `parse` feature.
5
6use super::OpCode;
7use crate::opcode::NAME_TO_OPCODE;
8use core::fmt;
9
10/// An error indicating that an opcode is invalid
11#[derive(Debug, PartialEq, Eq)]
12pub struct OpCodeError(());
13
14impl fmt::Display for OpCodeError {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        f.write_str("invalid opcode")
17    }
18}
19
20impl core::error::Error for OpCodeError {}
21
22impl core::str::FromStr for OpCode {
23    type Err = OpCodeError;
24
25    #[inline]
26    fn from_str(s: &str) -> Result<Self, Self::Err> {
27        Self::parse(s).ok_or(OpCodeError(()))
28    }
29}
30
31impl OpCode {
32    /// Parses an opcode from a string.
33    ///
34    /// This is the inverse of [`as_str`](Self::as_str).
35    #[inline]
36    pub fn parse(s: &str) -> Option<Self> {
37        NAME_TO_OPCODE.get(s).copied()
38    }
39}