block-db 0.2.0

Local, multi-threaded, durable byte DB.
Documentation
// Authors: Robert Lopez
#![allow(clippy::suspicious_open_options)]

use crate::{
    data_file::{data_block::DataBlock, wal::DataFileLog, DataFile},
    error::Error,
    wal::BlockDBLog,
    BlockKey,
};
use std::{
    collections::{HashMap, VecDeque},
    sync::Arc,
};
use tokio::sync::RwLock;

pub struct FailedBatchState {
    pub err: Error,
    pub data_file_inverse_log_map: HashMap<String, Vec<DataFileLog>>,
}

pub struct DataFileUpdateState {
    pub new_size: usize,
    pub new_free_bytes: usize,
    pub new_used_bytes: usize,
    pub new_data_blocks: HashMap<String, DataBlock>,
    pub new_free_chunk_offsets: VecDeque<usize>,
}

impl From<&DataFile> for DataFileUpdateState {
    fn from(value: &DataFile) -> Self {
        Self {
            new_size: value.size,
            new_free_bytes: value.free_bytes,
            new_used_bytes: value.used_bytes,
            new_data_blocks: value.data_blocks.clone(),
            new_free_chunk_offsets: value.free_chunk_offsets.clone(),
        }
    }
}

impl From<&tokio::sync::RwLockWriteGuard<'_, DataFile>> for DataFileUpdateState {
    fn from(value: &tokio::sync::RwLockWriteGuard<'_, DataFile>) -> Self {
        Self {
            new_size: value.size,
            new_free_bytes: value.free_bytes,
            new_used_bytes: value.used_bytes,
            new_data_blocks: value.data_blocks.clone(),
            new_free_chunk_offsets: value.free_chunk_offsets.clone(),
        }
    }
}

#[derive(Default)]
pub struct BlockDBUpdateState {
    pub logs: Vec<BlockDBLog>,
    pub freed_bytes: usize,
    pub new_block_keys: Vec<BlockKey>,
    pub new_data_file_map: HashMap<String, Arc<RwLock<DataFile>>>,
    pub data_file_log_map: HashMap<String, Vec<DataFileLog>>,
    pub data_file_update_map: HashMap<String, DataFileUpdateState>,
    pub data_file_inverse_log_map: HashMap<String, Vec<DataFileLog>>,
}

impl BlockDBUpdateState {
    pub fn to_failed_state(self, err: Error) -> Result<Self, FailedBatchState> {
        Err(FailedBatchState {
            err,
            data_file_inverse_log_map: self.data_file_inverse_log_map,
        })
    }
}