smol bot
Diffstat (limited to 'src/bot/ownership.rs')
-rw-r--r--src/bot/ownership.rs65
1 files changed, 38 insertions, 27 deletions
diff --git a/src/bot/ownership.rs b/src/bot/ownership.rs
index ab8639a..12a3fc3 100644
--- a/src/bot/ownership.rs
+++ b/src/bot/ownership.rs
@@ -1,33 +1,44 @@
use serenity::all::MessageId;
-use std::{collections::HashMap, sync::LazyLock};
-use tokio::sync::Mutex;
+use std::collections::HashMap;
+use tokio::sync::MutexGuard;
-pub static MAP: LazyLock<Mutex<HashMap<u64, (String, u64)>>> = LazyLock::new(|| {
- Mutex::new(serde_json::from_slice(&std::fs::read("repo/ownership.json").unwrap()).unwrap())
-});
-
-pub async fn insert(k: u64, v: (String, u64)) {
- let mut lock = MAP.lock().await;
- lock.insert(k, v);
- std::fs::write(
- "repo/ownership.json",
- serde_json::to_string_pretty(&*lock).unwrap(),
- )
- .unwrap();
+pub struct Ownership {
+ pub map: HashMap<u64, (String, u64)>,
+ path: &'static str,
}
-pub async fn get(k: u64) -> (String, u64) {
- MAP.lock().await[&k].clone()
+impl Ownership {
+ pub fn new(id: u64) -> Self {
+ let path = format!("repos/{id:x}/ownership.json").leak();
+ Self {
+ map: serde_json::from_slice(&std::fs::read(&path).unwrap_or_default())
+ .unwrap_or_default(),
+ path,
+ }
+ }
+
+ pub fn insert(&mut self, k: u64, v: (String, u64)) {
+ self.map.insert(k, v);
+ self.flush();
+ }
+ fn flush(&self) {
+ std::fs::write(&self.path, serde_json::to_string_pretty(&self.map).unwrap()).unwrap();
+ }
+ pub fn get(&self, k: u64) -> &(String, u64) {
+ self.map.get(&k).unwrap()
+ }
+ pub fn erase(&mut self, k: impl Into<u64>) -> Option<String> {
+ let x = self.map.remove(&k.into()).map(|(x, _)| x);
+ self.flush();
+ x
+ }
+
+ pub fn whos(&self, x: impl Into<MessageId>) -> &str {
+ &self.get(x.into().get()).0
+ }
}
-pub async fn erase(k: u64) -> Option<String> {
- let mut lock = MAP.lock().await;
- let x = lock.remove(&k).map(|(x, _)| x);
- std::fs::write(
- "repo/ownership.json",
- serde_json::to_string_pretty(&*lock).unwrap(),
- )
- .unwrap();
- x
+pub async fn whos(g: u64, x: impl Into<u64>) -> String {
+ super::repos::REPOS[&g].own().await.get(x.into()).0.clone()
}
-pub async fn whos(x: impl Into<MessageId>) -> String {
- get(x.into().get()).await.0
+pub async fn get(g: impl Into<u64>) -> MutexGuard<'static, Ownership> {
+ super::repos::REPOS[&g.into()].own().await
}