lunar-lib 0.9.0

Common utilities for lunar applications
Documentation
use sled::{IVec, Tree};

use crate::database::TransactionError;

pub type DbKey = [u8; 32];

/// Returns the raw bytes of the instance of [`Self`] in the database with the matching `key`
///
/// # Errors
///
/// Errors of [`sled`] fails to get the key. See [`sled::Tree::get()`] for more information
pub(crate) fn sled_get_raw(tree: &Tree, key: &DbKey) -> sled::Result<Option<IVec>> {
    tree.get(key)
}

/// Returns the raw bytes of all instances of [`Self`] in the database
///
/// # Errors
///
/// Errors if [`sled`] fails to read an entry in the tree
pub(crate) fn sled_get_all_raw(tree: &Tree) -> sled::Result<Vec<IVec>> {
    tree.iter().values().collect()
}

/// Returns the raw bytes of all keys of [`Self`] in the database
///
/// # Errors
///
/// Errors if [`sled`] fails to read an entry in the tree
pub(crate) fn sled_get_all_keys_raw(tree: &Tree) -> sled::Result<Vec<DbKey>> {
    tree.iter()
        .keys()
        .map(|ivec| {
            let key: DbKey = (&*ivec?).try_into().expect("Expected 32 byte key");
            Ok(key)
        })
        .collect::<Result<Vec<_>, _>>()
}

/// Returns a batch of [`Self`] from `ids`
///
/// # Errors
///
/// This function will error if [`sled`] fails to retrieve an entry, or any key is not found
pub(crate) fn sled_get_batch_raw<I>(tree: &Tree, keys: I) -> Result<Vec<IVec>, TransactionError>
where
    I: IntoIterator<Item = DbKey>,
{
    keys.into_iter()
        .map(|id| tree.get(id)?.ok_or(TransactionError::MissingEntry))
        .collect::<Result<Vec<IVec>, TransactionError>>()
}