1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use alloc::{
    collections::{btree_map::IntoIter, BTreeMap},
    vec::Vec,
};

use vm_core::{
    crypto::hash::RpoDigest,
    utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
};

use super::Felt;

// ADVICE MAP
// ================================================================================================

/// Defines a set of non-deterministic (advice) inputs which the VM can access by their keys.
///
/// Each key maps to one or more field element. To access the elements, the VM can move the values
/// associated with a given key onto the advice stack using `adv.push_mapval` instruction. The VM
/// can also insert new values into the advice map during execution.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AdviceMap(BTreeMap<RpoDigest, Vec<Felt>>);

impl AdviceMap {
    /// Creates a new advice map.
    pub fn new() -> Self {
        Self(BTreeMap::<RpoDigest, Vec<Felt>>::new())
    }

    /// Returns the values associated with given key.
    pub fn get(&self, key: &RpoDigest) -> Option<&[Felt]> {
        self.0.get(key).map(|v| v.as_slice())
    }

    /// Inserts a key value pair in the advice map and returns the inserted value.
    pub fn insert(&mut self, key: RpoDigest, value: Vec<Felt>) -> Option<Vec<Felt>> {
        self.0.insert(key, value)
    }

    /// Removes the value associated with the key and returns the removed element.
    pub fn remove(&mut self, key: RpoDigest) -> Option<Vec<Felt>> {
        self.0.remove(&key)
    }
}

impl From<BTreeMap<RpoDigest, Vec<Felt>>> for AdviceMap {
    fn from(value: BTreeMap<RpoDigest, Vec<Felt>>) -> Self {
        Self(value)
    }
}

impl IntoIterator for AdviceMap {
    type Item = (RpoDigest, Vec<Felt>);
    type IntoIter = IntoIter<RpoDigest, Vec<Felt>>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl Extend<(RpoDigest, Vec<Felt>)> for AdviceMap {
    fn extend<T: IntoIterator<Item = (RpoDigest, Vec<Felt>)>>(&mut self, iter: T) {
        self.0.extend(iter)
    }
}

impl Serializable for AdviceMap {
    fn write_into<W: ByteWriter>(&self, target: &mut W) {
        target.write_usize(self.0.len());
        for (key, values) in self.0.iter() {
            target.write((key, values));
        }
    }
}

impl Deserializable for AdviceMap {
    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        let mut map = BTreeMap::new();
        let count = source.read_usize()?;
        for _ in 0..count {
            let (key, values) = source.read()?;
            map.insert(key, values);
        }
        Ok(Self(map))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_advice_map_serialization() {
        let mut map1 = AdviceMap::new();
        map1.insert(RpoDigest::default(), vec![Felt::from(1u32), Felt::from(2u32)]);

        let bytes = map1.to_bytes();

        let map2 = AdviceMap::read_from_bytes(&bytes).unwrap();

        assert_eq!(map1, map2);
    }
}