1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::any::Any;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::time::Duration;

const MSGDEFAULT:&'static str = "wd-event-default-msg";

pub struct Context{
    status:AtomicBool, //向事件系统交互,是否停止后续事件
    delay:std::time::Duration,
    messages:RwLock<HashMap<String,Arc<dyn Any>>>
}
unsafe impl Send for Context{}
unsafe impl Sync for Context{}

impl Context{
    pub fn new_null()->Self{
        Context{
            status:AtomicBool::new(true),
            delay:std::time::Duration::from_millis(0),
            messages:RwLock::new(HashMap::new()),
        }
    }
    pub fn new_add_msg<V:Any>(msg:V)->Self{
        let ctx = Self::new_null();
        ctx.set_value(MSGDEFAULT,msg);
        return ctx
    }
    pub fn new_delay(t:std::time::Duration,cycle:bool)->Self{
        let mut ctx = Self::new_null();
        ctx.set_status(cycle);
        ctx.delay = t;
        return ctx
    }
    pub fn get_msg<T:'static>(&self)->Option<Arc<T>>{
        if let Some(s)= self.get_value_raw(&MSGDEFAULT.to_string()){
            let ss = s.clone();
            if let Some(a) = ss.downcast_ref::<Arc<T>>(){
                return Some(a.clone())
            };
        }
        return None
    }
    pub fn get_delay(&self) -> Duration {
        self.delay.clone()
    }
    pub fn set_value<K:ToString,V:Any>(&self, key:K, value:V){
        let arc_value = Arc::new(value);
        if let Ok(mut msgs) = self.messages.write(){
            msgs.insert(key.to_string(),Arc::new(arc_value));
        }
    }
    pub fn get_value_raw<K: ToString>(&self, key:&K) ->Option<Arc<dyn Any>>{
        if let Ok(msgs) = self.messages.read(){
            let key = key.to_string();
            match msgs.get(&key){
                Some(s)=>{
                    return Some(s.clone())
                }
                None=>{}
            }
        }
        return None
    }

    /// 获取指定类型的数据,该类型需要实现Clone
    ///
    /// ```rust
    /// let value:&str = match ctx.get_value("haha"){
    ///     Some(s)=>{s}
    ///     None=>{"haha"}
    /// };
    ///```
    pub fn get_value<K: ToString,T:Clone + 'static>(&self, key:&K) ->Option<T>{
        if let Some(s)= self.get_value_raw(&key.to_string()){
            let ss = s.clone();
            if let Some(a) = ss.downcast_ref::<Arc<T>>(){
                return Some(a.as_ref().clone())
            };
        }
        return None
    }

    pub fn get_arc_value<K: ToString,T:'static>(&self, key:&K) ->Option<Arc<T>>{
        if let Some(s)= self.get_value_raw(&key.to_string()){
            let ss = s.clone();
            if let Some(a) = ss.downcast_ref::<Arc<T>>(){
                return Some(a.clone())
            };
        }
        return None
    }

    /// 在顺序执行的事件中,如果检测到状态失败,则不再执行后续回调
    pub fn set_status(&self,status:bool){
        self.status.store(status,Ordering::Relaxed);
    }
    pub fn get_status(&self)->bool{
        return self.status.load(Ordering::Relaxed)
    }
}