libcoap_rs/
transport.rs

1// SPDX-License-Identifier: BSD-2-Clause
2/*
3 * Copyright © The libcoap-rs Contributors, all rights reserved.
4 * This file is part of the libcoap-rs project, see the README file for
5 * general information on this project and the NOTICE.md and LICENSE files
6 * for information regarding copyright ownership and terms of use.
7 *
8 * transport.rs - CoAP transports.
9 */
10
11use std::{net::SocketAddr, os::raw::c_uint};
12
13use libcoap_sys::{
14    coap_endpoint_set_default_mtu, coap_endpoint_t, coap_free_endpoint, coap_new_endpoint, coap_proto_t,
15};
16
17use crate::{error::EndpointCreationError, types::CoapAddress, CoapContext};
18
19pub type EndpointMtu = c_uint;
20
21#[derive(Debug)]
22pub struct CoapEndpoint {
23    raw_endpoint: *mut coap_endpoint_t,
24}
25
26/// Trait for functions common between all types of endpoints.
27impl CoapEndpoint {
28    /// Sets the default MTU value of the endpoint.
29    pub fn set_default_mtu(&mut self, mtu: EndpointMtu) {
30        // SAFETY: as_mut_raw_endpoint cannot fail and will always return a valid reference.
31        // Modifying the state of the endpoint is also fine, because we have a mutable reference
32        // of the whole endpoint.
33        unsafe {
34            coap_endpoint_set_default_mtu(&mut *self.raw_endpoint, mtu);
35        }
36    }
37
38    /// Method utilized by transport protocol specific constructors to actually create the endpoint in libcoap
39    pub(crate) fn new_endpoint(
40        context: &mut CoapContext,
41        addr: SocketAddr,
42        proto: coap_proto_t,
43    ) -> Result<Self, EndpointCreationError> {
44        let endpoint = unsafe {
45            // SAFETY: coap_new_endpoint will return null if it is unable to add new endpoint.
46            // These states are processed further in the code
47            coap_new_endpoint(
48                context.as_mut_raw_context(),
49                CoapAddress::from(addr).as_raw_address(),
50                proto,
51            )
52        };
53
54        if endpoint.is_null() {
55            Err(EndpointCreationError::Unknown)
56        } else {
57            Ok(Self { raw_endpoint: endpoint })
58        }
59    }
60}
61
62impl Drop for CoapEndpoint {
63    fn drop(&mut self) {
64        // SAFETY: Raw endpoint is guaranteed to exist for as long as the container exists.
65        unsafe { coap_free_endpoint(self.raw_endpoint) }
66    }
67}