Skip to content

Commit b6b7eac

Browse files
authored
refactor(levm): remove unneeded checks in swap (#5305)
**Motivation** Currently for swapN we do two unnecessary checks: - `stack.len() < N`, which is also done inside `Stack::swap` - checked add of offset (stack depth) and N, which is guaranteed to never fail as N and the offset are both bounded **Description** Checking that `offset + N >= STACK_DEPTH` should be enough.
1 parent 2690a53 commit b6b7eac

File tree

2 files changed

+11
-10
lines changed

2 files changed

+11
-10
lines changed

crates/vm/levm/src/call_frame.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -144,11 +144,15 @@ impl Stack {
144144
}
145145

146146
#[inline(always)]
147-
pub fn swap(&mut self, index: usize) -> Result<(), ExceptionalHalt> {
148-
let index = self
149-
.offset
150-
.checked_add(index)
151-
.ok_or(ExceptionalHalt::StackUnderflow)?;
147+
pub fn swap<const N: usize>(&mut self) -> Result<(), ExceptionalHalt> {
148+
// Compile-time check that ensures `self.offset + N` is safe,
149+
// since self.offset is bounded by STACK_LIMIT
150+
const {
151+
assert!(STACK_LIMIT.checked_add(N).is_some());
152+
}
153+
#[expect(clippy::arithmetic_side_effects)]
154+
let index = self.offset + N;
155+
152156
if index >= self.values.len() {
153157
return Err(ExceptionalHalt::StackUnderflow);
154158
}

crates/vm/levm/src/opcode_handlers/exchange.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::{
2-
errors::{ExceptionalHalt, OpcodeResult, VMError},
2+
errors::{OpcodeResult, VMError},
33
gas_cost,
44
vm::VM,
55
};
@@ -13,10 +13,7 @@ impl<'a> VM<'a> {
1313
let current_call_frame = &mut self.current_call_frame;
1414
current_call_frame.increase_consumed_gas(gas_cost::SWAPN)?;
1515

16-
if current_call_frame.stack.len() < N {
17-
return Err(ExceptionalHalt::StackUnderflow.into());
18-
}
19-
current_call_frame.stack.swap(N)?;
16+
current_call_frame.stack.swap::<N>()?;
2017

2118
Ok(OpcodeResult::Continue)
2219
}

0 commit comments

Comments
 (0)