coap_handler/
core_implementations.rs

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
//! This module provides implementations of [Handler]

use crate::{Handler, PausedOperation, Reporting, Request, Response};
use coap_message::MinimalWritableMessage;
use coap_numbers::code;

/// An easy way to have resources that may or may not be there in a tree, considering that Handler
/// is not object safe and thus, `if let Some(x) { all = all.at(...) }` won't work.
///
/// This returns 4.04 Not Found if the inner handler is absent, and otherwise forwards request and
/// response building.
impl<H> Handler for Option<H>
where
    H: Handler,
{
    type Error<M: MinimalWritableMessage> = Result<H::Error<M>, M::UnionError>;

    async fn handle<R: Request>(
        &mut self,
        request: R,
    ) -> Result<<R as Request>::ResponseDone, Self::Error<<R as Request>::ResponseMessage>> {
        let Some(slef) = self.as_mut() else {
            // We don't have an error handler on our own, but panicking when something can't do
            // 4.04 is probably OK
            let mut response = request.done().respond(0).await;
            let response_msg = response.response();
            use coap_message::Code;
            response_msg
                .set_code(Code::new(code::NOT_FOUND).expect("What server can't do a 4.04?"));
            return Ok(response.done());
        };
        slef.handle(request).await.map_err(Ok)
    }
}

impl<H> Reporting for Option<H>
where
    H: Reporting,
{
    type Record<'res> = H::Record<'res>
    where
        Self: 'res;
    type Reporter<'res> = OptionReporter<'res, H>
    where
        Self: 'res;

    fn report(&self) -> Self::Reporter<'_> {
        // This could be as simple as
        //
        // self.into_iter().map(|h| H::report(h)).into_iter().flatten()
        //
        // with TAIT; haven't managed without without introducing this helper:
        OptionReporter::<H>(self.as_ref().map(|h| h.report()))
    }
}

/// Helper type for the [Reporting] implementation on Option
pub struct OptionReporter<'res, H: Reporting + 'res>(Option<H::Reporter<'res>>);

impl<'res, H: Reporting + 'res> Iterator for OptionReporter<'res, H> {
    type Item = H::Record<'res>;
    fn next(&mut self) -> Option<H::Record<'res>> {
        self.0.as_mut().and_then(|s| s.next())
    }
}