Skip to content

Commit 16a3212

Browse files
committed
refactor WasmInteger trait
1 parent 53cd590 commit 16a3212

File tree

2 files changed

+23
-31
lines changed

2 files changed

+23
-31
lines changed

crates/wasmi/src/engine/translator/func2/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -860,7 +860,7 @@ impl FuncTranslator {
860860
(lhs, Operand::Immediate(rhs)) => {
861861
let lhs = self.layout.operand_to_reg(lhs)?;
862862
let rhs = T::from(rhs.val());
863-
let Some(non_zero_rhs) = <T as WasmInteger>::NonZero::try_from(rhs).ok() else {
863+
let Some(non_zero_rhs) = <T as WasmInteger>::non_zero(rhs) else {
864864
// Optimization: division by zero always traps
865865
return self.translate_trap(TrapCode::IntegerDivisionByZero);
866866
};

crates/wasmi/src/engine/translator/utils.rs

Lines changed: 22 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -42,51 +42,43 @@ impl_typed_for! {
4242
pub trait WasmInteger:
4343
Copy
4444
+ Eq
45+
+ Typed
4546
+ From<TypedVal>
4647
+ Into<TypedVal>
4748
+ From<UntypedVal>
4849
+ Into<UntypedVal>
4950
+ TryInto<Const16<Self>>
50-
+ Typed
5151
{
5252
/// The non-zero type of the [`WasmInteger`].
53-
type NonZero: Copy + TryFrom<Self> + Into<UntypedVal> + TryInto<Const16<Self::NonZero>>;
53+
type NonZero: Copy + Into<Self> + TryInto<Const16<Self::NonZero>> + Into<UntypedVal>;
54+
55+
/// Returns `self` as [`Self::NonZero`] if possible.
56+
///
57+
/// Returns `None` if `self` is zero.
58+
fn non_zero(self) -> Option<Self::NonZero>;
5459

5560
/// Returns `true` if `self` is equal to zero (0).
5661
fn eq_zero(self) -> bool;
5762
}
5863

59-
impl WasmInteger for i32 {
60-
type NonZero = NonZero<Self>;
61-
62-
fn eq_zero(self) -> bool {
63-
self == 0
64-
}
65-
}
66-
67-
impl WasmInteger for u32 {
68-
type NonZero = NonZero<Self>;
69-
70-
fn eq_zero(self) -> bool {
71-
self == 0
72-
}
73-
}
74-
75-
impl WasmInteger for i64 {
76-
type NonZero = NonZero<Self>;
77-
78-
fn eq_zero(self) -> bool {
79-
self == 0
80-
}
81-
}
64+
macro_rules! impl_wasm_integer {
65+
($($ty:ty),*) => {
66+
$(
67+
impl WasmInteger for $ty {
68+
type NonZero = NonZero<Self>;
8269

83-
impl WasmInteger for u64 {
84-
type NonZero = NonZero<Self>;
70+
fn non_zero(self) -> Option<Self::NonZero> {
71+
Self::NonZero::new(self)
72+
}
8573

86-
fn eq_zero(self) -> bool {
87-
self == 0
88-
}
74+
fn eq_zero(self) -> bool {
75+
self == 0
76+
}
77+
}
78+
)*
79+
};
8980
}
81+
impl_wasm_integer!(i32, u32, i64, u64);
9082

9183
/// A WebAssembly float. Either `f32` or `f64`.
9284
///

0 commit comments

Comments
 (0)