Files
openworm/src/bin/server/db.rs
T
2025-11-28 17:29:33 -05:00

54 lines
1.6 KiB
Rust

use std::path::Path;
use bincode::{Decode, Encode};
use openworm::net::BINCODE_CONFIG;
use sled::{Db, Tree};
pub const DB_VERSION: u64 = 0;
pub fn open_db(path: impl AsRef<Path>) -> Db {
let db = sled::open(path).expect("failed to open database");
if !db.was_recovered() {
println!("no previous db found, creating new");
db.insert_("version", DB_VERSION);
db.flush().unwrap();
} else {
let version: u64 = db.get_("version").expect("failed to read db version");
println!("found existing db version {version}");
if version != DB_VERSION {
panic!("non matching db version! (auto update in the future)");
}
}
db
}
pub trait DbUtil {
fn insert_<K: AsRef<[u8]>, V: Encode>(&self, k: K, v: V);
fn get_<K: AsRef<[u8]>, V: Decode<()>>(&self, k: K) -> Option<V>;
fn iter_all<V: Decode<()>>(&self) -> impl Iterator<Item = V>;
}
impl DbUtil for Tree {
fn insert_<K: AsRef<[u8]>, V: Encode>(&self, k: K, v: V) {
let bytes = bincode::encode_to_vec(v, BINCODE_CONFIG).unwrap();
self.insert(k, bytes).unwrap();
}
fn get_<K: AsRef<[u8]>, V: Decode<()>>(&self, k: K) -> Option<V> {
let bytes = self.get(k).unwrap()?;
Some(
bincode::decode_from_slice(&bytes, BINCODE_CONFIG)
.unwrap()
.0,
)
}
fn iter_all<V: Decode<()>>(&self) -> impl Iterator<Item = V> {
self.iter().map(|r| {
bincode::decode_from_slice(&r.unwrap().1, BINCODE_CONFIG)
.unwrap()
.0
})
}
}