|
@@ -0,0 +1,71 @@
|
|
|
+use std::ops::{Deref, DerefMut};
|
|
|
+use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
|
|
+
|
|
|
+pub enum GOption<T> {
|
|
|
+ None,
|
|
|
+ Some(T)
|
|
|
+}
|
|
|
+
|
|
|
+impl<T> Deref for GOption<T> {
|
|
|
+ type Target = T;
|
|
|
+
|
|
|
+ fn deref(&self) -> &Self::Target {
|
|
|
+ match self {
|
|
|
+ GOption::None => { panic!("operate on empty GlobalContainer"); },
|
|
|
+ GOption::Some(t) => t,
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl<T> DerefMut for GOption<T> {
|
|
|
+
|
|
|
+ fn deref_mut(&mut self) -> &mut Self::Target {
|
|
|
+ match self {
|
|
|
+ GOption::None => { panic!("operate on empty GlobalContainer"); },
|
|
|
+ GOption::Some(t) => t,
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+pub struct GlobalContainer<T>
|
|
|
+{
|
|
|
+ content: RwLock<GOption<T>>,
|
|
|
+}
|
|
|
+
|
|
|
+impl<T> GlobalContainer<T> {
|
|
|
+ pub const fn new() -> GlobalContainer<T> {
|
|
|
+ GlobalContainer::<T>{
|
|
|
+ content: RwLock::new(GOption::None),
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn set(&self, obj: T) {
|
|
|
+ *self.content.write().unwrap() = GOption::Some(obj);
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn is_empty(&self) -> bool {
|
|
|
+ let v = self.content.read().unwrap();
|
|
|
+ match v.deref() {
|
|
|
+ GOption::None => true,
|
|
|
+ GOption::Some(_) => false,
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn manual_drop(&self) {
|
|
|
+ *self.content.write().unwrap() = GOption::None;
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn get(&self) -> RwLockReadGuard<GOption<T>> {
|
|
|
+ self.content.read().unwrap()
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn get_mut(&self) -> RwLockWriteGuard<GOption<T>> {
|
|
|
+ self.content.write().unwrap()
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl<T> Drop for GlobalContainer<T> {
|
|
|
+ fn drop(&mut self) {
|
|
|
+ self.manual_drop();
|
|
|
+ }
|
|
|
+}
|