diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e1539ba38..8724213dd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ #### Upcoming Changes +* dev: add Memory::get_maybe_relocatable [#2039](https://github.com/lambdaclass/cairo-vm/pull/2039) + * refactor: remove duplicated get_val function [#2065](https://github.com/lambdaclass/cairo-vm/pull/2065) * fix: Always use a normal segment in first SegmentArena segment [#1845](https://github.com/lambdaclass/cairo-vm/pull/1845) diff --git a/vm/src/vm/vm_memory/memory.rs b/vm/src/vm/vm_memory/memory.rs index 7d108ce2ff..4bcd463935 100644 --- a/vm/src/vm/vm_memory/memory.rs +++ b/vm/src/vm/vm_memory/memory.rs @@ -448,6 +448,19 @@ impl Memory { } } + /// Gets the value from memory address as a MaybeRelocatable value. + /// Returns an Error if the value at the memory address is missing or not a MaybeRelocatable. + pub fn get_maybe_relocatable(&self, key: Relocatable) -> Result { + match self + .get(&key) + .ok_or_else(|| MemoryError::UnknownMemoryCell(Box::new(key)))? + { + // Note: the `Borrowed` variant will never occur. + Cow::Borrowed(maybe_rel) => Ok(maybe_rel.clone()), + Cow::Owned(maybe_rel) => Ok(maybe_rel), + } + } + /// Inserts a value into memory /// Returns an error if the memory cell asignment is invalid pub fn insert_value>( @@ -1194,6 +1207,29 @@ mod memory_tests { ); } + #[test] + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] + fn get_maybe_relocatable_valid_relocatable() { + let memory = memory![((0, 0), (1, 0))]; + assert_eq!( + memory + .get_maybe_relocatable(Relocatable::from((0, 0))) + .unwrap(), + Relocatable::from((1, 0)).into() + ); + } + + #[test] + fn get_maybe_relocatable_valid_integer() { + let memory = memory![((0, 0), 10)]; + assert_eq!( + memory + .get_maybe_relocatable(Relocatable::from((0, 0))) + .unwrap(), + 10.into() + ); + } + #[test] #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] fn default_memory() {