From 75aa714030165082f83cac13e224fec062b669b5 Mon Sep 17 00:00:00 2001 From: Magamedrasul Ibragimov Date: Sat, 10 Dec 2022 17:19:00 +0300 Subject: [PATCH] docs: add usage example --- README.md | 74 ++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 62 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index a8b787e..5ea46f2 100644 --- a/README.md +++ b/README.md @@ -22,18 +22,68 @@ To use batch insertions you must enable `batch_insert` feature: pmtree = { git = "https://github.com/Rate-Limiting-Nullifier/pmtree", features = ["batch_insert"] } ``` -## Clone & Build -```bash -git clone git@github.com:Rate-Limiting-Nullifier/pmtree.git && cd pmtree -cargo build --release -``` +## Example -## Run tests -```bash -cargo test --release -``` +In-Memory DB (HashMap) + Keccak +```rust +struct MemoryDB(HashMap); +struct MyKeccak(Keccak); -## Docs -```bash -cargo docs --open +impl Database for MemoryDB { + fn new(_dbpath: &str) -> Result { + Ok(MemoryDB(HashMap::new())) + } + + fn load(_dbpath: &str) -> Result { + Err(Error("Cannot load in-memory DB".to_string())) + } + + fn get(&self, key: DBKey) -> Result> { + Ok(self.0.get(&key).cloned()) + } + + fn put(&mut self, key: DBKey, value: Value) -> Result<()> { + self.0.insert(key, value); + + Ok(()) + } +} + +impl Hasher for MyKeccak { + type Fr = [u8; 32]; + + fn default_leaf() -> Self::Fr { + [0; 32] + } + + fn serialize(value: Self::Fr) -> Value { + value.to_vec() + } + + fn deserialize(value: Value) -> Self::Fr { + value.try_into().unwrap() + } + + fn hash(input: &[Self::Fr]) -> Self::Fr { + let mut output = [0; 32]; + let mut hasher = Keccak::v256(); + for element in input { + hasher.update(element); + } + hasher.finalize(&mut output); + output + } +} + +fn main() { + let mut mt = MerkleTree::::new(2, "abacaba").unwrap(); + + assert_eq!(mt.capacity(), 4); + assert_eq!(mt.depth(), 2); + + mt.update_next(hex!( + "c1ba1812ff680ce84c1d5b4f1087eeb08147a4d510f3496b2849df3a73f5af95" + )) + .unwrap(); +} ```