use alloc::string::String;
use miden_crypto::merkle::smt::{LeafIndex, SMT_DEPTH};
use miden_protocol_macros::WordWrapper;
use crate::utils::serde::{
ByteReader,
ByteWriter,
Deserializable,
DeserializationError,
Serializable,
};
use crate::{Felt, Hasher, Word};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, WordWrapper)]
pub struct StorageMapKey(Word);
impl StorageMapKey {
pub const SERIALIZED_SIZE: usize = Word::SERIALIZED_SIZE;
pub fn new(word: Word) -> Self {
Self::from_raw(word)
}
pub fn empty() -> Self {
Self::from_raw(Word::empty())
}
pub fn from_index(idx: u32) -> Self {
Self::from_raw(Word::from([idx, 0, 0, 0]))
}
pub fn hash(&self) -> StorageMapKeyHash {
StorageMapKeyHash::from_raw(Hasher::hash_elements(self.0.as_elements()))
}
}
impl From<StorageMapKey> for Word {
fn from(key: StorageMapKey) -> Self {
key.0
}
}
impl core::fmt::Display for StorageMapKey {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_fmt(format_args!("{}", self.as_word()))
}
}
impl Serializable for StorageMapKey {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
target.write_many(self.as_word());
}
fn get_size_hint(&self) -> usize {
Self::SERIALIZED_SIZE
}
}
impl Deserializable for StorageMapKey {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let key = source.read()?;
Ok(StorageMapKey::from_raw(key))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, WordWrapper)]
pub struct StorageMapKeyHash(Word);
impl StorageMapKeyHash {
pub fn to_leaf_index(&self) -> LeafIndex<SMT_DEPTH> {
self.0.into()
}
}
impl From<StorageMapKeyHash> for Word {
fn from(key: StorageMapKeyHash) -> Self {
key.0
}
}
impl From<StorageMapKey> for StorageMapKeyHash {
fn from(key: StorageMapKey) -> Self {
key.hash()
}
}