Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Implement alloc_constant_size hint #469

Merged
merged 1 commit into from
May 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions crates/cairo-1-hint-processor/src/hint_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ use num_traits::cast::ToPrimitive;
use num_traits::identities::Zero;
use std::{collections::HashMap, ops::Mul};

/// Execution scope for constant memory allocation.
struct MemoryExecScope {
/// The first free address in the segment.
next_address: Relocatable,
}

#[derive(MontConfig)]
#[modulus = "3618502788666131213697322783095070105623107215331596699973092056135872020481"]
#[generator = "3"]
Expand Down Expand Up @@ -139,6 +145,39 @@ fn as_cairo_short_string(value: &Felt252) -> Option<String> {
}

impl Cairo1HintProcessor {
fn alloc_constant_size(
&self,
vm: &mut VirtualMachine,
exec_scopes: &mut ExecutionScopes,
size: &ResOperand,
dst: &CellRef,
) -> Result<(), HintError> {
let object_size = res_operand_get_val(vm, size)?
.to_usize()
.expect("Object size too large.");
let memory_exec_scope =
match exec_scopes.get_mut_ref::<MemoryExecScope>("memory_exec_scope") {
Ok(memory_exec_scope) => memory_exec_scope,
Err(_) => {
exec_scopes.assign_or_update_variable(
"memory_exec_scope",
Box::new(MemoryExecScope {
next_address: vm.add_memory_segment(),
}),
);
exec_scopes.get_mut_ref::<MemoryExecScope>("memory_exec_scope")?
}
};

vm.insert_value(
cell_ref_to_relocatable(dst, vm),
memory_exec_scope.next_address,
)?;

memory_exec_scope.next_address.offset += object_size;
Ok(())
}

fn alloc_segment(&mut self, vm: &mut VirtualMachine, dst: &CellRef) -> Result<(), HintError> {
let segment = vm.add_memory_segment();
vm.insert_value(cell_ref_to_relocatable(dst, vm), segment)
Expand Down Expand Up @@ -922,6 +961,9 @@ impl HintProcessor for Cairo1HintProcessor {
let hint = hint_data.downcast_ref::<Hint>().unwrap();
match hint {
Hint::Core(CoreHint::AllocSegment { dst }) => self.alloc_segment(vm, dst),
Hint::Core(CoreHint::AllocConstantSize { size, dst }) => {
self.alloc_constant_size(vm, exec_scopes, size, dst)
}
Hint::Core(CoreHint::TestLessThan { lhs, rhs, dst }) => {
self.test_less_than(vm, lhs, rhs, dst)
}
Expand Down Expand Up @@ -1073,6 +1115,7 @@ impl HintProcessor for Cairo1HintProcessor {
Hint::Core(CoreHint::ShouldSkipSquashLoop { should_skip_loop }) => {
self.should_skip_squash_loop(vm, exec_scopes, should_skip_loop)
}

Hint::Core(CoreHint::AssertLtAssertValidInput { a, b }) => {
self.assert_lt_assert_valid_input(vm, exec_scopes, a, b)
}
Expand Down