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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use self::protocol_v1::ProtocolV1Reader;
use crate::service::sys_service_api::ServiceKey;
use std::hash::Hash;

pub mod protocol_ipc;
pub mod protocol_v1;


// 
pub const IPC_INITED_REQ_ID: i64 = -1;
pub const SYSTEM_CALL_FINALIZE_REQ_ID: i64 = -2;


#[derive(PartialEq, Debug)]
pub enum MsgType {
    HeartBit,          //心跳
    NormalMsg,         // 普通消息
    RspNormalMsg,      // 回应普通消息
    AckNormalMsg,      //确认消息
    System, //  系统消息
}

impl MsgType {
    fn from(value: i32) -> Option<Self> {
        match value {
            0 => Some(MsgType::HeartBit),
            1 => Some(MsgType::NormalMsg),
            2 => Some(MsgType::RspNormalMsg),
            3 => Some(MsgType::AckNormalMsg),
            4 => Some(MsgType::System),
            _ => None,
        }
    }
}

#[derive(Copy, Clone)]
pub struct XID {
    pub conn_id: i64,
    pub request_id: i64,
}

impl Hash for XID {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.conn_id.hash(state);
        self.request_id.hash(state);
    }
}

impl PartialEq for XID {
    fn eq(&self, other: &Self) -> bool {
        self.conn_id == other.conn_id && self.request_id == other.request_id
    }
}
impl Eq for XID {}

impl Default for XID {
    fn default() -> XID {
        XID {
            conn_id: 0,
            request_id: 0,
        }
    }
}
impl XID {
    pub fn new(conn_id: i64, msg_id: i64) -> Self {
        XID {
            conn_id,
            request_id: msg_id,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.request_id == 0
    }
}

/**
 *  ======= 读取内容 ======
 */
pub fn get_version(message: &[u8]) -> u16 {
    unsafe {
        let ptr = message.as_ptr().offset(4);
        let bytes = *(ptr as *const [u8; 2]);
        u16::from_le_bytes(bytes)
    }
}

pub fn get_msg_type(message: &[u8]) -> Option<MsgType> {
    let version = get_version(message);
    match version {
        1 => {
            let v1_reader = ProtocolV1Reader::new(message);

            v1_reader.msg_type()
        }
        _ => None,
    }
}

pub fn get_sender_service_key(message: &[u8]) -> Option<ServiceKey> {
    let version = get_version(message);
    match version {
        1 => {
            let v1_reader = ProtocolV1Reader::new(message);

            Some(v1_reader.sender())
        }
        _ => None,
    }
}

pub fn get_receiver_service_key(message: &[u8]) -> Option<ServiceKey> {
    let version = get_version(message);

    match version {
        1 => {
            let v1_reader = ProtocolV1Reader::new(message);
            Some(v1_reader.receiver())
        }
        _ => None,
    }
}