citahub / cita_trie

Rust implementation of the Modified Patricia Tree (aka Trie).
Apache License 2.0
71 stars 28 forks source link

Suggestion for ParticialTrie::from() #16

Closed mohanson closed 5 years ago

mohanson commented 5 years ago
pub fn from(db: &'db mut D, codec: C, root: &C::Hash) -> TrieResult<Self, C, D> {
        match db.get(root.as_ref()).map_err(TrieError::DB)? {
            Some(data) => {
                let mut trie = PatriciaTrie {
                    root: Node::Empty,
                    db,
                    codec,

                    cache: HashMap::new(),
                    deleted_keys: vec![],
                };

                trie.root = trie.decode_node(&data).map_err(TrieError::NodeCodec)?;
                Ok(trie)
            }
            None => Err(TrieError::InvalidStateRoot),
        }
    }

root already passed as a parameter, maybe we should not calculate it again in trie.root = trie.decode_node(&data).map_err(TrieError::NodeCodec)?;

So... Could we just use

pub fn from(db: &'db mut D, codec: C, root: &C::Hash) -> TrieResult<Self, C, D> {
        Ok(PatriciaTrie {
            root: Node::Hash(HashNode::new(root.as_ref())),
            db,
            codec,

            cache: HashMap::new(),
            deleted_keys: vec![],
        })
    }
yejiayu commented 5 years ago

But I need to determine if this root exists in the database.

yejiayu commented 5 years ago

Even If root into a hash node, you will also restore it from the database in the next operation.