|
@@ -1,5 +1,7 @@
|
|
|
//! Async version for `tokio`, need feature `tokio`.
|
|
|
//!
|
|
|
+//! NOTE: `AsyncGlobalContainer` use `RWLock`, `AsyncGlobalMutexContainer` use `Mutex`.
|
|
|
+//!
|
|
|
//! `lazy_static!` should be used for `AsyncGlobalContainer::new()`,
|
|
|
//! because of `tokio::sync::RwLock::new()` is not a constant function.
|
|
|
//!
|
|
@@ -65,7 +67,7 @@
|
|
|
|
|
|
use std::ops::Deref;
|
|
|
#[cfg(feature = "tokio")]
|
|
|
-use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
|
|
+use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard, Mutex, MutexGuard};
|
|
|
use crate::GOption;
|
|
|
|
|
|
|
|
@@ -134,3 +136,69 @@ impl<T> Drop for AsyncGlobalContainer<T> {
|
|
|
self.manual_drop();
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+#[cfg(feature = "tokio")]
|
|
|
+pub struct AsyncMutexGlobalContainer<T>
|
|
|
+{
|
|
|
+ content: Mutex<GOption<T>>,
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(feature = "tokio")]
|
|
|
+impl<T> AsyncMutexGlobalContainer<T> {
|
|
|
+ pub fn new() -> AsyncMutexGlobalContainer<T> {
|
|
|
+ AsyncMutexGlobalContainer::<T>{
|
|
|
+ content: Mutex::new(GOption::None),
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn set(&self, obj: T) {
|
|
|
+ *self.content.lock().await = GOption::Some(obj);
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn blocking_set(&self, obj: T) {
|
|
|
+ *self.content.blocking_lock() = GOption::Some(obj);
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn is_empty(&self) -> bool {
|
|
|
+ let v = self.content.lock().await;
|
|
|
+ match v.deref() {
|
|
|
+ GOption::None => true,
|
|
|
+ GOption::Some(_) => false,
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn is_empty_blocking(&self) -> bool {
|
|
|
+ let v = self.content.blocking_lock();
|
|
|
+ match v.deref() {
|
|
|
+ GOption::None => true,
|
|
|
+ GOption::Some(_) => false,
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn manual_drop(&self) {
|
|
|
+ *self.content.blocking_lock() = GOption::None;
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn get(&self) -> MutexGuard<GOption<T>> {
|
|
|
+ self.content.lock().await
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn get_mut(&self) -> MutexGuard<GOption<T>> {
|
|
|
+ self.content.lock().await
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn blocking_get(&self) -> MutexGuard<GOption<T>> {
|
|
|
+ self.content.blocking_lock()
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn blocking_get_mut(&self) -> MutexGuard<GOption<T>> {
|
|
|
+ self.content.blocking_lock()
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(feature = "tokio")]
|
|
|
+impl<T> Drop for AsyncMutexGlobalContainer<T> {
|
|
|
+ fn drop(&mut self) {
|
|
|
+ self.manual_drop();
|
|
|
+ }
|
|
|
+}
|