Skip to content

Commit ea8d3cf

Browse files
committed
memory address: add Add<usize>
1 parent d25acde commit ea8d3cf

File tree

6 files changed

+43
-44
lines changed

6 files changed

+43
-44
lines changed

crates/leanVm/src/context/run_context.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ impl RunContext {
4242
match operand {
4343
MemOrConstant::Constant(val) => Ok(MemoryValue::Int(*val)),
4444
MemOrConstant::MemoryAfterFp { shift } => {
45-
let addr = self.fp.add_usize(*shift)?;
45+
let addr = (self.fp + *shift)?;
4646
memory
4747
.get(addr)
4848
.ok_or(MemoryError::UninitializedMemory(addr))
@@ -62,7 +62,7 @@ impl RunContext {
6262
match operand {
6363
MemOrFp::Fp => Ok(MemoryValue::Address(self.fp)),
6464
MemOrFp::MemoryAfterFp { shift } => {
65-
let addr = self.fp.add_usize(*shift)?;
65+
let addr = (self.fp + *shift)?;
6666
memory
6767
.get(addr)
6868
.ok_or(MemoryError::UninitializedMemory(addr))
@@ -85,7 +85,7 @@ impl RunContext {
8585
MemOrFpOrConstant::Constant(val) => Ok(MemoryValue::Int(*val)),
8686
MemOrFpOrConstant::Fp => Ok(MemoryValue::Address(self.fp)),
8787
MemOrFpOrConstant::MemoryAfterFp { shift } => {
88-
let addr = self.fp.add_usize(*shift)?;
88+
let addr = (self.fp + *shift)?;
8989
memory
9090
.get(addr)
9191
.ok_or_else(|| MemoryError::UninitializedMemory(addr).into())
@@ -222,7 +222,7 @@ mod tests {
222222
fn test_get_value_from_mem_or_fp_or_constant_is_mem_success() {
223223
let mut memory = MemoryManager::default();
224224
let fp = memory.add();
225-
let addr_to_read = fp.add_usize(7).unwrap();
225+
let addr_to_read = (fp + 7).unwrap();
226226
let expected_val = MemoryValue::Address(MemoryAddress::new(5, 5));
227227
memory.memory.insert(addr_to_read, expected_val).unwrap();
228228

crates/leanVm/src/core.rs

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ impl<PERM16, PERM24> VirtualMachine<PERM16, PERM24> {
6464

6565
if is_zero {
6666
// **Condition is zero**: The jump is not taken. Advance the `pc` by one.
67-
self.run_context.pc().add_usize(1)?
67+
(*self.run_context.pc() + 1)?
6868
} else {
6969
// **Condition is non-zero**: Execute the jump.
7070
//
@@ -80,7 +80,7 @@ impl<PERM16, PERM24> VirtualMachine<PERM16, PERM24> {
8080
}
8181
} else {
8282
// For any instruction other than `JumpIfNotZero`, advance the `pc` by one.
83-
self.run_context.pc().add_usize(1)?
83+
(*self.run_context.pc() + 1)?
8484
};
8585

8686
// Update the virtual machine's program counter with the calculated next address.
@@ -99,7 +99,7 @@ impl<PERM16, PERM24> VirtualMachine<PERM16, PERM24> {
9999
MemOrFp::Fp => self.run_context.fp,
100100
// The instruction specifies updating `fp` to a value from memory.
101101
MemOrFp::MemoryAfterFp { shift } => {
102-
let addr = self.run_context.fp().add_usize(*shift)?;
102+
let addr = (*self.run_context.fp() + *shift)?;
103103
let value = self
104104
.memory_manager
105105
.get(addr)
@@ -272,7 +272,7 @@ impl<PERM16, PERM24> VirtualMachine<PERM16, PERM24> {
272272
.value_from_mem_or_fp_or_constant(res, &self.memory_manager)?;
273273

274274
// Calculate the address of the first-level pointer, `fp + shift_0`.
275-
let ptr_shift_0_addr = self.run_context.fp.add_usize(shift_0)?;
275+
let ptr_shift_0_addr = (self.run_context.fp + shift_0)?;
276276

277277
// Read the pointer from memory. It must be a `MemoryAddress` type.
278278
let ptr: MemoryAddress = self
@@ -282,7 +282,7 @@ impl<PERM16, PERM24> VirtualMachine<PERM16, PERM24> {
282282
.try_into()?;
283283

284284
// Calculate the final, second-level address: `ptr + shift_1`.
285-
let ptr_shift_1_addr = ptr.add_usize(shift_1)?;
285+
let ptr_shift_1_addr = (ptr + shift_1)?;
286286

287287
// Branch execution based on whether `res` was a known value or an unwritten address.
288288
match res_lookup_result {
@@ -326,7 +326,7 @@ impl<PERM16, PERM24> VirtualMachine<PERM16, PERM24> {
326326
// Read Pointers from Memory
327327
//
328328
// The instruction specifies 4 consecutive pointers starting at `fp + shift`.
329-
let base_ptr_addr = self.run_context.fp.add_usize(shift)?;
329+
let base_ptr_addr = (self.run_context.fp + shift)?;
330330
let ptrs: [MemoryValue; 4] = self.memory_manager.get_array(base_ptr_addr)?;
331331

332332
// Convert the `MemoryValue` pointers to `MemoryAddress`.
@@ -452,11 +452,7 @@ mod tests {
452452
let pc = MemoryAddress::new(0, 10);
453453
let fp = MemoryAddress::new(1, 5);
454454
// Pre-load memory with a zero value at the address `fp + 1`, which will be our condition.
455-
let mut vm = setup_vm(
456-
pc,
457-
fp,
458-
&[(fp.add_usize(1).unwrap(), MemoryValue::Int(F::ZERO))],
459-
);
455+
let mut vm = setup_vm(pc, fp, &[((fp + 1).unwrap(), MemoryValue::Int(F::ZERO))]);
460456
// Define a JNZ instruction where the condition points to the zero value.
461457
let instruction = Instruction::JumpIfNotZero {
462458
condition: MemOrConstant::MemoryAfterFp { shift: 1 },
@@ -482,9 +478,9 @@ mod tests {
482478
fp,
483479
&[
484480
// The condition value (non-zero).
485-
(fp.add_usize(1).unwrap(), MemoryValue::Int(F::from_u64(42))),
481+
((fp + 1).unwrap(), MemoryValue::Int(F::from_u64(42))),
486482
// The destination address for the jump.
487-
(fp.add_usize(2).unwrap(), MemoryValue::Address(jump_target)),
483+
((fp + 2).unwrap(), MemoryValue::Address(jump_target)),
488484
],
489485
);
490486
// Define a JNZ instruction pointing to the condition and destination.
@@ -509,7 +505,7 @@ mod tests {
509505
pc,
510506
fp,
511507
&[(
512-
fp.add_usize(1).unwrap(),
508+
(fp + 1).unwrap(),
513509
MemoryValue::Address(MemoryAddress::new(8, 8)),
514510
)],
515511
);
@@ -554,7 +550,7 @@ mod tests {
554550
let mut vm = setup_vm(
555551
MemoryAddress::new(0, 0),
556552
fp,
557-
&[(fp.add_usize(3).unwrap(), MemoryValue::Address(new_fp))],
553+
&[((fp + 3).unwrap(), MemoryValue::Address(new_fp))],
558554
);
559555
// Define a JNZ instruction where `updated_fp` points to the new address in memory.
560556
let instruction = Instruction::JumpIfNotZero {
@@ -576,7 +572,7 @@ mod tests {
576572
let mut vm = setup_vm(
577573
MemoryAddress::new(0, 0),
578574
fp,
579-
&[(fp.add_usize(3).unwrap(), MemoryValue::Int(F::from_u64(99)))],
575+
&[((fp + 3).unwrap(), MemoryValue::Int(F::from_u64(99)))],
580576
);
581577
// Define a JNZ instruction where `updated_fp` points to this integer value.
582578
let instruction = Instruction::JumpIfNotZero {

crates/leanVm/src/memory/address.rs

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,20 +25,6 @@ impl MemoryAddress {
2525
offset,
2626
}
2727
}
28-
29-
/// Add a `usize` to the address.
30-
pub fn add_usize(self, other: usize) -> Result<Self, MathError> {
31-
// Try to compute the new offset by adding `other` to the current offset.
32-
//
33-
// This uses `checked_add` to safely detect any potential `usize` overflow.
34-
self.offset
35-
.checked_add(other)
36-
.map(|offset| Self {
37-
segment_index: self.segment_index,
38-
offset,
39-
})
40-
.ok_or_else(|| MathError::MemoryAddressAddUsizeOffsetExceeded(Box::new((self, other))))
41-
}
4228
}
4329

4430
impl Add<&F> for MemoryAddress {
@@ -63,6 +49,23 @@ impl Add<&F> for MemoryAddress {
6349
}
6450
}
6551

52+
impl Add<usize> for MemoryAddress {
53+
type Output = Result<Self, MathError>;
54+
55+
fn add(self, other: usize) -> Self::Output {
56+
// Try to compute the new offset by adding `other` to the current offset.
57+
//
58+
// This uses `checked_add` to safely detect any potential `usize` overflow.
59+
self.offset
60+
.checked_add(other)
61+
.map(|offset| Self {
62+
segment_index: self.segment_index,
63+
offset,
64+
})
65+
.ok_or_else(|| MathError::MemoryAddressAddUsizeOffsetExceeded(Box::new((self, other))))
66+
}
67+
}
68+
6669
impl Display for MemoryAddress {
6770
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6871
write!(f, "{}:{}", self.segment_index, self.offset)
@@ -113,7 +116,7 @@ mod tests {
113116
segment_index: 2,
114117
offset: 100,
115118
};
116-
let result = addr.add_usize(25);
119+
let result = addr + 25;
117120
assert_eq!(
118121
result,
119122
Ok(MemoryAddress {
@@ -129,7 +132,7 @@ mod tests {
129132
segment_index: 5,
130133
offset: 500,
131134
};
132-
let result = addr.add_usize(0);
135+
let result = addr + 0;
133136
assert_eq!(result, Ok(addr));
134137
}
135138

@@ -139,7 +142,7 @@ mod tests {
139142
segment_index: 1,
140143
offset: usize::MAX,
141144
};
142-
let result = addr.add_usize(1);
145+
let result = addr + 1;
143146
match result {
144147
Err(MathError::MemoryAddressAddUsizeOffsetExceeded(boxed)) => {
145148
let (original, added) = *boxed;
@@ -154,7 +157,7 @@ mod tests {
154157
proptest! {
155158
#[test]
156159
fn test_add_does_not_overflow(addr in any::<MemoryAddress>(), delta in 0usize..1_000_000) {
157-
let result = addr.add_usize(delta);
160+
let result = addr + delta;
158161
// Only test when offset + delta won't overflow
159162
if let Some(expected_offset) = addr.offset.checked_add(delta) {
160163
prop_assert_eq!(result, Ok(MemoryAddress {

crates/leanVm/src/memory/manager.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ impl MemoryManager {
8080
// Compute the target address: ptr + num.
8181
//
8282
// This operation may fail if it causes overflow.
83-
let addr = ptr.add_usize(num).map_err(MemoryError::Math)?;
83+
let addr = (ptr + num).map_err(MemoryError::Math)?;
8484

8585
// Attempt to write the value into memory at the computed address.
8686
//
@@ -92,7 +92,7 @@ impl MemoryManager {
9292
// After writing all values, compute and return the address after the last item.
9393
//
9494
// This is simply ptr + data.len(), and it may also fail on overflow.
95-
ptr.add_usize(data.len()).map_err(MemoryError::Math)
95+
(ptr + data.len()).map_err(MemoryError::Math)
9696
}
9797

9898
/// Retrieves the value stored at a given memory address.

crates/leanVm/src/memory/mem.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ impl Memory {
166166
// Iterate from 0 to DIM-1 to read each element of the vector.
167167
for (i, res) in result.iter_mut().enumerate().take(DIM) {
168168
// Calculate the address of the current element by adding the index `i` to the start offset.
169-
let current_addr = start_address.add_usize(i).map_err(MemoryError::Math)?;
169+
let current_addr = (start_address + i).map_err(MemoryError::Math)?;
170170

171171
// Retrieve the value from the calculated address.
172172
let mem_val = self
@@ -198,7 +198,7 @@ impl Memory {
198198
// Iterate from 0 to DIM-1 to read each element of the vector.
199199
for (i, o) in out.iter_mut().enumerate().take(DIM) {
200200
// Calculate the address of the current element by adding the index `i` to the start offset.
201-
let addr = start_address.add_usize(i)?;
201+
let addr = (start_address + i)?;
202202

203203
// Attempt to retrieve the value from the memory and convert it into type `V`.
204204
let v = self
@@ -414,7 +414,7 @@ mod tests {
414414
for (i, &val) in values_to_insert.iter().enumerate() {
415415
memory
416416
// Calculate the address for the current item: `start_addr + i`.
417-
.insert(start_addr.add_usize(i).unwrap(), val)
417+
.insert((start_addr + i).unwrap(), val)
418418
.unwrap();
419419
}
420420

crates/leanVm/src/memory/val.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ impl Add<usize> for MemoryValue {
7575

7676
fn add(self, rhs: usize) -> Self::Output {
7777
match self {
78-
Self::Address(addr) => Ok(Self::Address(addr.add_usize(rhs)?)),
78+
Self::Address(addr) => Ok(Self::Address((addr + rhs)?)),
7979
Self::Int(int) => Ok(Self::Int(int + F::from_usize(rhs))),
8080
}
8181
}

0 commit comments

Comments
 (0)