turbofish-org / merk

High-performance Merkle key/value store
Apache License 2.0
226 stars 36 forks source link

How to find the number of elements in the tree #76

Closed cameron1024 closed 1 month ago

cameron1024 commented 1 year ago

This seems like a really simple question, but I can't find which part of the API to use :sweat_smile:

I tried this code:

fn merk_len(merk: &Merk) -> usize {
    let mut count = 0;
    let mut iter = merk.raw_iter();
    loop {
        iter.next();
        match iter.key() {
            None => return count,
            Some(_) => {
                count += 1;
                continue;
            }
        }
    }
}

but unfortunately this segfaults.

Is there a simple way to count how many keys are present in the tree?

mappum commented 1 year ago

Since this is using the RocksDB raw iterator API, you must first check if the entry is valid before trying to access the key, and you also need to first seek the iterator to the start. You should be able to do it like this:

fn merk_len(merk: &Merk) -> usize {
    let mut count = 0;
    let mut iter = merk.raw_iter();
    iter.seek_to_first();
    while iter.valid() {
        count += 1;
        iter.next();
    }
    count
}
mappum commented 1 month ago

Closing due to inactivity.