Files
continuwuity/src/service/globals/data.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

71 lines
1.5 KiB
Rust
Raw Normal View History

use std::sync::Arc;
2022-10-05 15:33:57 +02:00
use conduwuit::{Result, SyncRwLock, utils};
use database::{Database, Deserialized, Map};
2024-05-26 21:29:19 +00:00
2024-05-27 03:17:20 +00:00
pub struct Data {
2024-06-28 22:51:39 +00:00
global: Arc<Map>,
counter: SyncRwLock<u64>,
2024-07-18 06:37:47 +00:00
pub(super) db: Arc<Database>,
2022-09-07 13:25:51 +02:00
}
2024-05-26 21:29:19 +00:00
2024-07-13 08:07:49 +00:00
const COUNTER: &[u8] = b"c";
2024-05-27 03:17:20 +00:00
impl Data {
2024-07-18 06:37:47 +00:00
pub(super) fn new(args: &crate::Args<'_>) -> Self {
let db = &args.db;
2024-05-27 03:17:20 +00:00
Self {
2024-06-28 22:51:39 +00:00
global: db["global"].clone(),
counter: SyncRwLock::new(Self::stored_count(&db["global"]).unwrap_or_default()),
2024-07-18 06:37:47 +00:00
db: args.db.clone(),
2024-05-27 03:17:20 +00:00
}
}
pub fn next_count(&self) -> Result<u64> {
let _cork = self.db.cork();
let mut lock = self.counter.write();
2024-07-02 07:56:45 +00:00
let counter: &mut u64 = &mut lock;
debug_assert!(
*counter == Self::stored_count(&self.global).unwrap_or_default(),
2024-07-02 07:56:45 +00:00
"counter mismatch"
);
*counter = counter.checked_add(1).unwrap_or(*counter);
2024-07-07 04:46:16 +00:00
2024-10-07 17:54:27 +00:00
self.global.insert(COUNTER, counter.to_be_bytes());
2024-07-02 07:56:45 +00:00
Ok(*counter)
2024-05-26 21:29:19 +00:00
}
2024-07-02 07:56:45 +00:00
#[inline]
pub fn current_count(&self) -> u64 {
let lock = self.counter.read();
2024-07-02 07:56:45 +00:00
let counter: &u64 = &lock;
debug_assert!(
*counter == Self::stored_count(&self.global).unwrap_or_default(),
2024-07-02 07:56:45 +00:00
"counter mismatch"
);
*counter
}
fn stored_count(global: &Arc<Map>) -> Result<u64> {
global
2024-09-29 07:37:43 +00:00
.get_blocking(COUNTER)
2024-07-02 07:56:45 +00:00
.as_deref()
.map_or(Ok(0_u64), utils::u64_from_bytes)
2024-05-26 21:29:19 +00:00
}
pub async fn database_version(&self) -> u64 {
self.global
.get(b"version")
.await
.deserialized()
.unwrap_or(0)
}
2024-05-26 21:29:19 +00:00
#[inline]
pub fn bump_database_version(&self, new_version: u64) {
2024-10-07 17:54:27 +00:00
self.global.raw_put(b"version", new_version);
2024-05-26 21:29:19 +00:00
}
}