#lazy-evaluation #lazy-loaded

lazy-db

适用于小型项目的一个简单、基本且延迟加载的数据库

14 个稳定版本

1.5.5 2024年8月11日
1.5.4 2023年9月17日
1.5.3 2023年8月28日

#134数据库接口

Download history 32/week @ 2024-07-01 74/week @ 2024-08-05

74 每月下载次数
用于 2 crates

MIT/Apache

49KB
879

lazy-db

适用于小型项目的一个简单、基本且延迟加载的数据库

示例


一些基本用法

这是一个非常基础的 LazyDB,它保存了有关名为 'Dave' 的假设人物的一些信息

use lazy_db::*;

let path = "example_db"; // path to the database
let database = LazyDB::init_db(path).unwrap(); // initialise the database

// Writing to the database with a concise macro
// The individual containers are separated by `/` while the `LazyData` is separted with `::`.
// The assigning `=` sign indicates the `LazyData` that is being written to the path
// The function after the `=` sign is formatted like this: new_<primative_type>
write_database!((&database) /people/Dave::fav_colour = new_string("Blue")).unwrap();
write_database!((&database) /people/Dave::age = new_u8(21)).unwrap();
write_database!((&database) /people/Dave::unemployed = new_bool(true)).unwrap();

// Reading from the database with a concise macro
// Same path as before
// The search macro only creates a `LazyData` object, you must collect it with a collect function formatted like this: collect_<primative>
let fav_colour: String = search_database!((&database) /people/Dave::fav_colour).unwrap().collect_string().unwrap();
let age: u8 = search_database!((&database) /people/Dave::age).unwrap().collect_u8().unwrap();
let unemployed: bool = search_database!((&database) /people/Dave::unemployed).unwrap().collect_bool().unwrap();

延迟对象

LazyObject 的示例实现

use lazy_db::*;
struct Person {
    container: LazyContainer,
    name: Option<String>,
    age: Option<u8>,
}

impl LazyObject for Person {
    fn as_container(&self) -> &LazyContainer {
        &self.container
    }

    fn store_lazy(&self) -> Result<(), LDBError> {
        if let Some(x) = &self.name {
            LazyData::new_string(self.container.data_writer("name")?, x)?;
        };

        if let Some(x) = self.age {
            LazyData::new_u8(self.container.data_writer("name")?, x)?
        };

        Ok(())
    }

    fn load_lazy(container: LazyContainer) -> Self {
        Self {
            container,
            name: None,
            age: None,
        }
    }

    fn clear_cache(&mut self) {
        self.name = None;
        self.age = None;
    }
}

impl Drop for Person {
    fn drop(&mut self) {
        let _ = self.store_lazy();
    }
}

依赖项

~2–10MB
~113K SLoC