|
@@ -4,6 +4,20 @@
|
|
|
//!
|
|
|
//! By ZRY.
|
|
|
//!
|
|
|
+//! # Features
|
|
|
+//!
|
|
|
+//! ## `tokio`
|
|
|
+//!
|
|
|
+//! For tokio, use feature `tokio`
|
|
|
+//!
|
|
|
+//! ```toml
|
|
|
+//! [dependency]
|
|
|
+//! simple-rw-global = { version="0.2.0", default-features = false, feature=["tokio"] }
|
|
|
+//! ```
|
|
|
+//!
|
|
|
+//! With this feature, `lazy_static!` should be used for `GlobalContainer::new()`,
|
|
|
+//! because of `tokio::sync::RwLock::new()` is not a constant function.
|
|
|
+//!
|
|
|
//! # Example:
|
|
|
//!
|
|
|
//! ```
|
|
@@ -47,7 +61,13 @@
|
|
|
//!
|
|
|
|
|
|
use std::ops::{Deref, DerefMut};
|
|
|
+#[cfg(feature = "stdsync")]
|
|
|
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
|
|
+#[cfg(feature = "tokio")]
|
|
|
+use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
|
|
+
|
|
|
+#[cfg(all(feature = "stdsync", feature = "tokio"))]
|
|
|
+compile_error!("feature \"std\" and feature \"tokio\" cannot be enabled at the same time");
|
|
|
|
|
|
pub enum GOption<T> {
|
|
|
None,
|
|
@@ -80,6 +100,7 @@ pub struct GlobalContainer<T>
|
|
|
content: RwLock<GOption<T>>,
|
|
|
}
|
|
|
|
|
|
+#[cfg(feature = "stdsync")]
|
|
|
impl<T> GlobalContainer<T> {
|
|
|
pub const fn new() -> GlobalContainer<T> {
|
|
|
GlobalContainer::<T>{
|
|
@@ -112,8 +133,35 @@ impl<T> GlobalContainer<T> {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
-impl<T> Drop for GlobalContainer<T> {
|
|
|
- fn drop(&mut self) {
|
|
|
- self.manual_drop();
|
|
|
+#[cfg(feature = "tokio")]
|
|
|
+impl<T> GlobalContainer<T> {
|
|
|
+ pub fn new() -> GlobalContainer<T> {
|
|
|
+ GlobalContainer::<T>{
|
|
|
+ content: RwLock::new(GOption::None),
|
|
|
+ }
|
|
|
}
|
|
|
-}
|
|
|
+
|
|
|
+ pub async fn set(&self, obj: T) {
|
|
|
+ *self.content.write().await = GOption::Some(obj);
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn is_empty(&self) -> bool {
|
|
|
+ let v = self.content.read().await;
|
|
|
+ match v.deref() {
|
|
|
+ GOption::None => true,
|
|
|
+ GOption::Some(_) => false,
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn manual_drop(&self) {
|
|
|
+ *self.content.write().await = GOption::None;
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn get(&self) -> RwLockReadGuard<GOption<T>> {
|
|
|
+ self.content.read().await
|
|
|
+ }
|
|
|
+
|
|
|
+ pub async fn get_mut(&self) -> RwLockWriteGuard<GOption<T>> {
|
|
|
+ self.content.write().await
|
|
|
+ }
|
|
|
+}
|