Persistent Hashmap


#1

Correct syntax to create a new persistent hashmap in the main function using the persistent_hashmap crate


#2

It doesn’t seem like the persistent_hashmap crate is currently being updated, but here’s the syntax it uses in tests:

let mut db = PersistentHashmap::<&str, u8>::new("name.db", 10).expect("expected db to open correctly");

#3

Hi Daboross
thanks for the response, The “name.db” file do I have to create it ?


#4

It seems like PersistentHashmap::new() will always create a new file, and override any previous database, while PersistentHashmap::open() will read existing files but fail if the file doesn’t exist yet.

If you want to open an existing file if it exists, or create one of it doesn’t, maybe you could do something like this?

extern crate persistent_hashmap;
extern crate persistent_array;

use std::io;
use std::path::Path;

use persistent_hashmap::PersistentHashmap;

fn open_db<P, K, V>(file_name: &P, capacity: u64) -> Result<PersistentHashmap<K, V>, persistent_array::Error>
where
    P: AsRef<Path> + ?Sized,
    V: Default + Copy,
{
    match PersistentHashmap::open(file_name) {
        Ok(v) => Ok(v),
        Err(e) => {
            if let persistent_array::Error::UnableToOpenFile(ref io_e) = e {
                if io_e.kind() == io::ErrorKind::NotFound {
                    return PersistentHashmap::new(file_name, capacity);
                }
            }
            Err(e)
        }
    }
}

fn main() {
    let mut db: PersistentHashmap<&str, u8> = open_db("name.db", 10).expect("expected opening database to succeed.");

    // use db
}