Skip to content

Commit aca4508

Browse files
committed
Use num_enum for opcode enums
1 parent fe3f94a commit aca4508

File tree

6 files changed

+66
-413
lines changed

6 files changed

+66
-413
lines changed

Cargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

compiler/core/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ bitflags = { workspace = true }
1717
itertools = { workspace = true }
1818
malachite-bigint = { workspace = true }
1919
num-complex = { workspace = true }
20+
num_enum = { workspace = true }
21+
num-traits = { workspace = true }
2022

2123
lz4_flex = "0.11"
2224

compiler/core/src/opcode.rs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use crate::marshal::MarshalError;
12
pub use crate::opcodes::{PseudoOpcode, RealOpcode};
23

34
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
@@ -6,22 +7,42 @@ pub enum Opcode {
67
Pseudo(PseudoOpcode),
78
}
89

10+
impl TryFrom<u16> for Opcode {
11+
type Error = MarshalError;
12+
13+
fn try_from(raw: u16) -> Result<Self, Self::Error> {
14+
// Try first pseudo opcode. If not, fallback to real opcode.
15+
PseudoOpcode::try_from(raw)
16+
.map(Opcode::Pseudo)
17+
.or_else(|_| {
18+
Self::try_from(u8::try_from(raw).map_err(|_| Self::Error::InvalidBytecode)?)
19+
})
20+
}
21+
}
22+
23+
impl TryFrom<u8> for Opcode {
24+
type Error = MarshalError;
25+
26+
fn try_from(raw: u8) -> Result<Self, Self::Error> {
27+
// u8 can never be a pseduo.
28+
RealOpcode::try_from(raw).map(Opcode::Real)
29+
}
30+
}
31+
932
macro_rules! impl_try_from {
1033
($struct_name:ident, $($t:ty),+ $(,)?) => {
1134
$(
1235
impl TryFrom<$t> for $struct_name {
13-
type Error = ();
36+
type Error = MarshalError;
1437

1538
fn try_from(raw: $t) -> Result<Self, Self::Error> {
16-
RealOpcode::try_from(raw)
17-
.map(Opcode::Real)
18-
.or_else(|_| PseudoOpcode::try_from(raw).map(Opcode::Pseudo))
39+
Self::try_from(u16::try_from(raw).map_err(|_| Self::Error::InvalidBytecode)?)
1940
}
2041
}
2142
)+
2243
};
2344
}
2445

2546
impl_try_from!(
26-
Opcode, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
47+
Opcode, i8, i16, i32, i64, i128, isize, u32, u64, u128, usize
2748
);

0 commit comments

Comments
 (0)