async_coap/send_desc/
handler.rs

1// Copyright 2019 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15
16use super::*;
17
18impl<SD: SendDescUnicast, IC> SendDescUnicast for Handler<SD, IC> {}
19impl<SD: SendDescMulticast, IC> SendDescMulticast for Handler<SD, IC> {}
20
21/// Combinator for Send Descriptors created by [`SendDescExt::use_handler`].
22#[derive(Debug)]
23pub struct Handler<SD, F> {
24    pub(super) inner: SD,
25    pub(super) handler: F,
26}
27
28impl<SD, F, IC, R> SendDesc<IC, R> for Handler<SD, F>
29where
30    SD: SendDesc<IC, ()> + Send,
31    IC: InboundContext,
32    R: Send,
33    F: FnMut(
34            Result<&dyn InboundContext<SocketAddr = IC::SocketAddr>, Error>,
35        ) -> Result<ResponseStatus<R>, Error>
36        + Send,
37{
38    send_desc_passthru_timing!(inner);
39    send_desc_passthru_options!(inner);
40    send_desc_passthru_payload!(inner);
41    send_desc_passthru_supports_option!(inner);
42
43    fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<R>, Error> {
44        let inner_result = self.inner.handler(context);
45        let outer_result = (self.handler)(
46            context.map(|ic| ic as &dyn InboundContext<SocketAddr = IC::SocketAddr>),
47        );
48
49        if inner_result.is_err() || outer_result.is_err() {
50            Err(inner_result.err().or(outer_result.err()).unwrap())
51        } else {
52            outer_result
53        }
54    }
55}