rustlite_core/
lib.rs

1//! # RustLite Core
2//!
3//! Core types and implementations for RustLite embedded database.
4//!
5//! ## ⚠️ Internal Implementation Detail
6//!
7//! **This crate is an internal implementation detail of RustLite.**
8//!
9//! Users should depend on the main [`rustlite`](https://crates.io/crates/rustlite) crate
10//! instead, which provides the stable public API. This crate's API may change
11//! without notice between minor versions.
12//!
13//! ```toml
14//! # In your Cargo.toml - use the main crate, not this one:
15//! [dependencies]
16//! rustlite = "0.3"
17//! ```
18
19#![warn(missing_docs)]
20#![warn(clippy::all)]
21
22pub mod error;
23pub mod index;
24/// SQL-like query engine (v0.4+)
25pub mod query;
26pub mod storage;
27pub mod transaction;
28
29#[cfg(test)]
30mod transaction_tests;
31
32pub use error::{Error, Result};
33
34use std::collections::HashMap;
35use std::sync::{Arc, RwLock};
36
37/// The main database handle.
38///
39/// This is the primary interface for interacting with RustLite.
40/// It provides thread-safe access to the underlying storage engine.
41#[derive(Clone)]
42pub struct Database {
43    inner: Arc<DatabaseInner>,
44}
45
46struct DatabaseInner {
47    // Simple in-memory storage for v0.1
48    // This will be replaced with proper storage engine in future versions
49    store: RwLock<HashMap<Vec<u8>, Vec<u8>>>,
50}
51
52impl Database {
53    /// Creates a new in-memory database instance.
54    pub fn new() -> Result<Self> {
55        Ok(Database {
56            inner: Arc::new(DatabaseInner {
57                store: RwLock::new(HashMap::new()),
58            }),
59        })
60    }
61
62    /// Inserts or updates a key-value pair.
63    pub fn put(&self, key: &[u8], value: &[u8]) -> Result<()> {
64        let mut store = self.inner.store.write().map_err(|_| Error::LockPoisoned)?;
65        store.insert(key.to_vec(), value.to_vec());
66        Ok(())
67    }
68
69    /// Retrieves a value by key.
70    pub fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
71        let store = self.inner.store.read().map_err(|_| Error::LockPoisoned)?;
72        Ok(store.get(key).cloned())
73    }
74
75    /// Deletes a key-value pair.
76    pub fn delete(&self, key: &[u8]) -> Result<bool> {
77        let mut store = self.inner.store.write().map_err(|_| Error::LockPoisoned)?;
78        Ok(store.remove(key).is_some())
79    }
80}
81
82impl Default for Database {
83    fn default() -> Self {
84        Self::new().expect("Failed to create default database")
85    }
86}