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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
pub mod destination;
pub mod inbound;
pub mod outbound;

use crate::{Result, SolClientReturnCode, SolaceError};
pub use destination::{DestinationType, MessageDestination};
use enum_primitive::*;
pub use inbound::InboundMessage;
pub use outbound::{OutboundMessage, OutboundMessageBuilder};
use solace_rs_sys as ffi;
use std::ffi::CStr;
use std::mem;
use std::ptr;

enum_from_primitive! {
    #[derive(Debug, PartialEq, Eq)]
    #[repr(u32)]
    pub enum DeliveryMode {
        Direct=ffi::SOLCLIENT_DELIVERY_MODE_DIRECT,
        Persistent=ffi::SOLCLIENT_DELIVERY_MODE_PERSISTENT,
        NonPersistent=ffi::SOLCLIENT_DELIVERY_MODE_NONPERSISTENT
    }
}

enum_from_primitive! {
    #[derive(Debug, PartialEq, Eq)]
    #[repr(u32)]
    pub enum ClassOfService {
        One=ffi::SOLCLIENT_COS_1,
        Two=ffi::SOLCLIENT_COS_2,
        Three=ffi::SOLCLIENT_COS_3,
    }
}

impl From<ClassOfService> for u32 {
    fn from(val: ClassOfService) -> Self {
        match val {
            ClassOfService::One => ffi::SOLCLIENT_COS_1,
            ClassOfService::Two => ffi::SOLCLIENT_COS_2,
            ClassOfService::Three => ffi::SOLCLIENT_COS_3,
        }
    }
}

pub trait Message<'a> {
    /// .
    ///
    /// # Safety
    ///
    /// Should return ptr to a owned valid message.
    /// No other alias for the ptr should exists.
    /// Other methods will not check if the message is valid or not
    ///
    /// .
    unsafe fn get_raw_message_ptr(&'a self) -> ffi::solClient_opaqueMsg_pt;

    fn get_payload(&'a self) -> Result<&'a [u8]> {
        let mut buffer = ptr::null_mut();
        let mut buffer_len: u32 = 0;

        let msg_ops_result = unsafe {
            ffi::solClient_msg_getBinaryAttachmentPtr(
                self.get_raw_message_ptr(),
                &mut buffer,
                &mut buffer_len,
            )
        };

        if SolClientReturnCode::from_i32(msg_ops_result) != Some(SolClientReturnCode::Ok) {
            return Err(SolaceError);
        }

        // not supported if u32 cannot be converted to usize
        // maybe we can add a check at compile time?
        let buf_len = buffer_len.try_into().unwrap();

        let safe_slice = unsafe { std::slice::from_raw_parts(buffer as *const u8, buf_len) };

        Ok(safe_slice)
    }

    fn get_application_message_id(&'a self) -> Option<&'a str> {
        let mut buffer = ptr::null();

        let op_result = unsafe {
            ffi::solClient_msg_getApplicationMessageId(self.get_raw_message_ptr(), &mut buffer)
        };

        if SolClientReturnCode::from_i32(op_result) != Some(SolClientReturnCode::Ok) {
            return None;
        }

        let c_str = unsafe { CStr::from_ptr(buffer) };

        c_str.to_str().ok()
    }

    fn get_application_msg_type(&'a self) -> Option<&'a str> {
        let mut buffer = ptr::null();

        let op_result = unsafe {
            ffi::solClient_msg_getApplicationMsgType(self.get_raw_message_ptr(), &mut buffer)
        };

        if SolClientReturnCode::from_i32(op_result) != Some(SolClientReturnCode::Ok) {
            return None;
        }

        let c_str = unsafe { CStr::from_ptr(buffer) };

        c_str.to_str().ok()
    }

    fn get_class_of_service(&'a self) -> Result<ClassOfService> {
        let mut cos: u32 = 0;
        let cos_result =
            unsafe { ffi::solClient_msg_getClassOfService(self.get_raw_message_ptr(), &mut cos) };

        if SolClientReturnCode::from_i32(cos_result) != Some(SolClientReturnCode::Ok) {
            return Err(SolaceError);
        }

        let Some(cos) = ClassOfService::from_u32(cos) else {
            return Err(SolaceError);
        };

        Ok(cos)
    }

    fn get_correlation_id(&'a self) -> Result<&'a str> {
        let mut buffer = ptr::null();

        let msg_ops_result =
            unsafe { ffi::solClient_msg_getCorrelationId(self.get_raw_message_ptr(), &mut buffer) };

        if SolClientReturnCode::from_i32(msg_ops_result) != Some(SolClientReturnCode::Ok) {
            return Err(SolaceError);
        }

        let c_str = unsafe { CStr::from_ptr(buffer) };
        return c_str.to_str().map_err(|_| SolaceError);
    }

    fn get_expiration(&'a self) -> i64 {
        let mut exp: i64 = 0;
        unsafe { ffi::solClient_msg_getExpiration(self.get_raw_message_ptr(), &mut exp) };

        exp
    }

    fn get_priority(&'a self) -> Result<Option<u8>> {
        let mut priority: i32 = 0;
        let op_result =
            unsafe { ffi::solClient_msg_getPriority(self.get_raw_message_ptr(), &mut priority) };

        if Some(SolClientReturnCode::Ok) != SolClientReturnCode::from_i32(op_result) {
            return Err(SolaceError);
        }

        if priority == -1 {
            return Ok(None);
        }

        Ok(Some(priority as u8))
    }

    fn get_sequence_number(&'a self) -> Result<Option<i64>> {
        let mut seq_num: i64 = 0;
        let op_result = unsafe {
            ffi::solClient_msg_getSequenceNumber(self.get_raw_message_ptr(), &mut seq_num)
        };
        match SolClientReturnCode::from_i32(op_result) {
            Some(SolClientReturnCode::Ok) => Ok(Some(seq_num)),
            Some(SolClientReturnCode::NotFound) => Ok(None),
            _ => Err(SolaceError),
        }
    }

    fn get_destination(&'a self) -> Result<Option<MessageDestination>> {
        let mut dest_struct: ffi::solClient_destination = ffi::solClient_destination {
            destType: ffi::solClient_destinationType_SOLCLIENT_NULL_DESTINATION,
            dest: ptr::null_mut(),
        };

        let msg_ops_result = unsafe {
            ffi::solClient_msg_getDestination(
                self.get_raw_message_ptr(),
                &mut dest_struct,
                mem::size_of::<ffi::solClient_destination>(),
            )
        };
        if SolClientReturnCode::from_i32(msg_ops_result) == Some(SolClientReturnCode::NotFound) {
            return Ok(None);
        }

        if SolClientReturnCode::from_i32(msg_ops_result) == Some(SolClientReturnCode::Fail) {
            return Err(SolaceError);
        }

        Ok(Some(MessageDestination::from(dest_struct)))
    }
}