Browse Source

Add feature `tokio`.

ZRY 1 year ago
parent
commit
11cafcfeb5
2 changed files with 60 additions and 5 deletions
  1. 8 1
      Cargo.toml
  2. 52 4
      src/lib.rs

+ 8 - 1
Cargo.toml

@@ -1,12 +1,19 @@
 [package]
 name = "simple-rw-global"
-version = "0.1.0"
+version = "0.2.0"
 edition = "2021"
 authors = ["ZRY <admin@>z-touhou.org"]
+
 description = "Simple GlobalContainer based on std::sync::RwLock."
 readme = "README.md"
 repository = "https://git.swzry.com/zry/simple-rw-global"
 homepage = "https://git.swzry.com/zry/simple-rw-global"
 license = "MIT"
 
+[features]
+default = ["stdsync"]
+stdsync=[]
+tokio=["dep:tokio"]
+
 [dependencies]
+tokio = { version="1.28.0", optional=true, features=["sync"] }

+ 52 - 4
src/lib.rs

@@ -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
+    }
+}