From 0273237b76311df1fe6f7b2072cbd04f071e52ef Mon Sep 17 00:00:00 2001 From: Natsu Kagami Date: Tue, 11 Feb 2020 14:05:19 -0500 Subject: [PATCH] DB now only writes on borrow_mut --- youmubot-db/src/lib.rs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/youmubot-db/src/lib.rs b/youmubot-db/src/lib.rs index 974fc60..af734f0 100644 --- a/youmubot-db/src/lib.rs +++ b/youmubot-db/src/lib.rs @@ -2,9 +2,7 @@ use rustbreak::{deser::Yaml as Ron, FileDatabase}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serenity::{framework::standard::CommandError as Error, model::id::GuildId, prelude::*}; use std::collections::HashMap; -use std::path::Path; -use std::sync::Arc; - +use std::{cell::Cell, path::Path, sync::Arc}; /// GuildMap defines the guild-map type. /// It is basically a HashMap from a GuildId to a data structure. pub type GuildMap = HashMap; @@ -38,16 +36,23 @@ where /// The write guard for our FileDatabase. /// It wraps the FileDatabase in a write-on-drop lock. #[derive(Debug)] -pub struct DBWriteGuard(Arc>) +pub struct DBWriteGuard where - T: Send + Sync + Clone + std::fmt::Debug + Serialize + DeserializeOwned; + T: Send + Sync + Clone + std::fmt::Debug + Serialize + DeserializeOwned, +{ + db: Arc>, + needs_save: Cell, +} impl From>> for DBWriteGuard where T: Send + Sync + Clone + std::fmt::Debug + Serialize + DeserializeOwned, { fn from(v: Arc>) -> Self { - DBWriteGuard(v) + DBWriteGuard { + db: v, + needs_save: Cell::new(false), + } } } @@ -57,11 +62,12 @@ where { /// Borrows the FileDatabase. pub fn borrow(&self) -> Result, rustbreak::RustbreakError> { - (*self).0.borrow_data() + (*self).db.borrow_data() } /// Borrows the FileDatabase for writing. pub fn borrow_mut(&self) -> Result, rustbreak::RustbreakError> { - (*self).0.borrow_data_mut() + self.needs_save.set(true); + (*self).db.borrow_data_mut() } } @@ -70,8 +76,10 @@ where T: Send + Sync + Clone + std::fmt::Debug + Serialize + DeserializeOwned, { fn drop(&mut self) { - if let Err(e) = self.0.save() { - dbg!(e); + if self.needs_save.get() { + if let Err(e) = self.db.save() { + dbg!(e); + } } } }