diff --git a/src/profile/bookmark.rs b/src/profile/bookmark.rs index 47a874fb..0468e17e 100644 --- a/src/profile/bookmark.rs +++ b/src/profile/bookmark.rs @@ -1,21 +1,49 @@ mod database; +mod memory; + use database::Database; +use memory::Memory; use sqlite::{Connection, Transaction}; use std::{rc::Rc, sync::RwLock}; pub struct Bookmark { - pub database: Rc, + database: Rc, + memory: Rc, } impl Bookmark { // Constructors + /// Create new `Self` pub fn new(connection: Rc>, profile_id: i64) -> Self { - Self { - database: Rc::new(Database::new(connection, profile_id)), + // Init children components + let database = Rc::new(Database::new(connection, profile_id)); + let memory = Rc::new(Memory::new()); + + // Build initial index + for record in database.records(None) { + memory.set(record.request, record.time) + } + + // Return new `Self` + Self { database, memory } + } + + // Actions + + /// Check request exist in: + /// * memory if `is_memory` is `true` (fast) + /// * database if `is_memory` is `false` (slow) + pub fn has_request(&self, request: &str, is_memory: bool) -> bool { + if is_memory { + self.memory.is_exist(request) + } else { + !self.database.records(Some(request)).is_empty() } } + + // @TODO add new record with index update } // Tools diff --git a/src/profile/bookmark/memory.rs b/src/profile/bookmark/memory.rs new file mode 100644 index 00000000..95b519ec --- /dev/null +++ b/src/profile/bookmark/memory.rs @@ -0,0 +1,38 @@ +use gtk::glib::DateTime; +use std::{cell::RefCell, collections::HashMap}; + +/// Reduce disk usage by cache results in memory +pub struct Memory { + index: RefCell>, +} + +impl Memory { + // Constructors + + pub fn new() -> Self { + Self { + index: RefCell::new(HashMap::new()), + } + } + + // Actions + + /// Set new record + /// * replace existing record with new value + pub fn set(&self, request: String, time: DateTime) { + // Borrow index to update + let mut index = self.index.borrow_mut(); + + // Cleanup previous record + if index.get(&request).is_some() { + index.remove(&request); + } + + // Insert new record with actual data + index.insert(request, time); + } + + pub fn is_exist(&self, request: &str) -> bool { + self.index.borrow().get(request).is_some() + } +}