Skip to content

Commit

Permalink
feature: support rw lock & display
Browse files Browse the repository at this point in the history
  • Loading branch information
tyrchen committed Mar 30, 2024
1 parent 5ea969f commit 25c6257
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
2 changes: 1 addition & 1 deletion examples/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn main() -> Result<()> {

loop {
thread::sleep(Duration::from_secs(2));
println!("{:?}", metrics.snapshot());
println!("{}", metrics);
}
}

Expand Down
21 changes: 16 additions & 5 deletions src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
use anyhow::{anyhow, Result};
use std::{
collections::HashMap,
sync::{Arc, Mutex},
fmt,
sync::{Arc, RwLock},
};

#[derive(Debug, Clone)]
pub struct Metrics {
data: Arc<Mutex<HashMap<String, i64>>>,
data: Arc<RwLock<HashMap<String, i64>>>,
}

impl Default for Metrics {
Expand All @@ -21,12 +22,12 @@ impl Default for Metrics {
impl Metrics {
pub fn new() -> Self {
Metrics {
data: Arc::new(Mutex::new(HashMap::new())),
data: Arc::new(RwLock::new(HashMap::new())),
}
}

pub fn inc(&self, key: impl Into<String>) -> Result<()> {
let mut data = self.data.lock().map_err(|e| anyhow!(e.to_string()))?;
let mut data = self.data.write().map_err(|e| anyhow!(e.to_string()))?;
let counter = data.entry(key.into()).or_insert(0);
*counter += 1;
Ok(())
Expand All @@ -35,8 +36,18 @@ impl Metrics {
pub fn snapshot(&self) -> Result<HashMap<String, i64>> {
Ok(self
.data
.lock()
.read()
.map_err(|e| anyhow!(e.to_string()))?
.clone())
}
}

impl fmt::Display for Metrics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let data = self.data.read().map_err(|_e| fmt::Error {})?;
for (key, value) in data.iter() {
writeln!(f, "{}: {}", key, value)?;
}
Ok(())
}
}

0 comments on commit 25c6257

Please sign in to comment.