cairo_lang_sierra/
edit_state.rs

1use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
2use thiserror::Error;
3
4use crate::ids::VarId;
5
6#[cfg(test)]
7#[path = "edit_state_test.rs"]
8mod test;
9
10#[derive(Error, Debug, Eq, PartialEq)]
11pub enum EditStateError {
12    #[error("Missing reference")]
13    MissingReference(VarId),
14    #[error("Overridden variable")]
15    VariableOverride(VarId),
16}
17impl EditStateError {
18    pub fn var_id(self) -> VarId {
19        match self {
20            EditStateError::MissingReference(var_id) => var_id,
21            EditStateError::VariableOverride(var_id) => var_id,
22        }
23    }
24}
25
26/// Given a map with var ids as keys, extracts out the given ids, failing if some id is missing.
27pub fn take_args<'a, V: 'a>(
28    mut state: OrderedHashMap<VarId, V>,
29    ids: impl Iterator<Item = &'a VarId>,
30) -> Result<(OrderedHashMap<VarId, V>, Vec<V>), EditStateError> {
31    let mut vals = vec![];
32    for id in ids {
33        match state.swap_remove(id) {
34            None => {
35                return Err(EditStateError::MissingReference(id.clone()));
36            }
37            Some(v) => {
38                vals.push(v);
39            }
40        }
41    }
42    Ok((state, vals))
43}
44
45/// Adds the given pairs to map with var ids as keys, failing if some variable is overridden.
46pub fn put_results<'a, V>(
47    mut state: OrderedHashMap<VarId, V>,
48    results: impl Iterator<Item = (&'a VarId, V)>,
49) -> Result<OrderedHashMap<VarId, V>, EditStateError> {
50    for (id, v) in results {
51        if state.insert(id.clone(), v).is_some() {
52            return Err(EditStateError::VariableOverride(id.clone()));
53        }
54    }
55    Ok(state)
56}