Skip to content

Commit

Permalink
Use arc and rwlock
Browse files Browse the repository at this point in the history
  • Loading branch information
RealHinome authored Mar 10, 2024
1 parent d95aa4d commit e123805
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions squid/src/helpers/database.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use crate::models::database::Entity;
use anyhow::Result;
use anyhow::{anyhow, Result};
use squid_algorithm::hashtable::MapAlgorithm;
use squid_db::Instance;
use std::sync::{Arc, RwLock};

/// The algorithms managed by Squid.
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum Algorithm {
Map(MapAlgorithm),
}
Expand All @@ -18,11 +19,17 @@ impl From<MapAlgorithm> for Algorithm {

/// Adds a value to the database and the algorithm.
pub fn set<A: Into<Algorithm>>(
instance: &mut Instance<Entity>,
instance: Arc<RwLock<Instance<Entity>>>,
algorithm: A,
value: Entity,
) -> Result<()> {
instance.set(value.clone())?;
instance
.write()
.map_err(|error| {
log::error!("Failed to mutate instance on `set`: {}", error);
anyhow!("cannot mutate instance")
})?
.set(value.clone())?;

match algorithm.into() {
Algorithm::Map(mut implementation) => {
Expand All @@ -37,11 +44,10 @@ pub fn set<A: Into<Algorithm>>(

/// Rank the most used words.
pub fn rank<A: Into<Algorithm>>(
instance: &mut Instance<Entity>,
algorithm: A,
length: usize,
) -> Result<Vec<String>> {
) -> Vec<(String, usize)> {
match algorithm.into() {
Algorithm::Map(implementation) => Ok(implementation.rank(length)),
Algorithm::Map(implementation) => implementation.rank(length),
}
}

0 comments on commit e123805

Please sign in to comment.