use std::net::SocketAddr;
use libcoap_sys::{coap_endpoint_t, coap_free_endpoint, coap_new_endpoint, coap_proto_t::COAP_PROTO_UDP};
use crate::{context::CoapContext, error::EndpointCreationError, transport::EndpointCommon, types::CoapAddress};
#[derive(Debug)]
pub struct CoapUdpEndpoint {
raw_endpoint: *mut coap_endpoint_t,
}
impl CoapUdpEndpoint {
pub(crate) unsafe fn new(
context: &mut CoapContext,
addr: SocketAddr,
) -> Result<CoapUdpEndpoint, EndpointCreationError> {
let endpoint = coap_new_endpoint(
context.as_mut_raw_context(),
CoapAddress::from(addr).as_raw_address(),
COAP_PROTO_UDP,
);
if endpoint.is_null() {
return Err(EndpointCreationError::Unknown);
}
Ok(CoapUdpEndpoint { raw_endpoint: endpoint })
}
}
impl EndpointCommon for CoapUdpEndpoint {
unsafe fn as_raw_endpoint(&self) -> &coap_endpoint_t {
&*self.raw_endpoint
}
unsafe fn as_mut_raw_endpoint(&mut self) -> &mut coap_endpoint_t {
&mut *self.raw_endpoint
}
}
impl Drop for CoapUdpEndpoint {
fn drop(&mut self) {
unsafe { coap_free_endpoint(self.raw_endpoint) }
}
}