diff --git a/Cargo.toml b/Cargo.toml index ce77d57..32ce623 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,20 +24,15 @@ version = "0.7.0" optional = true version = "0.8.0" -[dependencies.error-chain] -optional = true -version = "0.11.0" - [dependencies.serde_yaml] optional = true version = "0.7" [dev-dependencies] -lazy_static = "1.0.0" serde_derive = "1" tempfile = "2.1" [features] -bin = ["bincode", "base64", "error-chain"] +bin = ["bincode", "base64"] yaml = ["serde_yaml"] ron_enc = ["ron"] diff --git a/examples/config.rs b/examples/config.rs index b403fb9..395cf5b 100644 --- a/examples/config.rs +++ b/examples/config.rs @@ -13,18 +13,17 @@ extern crate rustbreak; #[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; -use std::fs::File; use std::path::PathBuf; use std::default::Default; -use rustbreak::Database; +use rustbreak::FileDatabase; use rustbreak::deser::Yaml; -type DB = Database; +type DB = FileDatabase; lazy_static! { static ref CONFIG: DB = { - let db = Database::from_path(Config::default(), "/tmp/config.yml").expect("Create database from path"); - let db = db.with_deser(Yaml); + let db = FileDatabase::from_path(Config::default(), Yaml, "/tmp/config.yml") + .expect("Create database from path"); db.reload().expect("Config to load"); db }; diff --git a/src/lib.rs b/src/lib.rs index 42c8013..7d638a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -47,9 +47,9 @@ //! //! ```rust //! # use std::collections::HashMap; -//! use rustbreak::Database; +//! use rustbreak::{MemoryDatabase, deser::Ron}; //! -//! let db = Database::>::memory(HashMap::new()); +//! let db = MemoryDatabase::, Ron>::memory(HashMap::new(), Ron); //! //! println!("Writing to Database"); //! db.write(|db| { @@ -191,12 +191,11 @@ impl Database } /// Read lock the database and get write access to the `Data` container - pub fn read(&self, task: T) -> error::Result<()> - where T: FnOnce(&Data) + pub fn read(&self, task: T) -> error::Result + where T: FnOnce(&Data) -> R { let mut lock = self.data.read().map_err(|_| error::RustbreakErrorKind::PoisonError)?; - task(&mut lock); - Ok(()) + Ok(task(&mut lock)) } /// Reload the Data from the backend @@ -253,3 +252,37 @@ impl Database }) } } + +/// An in memory backend +/// +/// It is backed by a `Vec` +pub struct MemoryBackend(Vec); + +impl Backend for MemoryBackend { + fn get_data(&mut self) -> error::Result> { + Ok(self.0.clone()) + } + + fn put_data(&mut self, data: &[u8]) -> error::Result<()> { + self.0 = data.to_owned(); + Ok(()) + } +} + +/// A database backed by a file +pub type MemoryDatabase = Database; + +impl Database + where + Data: Serialize + DeserializeOwned + Debug + Clone + Send, + DeSer: DeSerializer + Send + Sync +{ + /// Create new FileDatabase from Path + pub fn memory(data: Data, deser: DeSer) -> MemoryDatabase { + Database { + data: RwLock::new(data), + backend: Mutex::new(MemoryBackend(vec![])), + deser: deser, + } + } +}