azure_iot_rs/
message.rs

1use azure_iot_rs_sys::*;
2use std::ffi::{CStr};
3
4/// Enum to return the type of an IOT hub message.
5#[derive(Debug)]
6pub enum MessageBody<'b> {
7    Text(&'b str),
8    Binary(&'b [u8])
9}
10
11/// A struct to represet an IOT hub message.
12#[derive(Debug)]
13pub struct IotHubMessage {
14    pub(crate) handle: IOTHUB_MESSAGE_HANDLE,
15    own: bool
16}
17
18impl Drop for IotHubMessage {
19    fn drop(&mut self) {
20        if self.own {
21            unsafe {
22                IoTHubMessage_Destroy(self.handle);
23            }    
24        }
25    }
26}
27
28impl Clone for IotHubMessage {
29    fn clone(&self) -> Self {
30        let handle = unsafe { IoTHubMessage_Clone(self.handle) };
31        if handle == std::ptr::null_mut() {
32            panic!("Failed to allocate message");
33        }
34        return IotHubMessage {
35            handle, 
36            own: true
37        }
38    }
39}
40
41impl IotHubMessage {
42    fn get_array<'a>(&'a self) -> &'a [u8] {
43        let buffer: *mut *const ::std::os::raw::c_uchar = std::ptr::null_mut();
44        let size: *mut usize  = std::ptr::null_mut();
45        unsafe { 
46            IoTHubMessage_GetByteArray(self.handle, buffer, size); 
47            std::slice::from_raw_parts(*buffer, *size as usize)
48        }
49    }
50
51    fn get_text<'a>(&'a self) -> &'a str {
52        let ptr = unsafe { IoTHubMessage_GetString(self.handle) };
53        if ptr  ==  std::ptr::null() {
54            return "";
55        }
56        match unsafe { CStr::from_ptr(ptr).to_str() } {
57             Ok(string) => string,
58             _ => ""
59        }
60    }
61
62    pub fn content_type(&self) -> IOTHUBMESSAGE_CONTENT_TYPE {
63        unsafe { IoTHubMessage_GetContentType(self.handle) }
64    }
65
66    pub fn from_handle(handle: IOTHUB_MESSAGE_HANDLE) -> Self {
67        return IotHubMessage {
68            handle,
69            own: false
70        }
71    }
72
73    pub fn body<'a>(&'a self) -> MessageBody<'a> {
74        let content_type = self.content_type();
75        return match content_type {
76            IOTHUBMESSAGE_CONTENT_TYPE_TAG_IOTHUBMESSAGE_STRING => MessageBody::Text(self.get_text()),
77            IOTHUBMESSAGE_CONTENT_TYPE_TAG_IOTHUBMESSAGE_BYTEARRAY => MessageBody::Binary(self.get_array()),
78            _ => panic!("Unknown content type")
79        }
80    }
81}
82