Skip to content

Commit f7be7f6

Browse files
committed
memory: implement TryFrom<MemoryValue> for F
1 parent ea8d3cf commit f7be7f6

File tree

2 files changed

+15
-16
lines changed

2 files changed

+15
-16
lines changed

crates/leanVm/src/core.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,9 @@ impl<PERM16, PERM24> VirtualMachine<PERM16, PERM24> {
6060
.value_from_mem_or_constant(condition, &self.memory_manager)?;
6161

6262
// A jump condition must be a field element.
63-
let is_zero = condition_val.to_f()?.is_zero();
63+
let f: F = condition_val.try_into()?;
6464

65-
if is_zero {
65+
if f.is_zero() {
6666
// **Condition is zero**: The jump is not taken. Advance the `pc` by one.
6767
(*self.run_context.pc() + 1)?
6868
} else {
@@ -351,7 +351,7 @@ impl<PERM16, PERM24> VirtualMachine<PERM16, PERM24> {
351351
// Convert the state to an array of field
352352
let mut state_f: [F; DIMENSION * 2] = [F::ZERO; DIMENSION * 2];
353353
for i in 0..DIMENSION {
354-
state_f[i] = state[i].to_f()?;
354+
state_f[i] = state[i].try_into()?;
355355
}
356356

357357
// Apply the Poseidon2 permutation to the state.

crates/leanVm/src/memory/val.rs

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,13 @@ impl Default for MemoryValue {
1919
}
2020
}
2121

22-
impl MemoryValue {
23-
pub const fn to_f(&self) -> Result<F, MemoryError> {
24-
match self {
25-
Self::Address(_) => Err(MemoryError::ExpectedInteger),
26-
Self::Int(f) => Ok(*f),
22+
impl TryFrom<MemoryValue> for F {
23+
type Error = MemoryError;
24+
25+
fn try_from(value: MemoryValue) -> Result<Self, Self::Error> {
26+
match value {
27+
MemoryValue::Int(f) => Ok(f),
28+
MemoryValue::Address(_) => Err(MemoryError::ExpectedInteger),
2729
}
2830
}
2931
}
@@ -124,14 +126,11 @@ mod tests {
124126
// Wrap it in a MemoryValue::Int variant
125127
let val: MemoryValue = MemoryValue::Int(field_elem);
126128

127-
// Call to_f()
128-
let result = val.to_f();
129-
130-
// Assert it succeeds
131-
assert!(result.is_ok());
129+
// Call
130+
let result: F = val.try_into().unwrap();
132131

133132
// Assert the returned value is equal to the original
134-
assert_eq!(result.unwrap(), field_elem);
133+
assert_eq!(result, field_elem);
135134
}
136135

137136
#[test]
@@ -145,8 +144,8 @@ mod tests {
145144
// Wrap it in a MemoryValue::Address variant
146145
let val: MemoryValue = MemoryValue::Address(addr);
147146

148-
// Call to_f()
149-
let result = val.to_f();
147+
// Call
148+
let result: Result<F, MemoryError> = val.try_into();
150149

151150
// Assert it fails
152151
assert!(result.is_err());

0 commit comments

Comments
 (0)