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
//! # pmtree
//! Persistent Merkle Tree in Rust
//!
//! ## How it stored
//! { (usize::MAX - 1) : depth }
//! { (usize::MAX)     : next_index}
//! { Position (tuple - (depth, index), converted to DBKey) : Value}

pub mod database;
pub mod hasher;
pub mod tree;

use std::fmt::{Debug, Display};

pub use database::*;
pub use hasher::*;
pub use tree::MerkleTree;

/// Denotes keys in a database
pub type DBKey = [u8; 8];

/// Denotes values in a database
pub type Value = Vec<u8>;

/// Denotes pmtree Merkle tree errors
#[derive(Debug)]
pub enum TreeErrorKind {
    MerkleTreeIsFull,
    InvalidKey,
    IndexOutOfBounds,
    CustomError(String),
}

/// Denotes pmtree database errors
#[derive(Debug)]
pub enum DatabaseErrorKind {
    CannotLoadDatabase,
    DatabaseExists,
    CustomError(String),
}

/// Denotes pmtree errors
#[derive(Debug)]
pub enum PmtreeErrorKind {
    /// Error in database
    DatabaseError(DatabaseErrorKind),
    /// Error in tree
    TreeError(TreeErrorKind),
    /// Custom error
    CustomError(String),
}

impl Display for PmtreeErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            PmtreeErrorKind::DatabaseError(e) => write!(f, "Database error: {e:?}"),
            PmtreeErrorKind::TreeError(e) => write!(f, "Tree error: {e:?}"),
            PmtreeErrorKind::CustomError(e) => write!(f, "Custom error: {e:?}"),
        }
    }
}

impl std::error::Error for PmtreeErrorKind {}

/// Custom `Result` type with custom `Error` type
pub type PmtreeResult<T> = std::result::Result<T, PmtreeErrorKind>;