miden_objects/account/component/template/storage/
init_storage_data.rs

1use alloc::collections::BTreeMap;
2use alloc::string::String;
3use alloc::vec::Vec;
4
5use super::StorageValueName;
6use crate::Word;
7
8/// Represents the data required to initialize storage entries when instantiating an
9/// [AccountComponent](crate::account::AccountComponent) from a
10/// [template](crate::account::AccountComponentTemplate).
11///
12/// An [`InitStorageData`] can be created from a TOML string when the `std` feature flag is set.
13#[derive(Clone, Debug, Default)]
14pub struct InitStorageData {
15    // TODO: Both the below fields could be a single field with a two variant enum
16    // (eg, BTreeMap<StorageValueName, StorageTemplateValue>)
17    /// A mapping of storage placeholder names to their corresponding storage values.
18    value_entries: BTreeMap<StorageValueName, String>,
19    /// A mapping of map placeholder names to their corresponding key/value entries.
20    map_entries: BTreeMap<StorageValueName, Vec<(Word, Word)>>,
21}
22
23impl InitStorageData {
24    /// Creates a new instance of [InitStorageData].
25    ///
26    /// A [`BTreeMap`] is constructed from the passed iterator, so duplicate keys will cause
27    /// overridden values.
28    ///
29    /// # Parameters
30    ///
31    /// - `entries`: An iterable collection of key-value pairs.
32    /// - `map_entries`: An iterable collection of storage map entries keyed by placeholder.
33    pub fn new(
34        entries: impl IntoIterator<Item = (StorageValueName, String)>,
35        map_entries: impl IntoIterator<Item = (StorageValueName, Vec<(Word, Word)>)>,
36    ) -> Self {
37        let value_entries = entries
38            .into_iter()
39            .filter(|(entry_name, _)| !entry_name.as_str().is_empty())
40            .collect::<BTreeMap<_, _>>();
41
42        InitStorageData {
43            value_entries,
44            map_entries: map_entries.into_iter().collect(),
45        }
46    }
47
48    /// Retrieves a reference to the storage placeholders.
49    pub fn placeholders(&self) -> &BTreeMap<StorageValueName, String> {
50        &self.value_entries
51    }
52
53    /// Returns a reference to the name corresponding to the placeholder, or
54    /// [`Option::None`] if the placeholder is not present.
55    pub fn get(&self, key: &StorageValueName) -> Option<&String> {
56        self.value_entries.get(key)
57    }
58
59    /// Returns the map entries associated with the given placeholder name, if any.
60    pub fn map_entries(&self, key: &StorageValueName) -> Option<&Vec<(Word, Word)>> {
61        self.map_entries.get(key)
62    }
63}