block-db 0.2.0

Local, multi-threaded, durable byte DB.
Documentation
// Authors: Robert Lopez

use crate::error::Error;
use std::path::{Path, PathBuf};
use tokio::fs::{create_dir_all, read_dir, remove_dir_all, remove_file, try_exists, ReadDir};

pub async fn delete_file(path: &Path) -> Result<(), Error> {
    if try_exists(path).await? {
        remove_file(path).await?;
    }

    Ok(())
}

pub async fn delete_directory(path: &Path) -> Result<(), Error> {
    if try_exists(path).await? {
        remove_dir_all(path).await?;
    }

    Ok(())
}

pub async fn create_directory(path: &Path) -> Result<(), Error> {
    if !try_exists(path).await? {
        create_dir_all(path).await?;
    }

    Ok(())
}

pub async fn delete_temp_files(path: &Path) -> Result<(), Error> {
    let mut directory_iter = DirectoryIter::new(path).await?;
    while let Some((name, path)) = directory_iter.next().await? {
        if name.starts_with("temp") {
            delete_file(&path).await?;
        }
    }

    Ok(())
}

pub struct DirectoryIter {
    read_dir: ReadDir,
}

impl DirectoryIter {
    pub async fn new(path: &Path) -> Result<Self, Error> {
        let read_dir = read_dir(path).await?;

        Ok(Self { read_dir })
    }

    pub async fn next(&mut self) -> Result<Option<(String, PathBuf)>, Error> {
        if let Some(entry) = self.read_dir.next_entry().await? {
            return Ok(entry
                .file_name()
                .to_str()
                .map(|s| (s.to_string(), entry.path())));
        }

        Ok(None)
    }
}