Skip to content

Commit

Permalink
Testing sled db
Browse files Browse the repository at this point in the history
  • Loading branch information
maxfierrog committed Nov 19, 2024
1 parent 1e8144b commit a4e7f99
Show file tree
Hide file tree
Showing 14 changed files with 448 additions and 142 deletions.
183 changes: 183 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ repository = "https://github.com/GamesCrafters/GamesmanNova"
keywords = ["game", "solver", "strong-solver", "research"]
edition = "2021"
readme = "README.md"
exclude = ["/.github", "/dev"]
exclude = ["/.github", "/dev", "/doc"]

[[bin]]
path = "src/main.rs"
Expand All @@ -28,6 +28,7 @@ exitcode = "^1"
anyhow = "^1"
bitvec = "^1"
regex = "^1"
sled = "^0.34"

[dev-dependencies]
strum_macros = "0.26"
Expand Down
103 changes: 103 additions & 0 deletions src/database/engine/sled.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
//! # Sled Database Engine API
//!
//! It's all downhill from here.
use anyhow::anyhow;
use anyhow::Result;

use std::path::Path;

use crate::database::ByteMap;
use crate::database::Persistent;
use crate::database::ProtoRelational;
use crate::database::Relation;
use crate::database::Schema;

/* DEFINITIONS */

pub struct SledDatabase {
db: sled::Db,
}

pub struct SledNamespace {
tree: sled::Tree,
schema: Schema,
}

/* IMPLEMENTATIONS */

impl ByteMap for SledNamespace {
fn insert<K, V>(&mut self, key: K, record: V) -> Result<()>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
self.tree
.insert(key, record.as_ref())?;
Ok(())
}

fn get<K>(&self, key: K) -> Result<Option<Vec<u8>>>
where
K: AsRef<[u8]>,
{
Ok(self
.tree
.get(key)?
.map(|v| v.to_vec()))
}

fn remove<K>(&mut self, key: K) -> Result<Option<Vec<u8>>>
where
K: AsRef<[u8]>,
{
Ok(self
.tree
.remove(key)?
.map(|v| v.to_vec()))
}
}

impl Relation for SledNamespace {
fn schema(&self) -> &Schema {
&self.schema
}

fn count(&self) -> usize {
self.tree.len()
}
}

impl ProtoRelational for SledDatabase {
type Namespace = SledNamespace;
fn namespace(&self, schema: Schema, name: &str) -> Result<Self::Namespace> {
Ok(SledNamespace {
tree: self.db.open_tree(name)?,
schema,
})
}
}

impl Persistent for SledDatabase {
fn new(path: &Path) -> Result<Self>
where
Self: Sized,
{
let db = sled::open(path)?;
Ok(SledDatabase { db })
}

fn flush(&self) -> Result<usize> {
self.db
.flush()
.map_err(|e| anyhow!("Failed to flush database: {}", e))
}
}

impl Drop for SledDatabase {
fn drop(&mut self) {
self.db
.flush()
.expect(&format!("Failed to flush Sled database"));
}
}
Loading

0 comments on commit a4e7f99

Please sign in to comment.