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
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! The `coap-handler-implementations` crate provides a few convenience, example or
//! reference implementations of the [coap-handler] interface.
//!
//! They range from the generic "4.04
//! Not Found" responder up to a handler that creates a [write] formatter for GET-only resources,
//! and even provides [block-wise transfer] that.
//! The [SimpleCBORWrapper] enables the easy creation of [serde_cbor] based
//! resource implementations with GET, PUT and POST support in CBOR format.
//! The `HandlerBuilder` implements crude static path based routing
//! that may suffice for some applications, and is also useful to get started quickly.
//!
//! [coap-handler]: https://crates.io/crates/coap-handler
//! [write]: https://doc.rust-lang.org/core/fmt/trait.Write.html
//! [block-wise transfer]: https://tools.ietf.org/html/rfc7959
//! [serde_cbor]: https://crates.io/crates/serde_cbor
//!
//! History
//! -------
//!
//! This code used to be part of coap-handler, but while the interface needs to stabilize fast (as
//! incompatible changes there propagate to implementations), the implementations still need to
//! develop fast (but it doesn't hurt too much if one code part is using the old SimpleRenderable
//! while another uses a newer NeverFound).
//!
//! Version 0.1 is what was available in coap-handler (if Cargo allowed cyclic dependencies,
//! coap-handler would `pub use` this crate); users are encouraged to just use
//! coap-handler-implementations directly.
//!
//! Options Hiding
//! --------------
//!
//! A common mechanism in handlers is that handlers "consume" options. For example, the
//! [ForkingHandler] built through [HandlerBuilder::at] "eats" the Uri-Path; likewise, an
//! Accept-based dispatcher would consume the Accept option.
//!
//! This allows the handlers themselves to check for any left-over critical options and fail if
//! they can't handle them -- without the need to mask them out there assuming (without an actual
//! check) that prior wrappers took care of them.
#![no_std]
#![feature(generic_associated_types)]
#![feature(iter_order_by)]
#![cfg_attr(
    feature = "nontrivial_option_processing",
    feature(type_alias_impl_trait)
)]

use coap_message::{MessageOption, MutableWritableMessage, ReadableMessage};

pub mod helpers;
pub mod option_processing;
pub mod wkc;
mod wkc_implementation;

mod forking_helpers;
use forking_helpers::{ForkingRecord, PrefixedRecord};

use crate::helpers::{
    block2_write_with_cf, codeconvert, Block2RequestData, MaskingUriUpToPath, MaskingUriUpToPathN,
};
use coap_handler::Handler;

use coap_numbers::{code, option};

/// Used to store response codes internally until the type of the response message is determined and
/// it can be converted into an actual outgoing code
///
/// It was tried to use an enum here, but in the end that needs to go through something
/// [codeconvert]-like just again. As the output message type is generally not known in advance,
/// that can't be used either.
type Code = u8;

/// A resource that unconditionally responds 4.04 Not Found.
///
/// This is a convenience tool for building trees of resources -- rather than special casing the
/// "none found" situation, this handler can be used.
pub struct NeverFound {}

impl Handler for NeverFound {
    type RequestData = ();

    fn extract_request_data(&mut self, _request: &impl ReadableMessage) -> Self::RequestData {
        ()
    }

    fn estimate_length(&mut self, _request: &Self::RequestData) -> usize {
        0
    }

    fn build_response(
        &mut self,
        response: &mut impl MutableWritableMessage,
        _request: Self::RequestData,
    ) {
        response.set_code(codeconvert(code::NOT_FOUND));
        response.set_payload(b"");
    }
}

/// Start building a tree of sub-resources
///
/// While technically this just returns a handler that returns 4.04 unconditionally, it also
/// implements HandlerBuilder, and thus can be used like this:
///
/// ```
/// use coap_handler_implementations::*;
/// let handler = new_dispatcher()
///     .at(&["dev", "name"], SimpleRendered::new_typed_str("Demo program", Some(0)))
///     .at(&["dev", "version"], SimpleRendered::new_typed_str("0.8.15", Some(0)))
///     .with_wkc()
///     ;
/// ```
pub fn new_dispatcher() -> impl Handler + wkc::Reporting {
    wkc::NotReporting::new(NeverFound {})
}

/// Trait implemented by default on all handlers that lets the user stack them using a builder-like
/// syntax.
///
/// Note that the resulting ForkingRequestData<ForkingRequestData<...>,()> enums that might look
/// wasteful on paper are optimized into the minimum necessary size since
/// <https://github.com/rust-lang/rust/pull/45225>. They are, however, suboptimal when it comes to
/// how many times the options are read.
pub trait HandlerBuilder<'a, OldRD>
where
    Self: Handler + Sized,
{
    /// Divert requests arriving at `path` into the given `handler`.
    ///
    /// The handler will not *not* see the Uri-Path (and Uri-Host, as this builder doesn't do
    /// virtual hosting yet) options any more; see the top-level module documentation on Options
    /// Hiding for rationale.
    ///
    /// If both the previous tree and the new handler are Reporting, so is the result.
    fn at<H>(self, path: &'a [&'a str], handler: H) -> ForkingHandler<'a, H, Self>
    where
        H: Handler + Sized,
    {
        ForkingHandler {
            h1: handler,
            h2: self,
            h1_condition: path,
        }
    }

    /// Divert requests arriving at `path` into the given `handler`, and announce them with the
    /// given attributes in .well-known/core.
    ///
    /// Any reporting the handler would have done is overridden.
    ///
    /// This is a shorthand for `.at(ConstantSingleRecordReport::new(h, attributes))`.
    fn at_with_attributes<H>(
        self,
        path: &'a [&'a str],
        attributes: &'a [wkc::Attribute],
        handler: H,
    ) -> ForkingHandler<'a, wkc::ConstantSingleRecordReport<'a, H>, Self>
    where
        H: Handler + Sized,
    {
        ForkingHandler {
            h1: wkc::ConstantSingleRecordReport::new(handler, attributes),
            h2: self,
            h1_condition: path,
        }
    }

    /// Divert requests arriving with an Uri-Path starting with `path` to the given `handler`.
    ///
    /// Only remaining Uri-Path options will be visible to the handler; those expressed in path
    /// (and Uri-Host, see [.at()]) are hidden.
    ///
    /// If both the previous tree and the new handler are Reporting, so is the result.
    fn below<H>(self, path: &'a [&'a str], handler: H) -> ForkingTreeHandler<'a, H, Self> {
        ForkingTreeHandler {
            h1: handler,
            h2: self,
            h1_condition: path,
        }
    }
}

impl<'a, OldRD, OldH> HandlerBuilder<'a, OldRD> for OldH
where
    Self: Handler<RequestData = OldRD> + Sized,
{
    // Methods are provided
}

/// Extension trait for handlers that also implement [Reporting](crate::wkc::Reporting).
///
/// Like [HandlerBuilder] this is implemented for wherever it works.
///
/// (Note that while this *could* be implemented as a provided method of Reporting, it is split out
/// to stay architecturally analogous to the HandlerBuilder, and to not force this crate's
/// implementation of .well-known/core onto other users of Reporting. Possibly, these could be
/// separated approaching stabilization.)
pub trait ReportingHandlerBuilder<'a, OldRD>: HandlerBuilder<'a, OldRD> + wkc::Reporting {
    /// Add a `/.well-known/core` resource that exposes the information the previous (stack of)
    /// handler(s) exposes throught the [Reporting](crate::wkc::Reporting) trait.
    fn with_wkc(self) -> wkc_implementation::WellKnownCore<Self> {
        wkc_implementation::WellKnownCore::new(self)
    }
}

impl<'a, OldRD, OldH> ReportingHandlerBuilder<'a, OldRD> for OldH
where
    OldH: Handler<RequestData = OldRD> + wkc::Reporting,
{
    // Methods are provided
}

pub struct ForkingHandler<'a, H1, H2> {
    h1: H1,
    h2: H2,

    // I'd like to have a closure in here, and that'd almost work as a type D: Fn(&Message<Bin>)
    // -> bool, but I can't write at()... -> ForkingHandler<impl ..., H, Self> in the trait's
    // signature.
    h1_condition: &'a [&'a str],
}

/// Tagged-union container for ForkingHandler
pub enum ForkingRequestData<RD1, RD2> {
    First(RD1),
    Second(RD2),
}

impl<'a, RD1, H1, RD2, H2> Handler for ForkingHandler<'a, H1, H2>
where
    H1: Handler<RequestData = RD1>,
    H2: Handler<RequestData = RD2>,
{
    type RequestData = ForkingRequestData<RD1, RD2>;

    fn extract_request_data(&mut self, request: &impl ReadableMessage) -> Self::RequestData {
        let expected_path = self.h1_condition.iter().map(|s| s.as_bytes());
        let actual_path = request.options().filter(|o| o.number() == option::URI_PATH);

        if expected_path.cmp_by(actual_path, |e, a| e.cmp(a.value())) == core::cmp::Ordering::Equal
        {
            let masked = MaskingUriUpToPath(request);
            ForkingRequestData::First(self.h1.extract_request_data(&masked))
        } else {
            ForkingRequestData::Second(self.h2.extract_request_data(request))
        }
    }

    fn estimate_length(&mut self, request: &Self::RequestData) -> usize {
        match request {
            ForkingRequestData::First(r) => self.h1.estimate_length(r),
            ForkingRequestData::Second(r) => self.h2.estimate_length(r),
        }
    }

    fn build_response(
        &mut self,
        response: &mut impl MutableWritableMessage,
        request: Self::RequestData,
    ) {
        match request {
            ForkingRequestData::First(r) => self.h1.build_response(response, r),
            ForkingRequestData::Second(r) => self.h2.build_response(response, r),
        }
    }
}

impl<'a, RD1, H1, RD2, H2> wkc::Reporting for ForkingHandler<'a, H1, H2>
where
    H1: Handler<RequestData = RD1> + wkc::Reporting,
    H2: Handler<RequestData = RD2> + wkc::Reporting,
{
    // FIXME: This is copied over from ForkingTreeHandler (and stripped to the general not(feature
    // = "nontrivial_option_processing") case)
    //
    // As it is now it would appear to warrant the Forking{,Tree}Handler unification hinted at the
    // ForkingTreeHandler definition. Not starting the deduplication (which would be warranted by
    // the below behemoth) as this'll all look much slimmer again once type_alias_impl_trait is
    // on by default.
    //
    // (After that, could be that it's warranted as it's now more than a few 4-liners, could be
    // that not).

    type Record<'b>
    where
        Self: 'b,
    = ForkingRecord<PrefixedRecord<'b, H1::Record<'b>>, H2::Record<'b>>;

    type Reporter<'b>
    where
        Self: 'b,
    = core::iter::Chain<
        core::iter::Map<H2::Reporter<'b>, fn(H2::Record<'b>) -> Self::Record<'b>>,
        core::iter::Map<
            core::iter::Zip<H1::Reporter<'b>, core::iter::Repeat<&'b [&'b str]>>,
            fn((H1::Record<'b>, &'b [&'b str])) -> Self::Record<'b>,
        >,
    >;
    fn report(&self) -> Self::Reporter<'_> {
        fn first<'c, H1R, H2R>(
            prefixed_prefix: (H1R, &'c [&'c str]),
        ) -> ForkingRecord<PrefixedRecord<'c, H1R>, H2R> {
            let (prefixed, prefix) = prefixed_prefix;
            ForkingRecord::First(PrefixedRecord { prefix, prefixed })
        }
        self.h2
            .report()
            .map(ForkingRecord::Second as fn(_) -> _)
            .chain(
                self.h1
                    .report()
                    .zip(core::iter::repeat(self.h1_condition))
                    .map(first as fn(_) -> _),
            )
    }
}

// This is identical to the ForkingHandler in its structure -- just the matching behavior differs.
// Even ForkingRequestData can be shared; unfortunately, the main code is still duplicated -- it
// could be refactored, but is it worth it for the identical 4-lines parts?
pub struct ForkingTreeHandler<'a, H1, H2> {
    h1: H1,
    h2: H2,

    h1_condition: &'a [&'a str],
}

impl<'a, RD1, H1, RD2, H2> Handler for ForkingTreeHandler<'a, H1, H2>
where
    H1: Handler<RequestData = RD1>,
    H2: Handler<RequestData = RD2>,
{
    type RequestData = ForkingRequestData<RD1, RD2>;

    fn extract_request_data(&mut self, request: &impl ReadableMessage) -> Self::RequestData {
        let expected_path = self.h1_condition.iter().map(|s| s.as_bytes());
        let actual_path = request
            .options()
            .filter(|o| o.number() == option::URI_PATH)
            .take(self.h1_condition.len());

        if expected_path.cmp_by(actual_path, |e, a| e.cmp(a.value())) == core::cmp::Ordering::Equal
        {
            let masked = MaskingUriUpToPathN::new(request, self.h1_condition.len());
            ForkingRequestData::First(self.h1.extract_request_data(&masked))
        } else {
            ForkingRequestData::Second(self.h2.extract_request_data(request))
        }
    }

    fn estimate_length(&mut self, request: &Self::RequestData) -> usize {
        match request {
            ForkingRequestData::First(r) => self.h1.estimate_length(r),
            ForkingRequestData::Second(r) => self.h2.estimate_length(r),
        }
    }

    fn build_response(
        &mut self,
        response: &mut impl MutableWritableMessage,
        request: Self::RequestData,
    ) {
        match request {
            ForkingRequestData::First(r) => self.h1.build_response(response, r),
            ForkingRequestData::Second(r) => self.h2.build_response(response, r),
        }
    }
}

impl<'a, RD1, H1, RD2, H2> wkc::Reporting for ForkingTreeHandler<'a, H1, H2>
where
    H1: Handler<RequestData = RD1> + wkc::Reporting,
    H2: Handler<RequestData = RD2> + wkc::Reporting,
{
    type Record<'b>
    where
        Self: 'b,
    = ForkingRecord<PrefixedRecord<'b, H1::Record<'b>>, H2::Record<'b>>;

    // FIXME: one of these is copied over to wkc::Reporting for ForkingHandler, see there.

    #[cfg(feature = "nontrivial_option_processing")]
    type Reporter<'b>
    where
        Self: 'b,
    = impl Iterator<Item = Self::Record<'b>>;
    #[cfg(feature = "nontrivial_option_processing")]
    fn report(&self) -> Self::Reporter<'_> {
        self.h2
            .report()
            .map(ForkingRecord::Second as fn(_) -> _)
            .chain(self.h1.report().map(|f| {
                ForkingRecord::First(PrefixedRecord {
                    prefix: self.h1_condition,
                    prefixed: f,
                })
            }))
    }

    #[cfg(not(feature = "nontrivial_option_processing"))]
    type Reporter<'b>
    where
        Self: 'b,
    = core::iter::Chain<
        core::iter::Map<H2::Reporter<'b>, fn(H2::Record<'b>) -> Self::Record<'b>>,
        core::iter::Map<
            core::iter::Zip<H1::Reporter<'b>, core::iter::Repeat<&'b [&'b str]>>,
            fn((H1::Record<'b>, &'b [&'b str])) -> Self::Record<'b>,
        >,
    >;
    #[cfg(not(feature = "nontrivial_option_processing"))]
    fn report(&self) -> Self::Reporter<'_> {
        fn first<'c, H1R, H2R>(
            prefixed_prefix: (H1R, &'c [&'c str]),
        ) -> ForkingRecord<PrefixedRecord<'c, H1R>, H2R> {
            let (prefixed, prefix) = prefixed_prefix;
            ForkingRecord::First(PrefixedRecord { prefix, prefixed })
        }
        self.h2
            .report()
            .map(ForkingRecord::Second as fn(_) -> _)
            .chain(
                self.h1
                    .report()
                    .zip(core::iter::repeat(self.h1_condition))
                    .map(first as fn(_) -> _),
            )
    }
}

/// Information a SimpleRenderable needs to carry from request to response.
// Newtype wrapper to avoid exposing Block2RequestData
pub struct SimpleRenderableData(Result<Block2RequestData, Code>);

/// A simplified Handler trait that can react to GET requests and will render to a fmt::Write
/// object with blockwise backing.
///
/// Anything that implements it (which includes plain &str, for example) can be packed into a
/// [SimpleRendered] to form a Handler.
///
/// For binary data, render_bytes can be implemented instead of render, and utilize the
/// WindowedInfinityWithETag's write_bytes method (multiple times, if so desired). In that case, the render
/// function can be left unimplemented.
pub trait SimpleRenderable {
    fn render<W>(&mut self, writer: &mut W)
    where
        W: core::fmt::Write;

    fn render_bytes(&mut self, writer: &mut helpers::WindowedInfinityWithETag) {
        self.render(writer)
    }

    /// If something is returned, GETs with differing Accept options will be rejecected, and the
    /// value will be set in responses.
    fn content_format(&self) -> Option<u16> {
        None
    }
}

#[derive(Debug, Copy, Clone)]
pub struct SimpleRendered<T: SimpleRenderable>(pub T);

impl<'a> SimpleRendered<TypedStaticRenderable<'a>> {
    pub fn new_typed_slice(data: &'a [u8], content_format: Option<u16>) -> Self {
        SimpleRendered(TypedStaticRenderable {
            data,
            content_format,
        })
    }

    pub fn new_typed_str(data: &'a str, content_format: Option<u16>) -> Self {
        let data = data.as_bytes();
        Self::new_typed_slice(data, content_format)
    }
}

impl<T> Handler for SimpleRendered<T>
where
    T: SimpleRenderable,
{
    type RequestData = SimpleRenderableData;

    fn extract_request_data(&mut self, request: &impl ReadableMessage) -> Self::RequestData {
        let expected_accept = self.0.content_format();

        let mut block2 = Ok(None);

        for o in request.options() {
            match o.number() {
                coap_numbers::option::ACCEPT => {
                    if expected_accept.is_some() && o.value_uint() != expected_accept {
                        return SimpleRenderableData(Err(coap_numbers::code::NOT_ACCEPTABLE));
                    }
                }
                coap_numbers::option::BLOCK2 => {
                    block2 = match block2 {
                        Err(e) => Err(e),
                        Ok(Some(_)) => Err(coap_numbers::code::BAD_REQUEST),
                        Ok(None) => Block2RequestData::from_option(&o)
                            .map(Some)
                            .map_err(|_| code::BAD_REQUEST),
                    }
                }
                o if option::get_criticality(o) == option::Criticality::Critical => {
                    return SimpleRenderableData(Err(code::BAD_OPTION));
                }
                _ => (),
            }
        }

        let reqdata = match request.code().into() {
            code::GET => block2.map(|o| o.unwrap_or_default()),
            _ => Err(code::METHOD_NOT_ALLOWED),
        };
        SimpleRenderableData(reqdata)
    }

    fn estimate_length(&mut self, _request: &Self::RequestData) -> usize {
        1280 - 40 - 4 // does this correclty calculate the IPv6 minimum MTU?
    }

    fn build_response(
        &mut self,
        response: &mut impl MutableWritableMessage,
        request: Self::RequestData,
    ) {
        let block2data = match request.0 {
            Ok(x) => x,
            Err(c) => {
                response.set_code(codeconvert(c));
                response.set_payload(b"");
                return;
            }
        };

        let cf = self.0.content_format();
        response.set_code(codeconvert(code::CONTENT));
        block2_write_with_cf(block2data, response, |w| self.0.render_bytes(w), cf);
    }
}

impl<T> wkc::Reporting for SimpleRendered<T>
where
    T: SimpleRenderable,
{
    type Record<'a>
    where
        Self: 'a,
    = wkc::EmptyRecord;
    type Reporter<'a>
    where
        Self: 'a,
    = core::iter::Once<wkc::EmptyRecord>;

    fn report(&self) -> Self::Reporter<'_> {
        // Using a ConstantSliceRecord instead would be tempting, but that'd need a const return
        // value from self.0.content_format()
        core::iter::once(wkc::EmptyRecord {})
    }
}

impl<'a> SimpleRenderable for &'a str {
    fn render<W>(&mut self, writer: &mut W)
    where
        W: core::fmt::Write,
    {
        writer
            .write_str(*self)
            .expect("The backend of SimpleRenderable supports infallible writing");
    }

    fn content_format(&self) -> Option<u16> {
        Some(0)
    }
}

pub struct TypedStaticRenderable<'a> {
    data: &'a [u8],
    content_format: Option<u16>,
}

impl<'a> SimpleRenderable for TypedStaticRenderable<'a> {
    fn render<W>(&mut self, _: &mut W)
    where
        W: core::fmt::Write,
    {
        unimplemented!("render_bytes is implemented instead")
    }

    fn render_bytes(&mut self, writer: &mut helpers::WindowedInfinityWithETag) {
        writer.write(self.data)
    }

    fn content_format(&self) -> Option<u16> {
        self.content_format
    }
}

use serde::Serialize;

/// A simple Handler trait that supports GET, POST and/or PUT on a data structure that supports
/// serde.
///
/// A SimpleCBORHandler implementation can be turned into a [Handler] by wrapping it in
/// [SimpleCBORWrapper::new].
pub trait SimpleCBORHandler {
    // Does it really make sense to constrain them? Seems so, as the only practical thing this
    // trait is used for is later derivation, and that'd fail if any of those isn't satisified, so
    // rather specifying them here for good error messages.
    type Get: for<'de> serde::Serialize;
    type Post: for<'de> serde::Deserialize<'de>;
    type Put: for<'de> serde::Deserialize<'de>;

    fn get(&mut self) -> Result<Self::Get, Code> {
        Err(code::METHOD_NOT_ALLOWED)
    }
    fn post(&mut self, _representation: &Self::Post) -> Code {
        code::METHOD_NOT_ALLOWED
    }
    fn put(&mut self, _representation: &Self::Put) -> Code {
        code::METHOD_NOT_ALLOWED
    }
}

/// Wrapper for resource handlers that are implemented in terms of GETting, POSTing or PUTting
/// objects in CBOR format.
///
/// The wrapper handles all encoding and decoding, options processing (ignoring the critical
/// Uri-Path option under the assumption that that has been already processed by an underlying
/// request router), the corresponding errors and block-wise GETs.
///
/// More complex handlers (eg. implementing additional representations, or processing query
/// aprameters into additional data available to the [SimpleCBORHandler]) can be built by
/// forwarding to this (where any critical but already processed options would need to be masked
/// from the message's option) or taking inspiration from it.
pub struct SimpleCBORWrapper<H: SimpleCBORHandler> {
    handler: H,
}

impl<H: SimpleCBORHandler> SimpleCBORWrapper<H> {
    pub fn new(handler: H) -> Self {
        SimpleCBORWrapper { handler }
    }

    fn check_get_options(request: &impl ReadableMessage) -> Result<Block2RequestData, Code> {
        let mut block2 = Ok(None);

        for o in request.options() {
            match o.number() {
                option::ACCEPT => {
                    if o.value_uint() != Some(60u8) {
                        return Err(code::UNSUPPORTED_CONTENT_FORMAT);
                    }
                }
                option::BLOCK2 => {
                    block2 = match block2 {
                        Err(e) => Err(e),
                        Ok(Some(_)) => Err(coap_numbers::code::BAD_REQUEST),
                        Ok(None) => Block2RequestData::from_option(&o)
                            .map(Some)
                            .map_err(|_| code::BAD_REQUEST),
                    }
                }
                o if option::get_criticality(o) == option::Criticality::Critical => {
                    return Err(code::BAD_OPTION);
                }
                _ => {}
            }
        }

        Ok(block2?.unwrap_or_default())
    }

    fn check_postput_options(request: &impl ReadableMessage) -> Result<(), Code> {
        for o in request.options() {
            match o.number() {
                option::CONTENT_FORMAT => {
                    if o.value_uint() != Some(60u8) {
                        return Err(code::NOT_ACCEPTABLE);
                    }
                }
                o if option::get_criticality(o) == option::Criticality::Critical => {
                    return Err(code::BAD_OPTION);
                }
                _ => {}
            }
        }

        Ok(())
    }
}

pub enum SimpleCBORRequestData {
    Get(Block2RequestData), // GET to be processed later, but all request opions were in order
    Done(Code), // All done, just a response to emit -- if POST/PUT has been processed, or GET had a bad accept/option
}
use self::SimpleCBORRequestData::{Done, Get};
impl<H> Handler for SimpleCBORWrapper<H>
where
    H: SimpleCBORHandler,
    H::Get: serde::Serialize,
    H::Post: for<'de> serde::Deserialize<'de>,
    H::Put: for<'de> serde::Deserialize<'de>,
{
    type RequestData = SimpleCBORRequestData;

    fn extract_request_data(&mut self, request: &impl ReadableMessage) -> Self::RequestData {
        match request.code().into() {
            code::GET => match Self::check_get_options(request) {
                Err(e) => Done(e),
                Ok(block) => Get(block),
            },
            code::POST => {
                if let Err(e) = Self::check_postput_options(request) {
                    return Done(e);
                }

                // FIXME: allow getting a mutable payload here, which may be hard for general
                // Message but usually cheap for GNRC-based.
                let parsed: Result<H::Post, _> =
                    serde_cbor::de::from_slice_with_scratch(request.payload(), &mut []);
                match parsed {
                    Ok(p) => Done(self.handler.post(&p)),
                    Err(_) => Done(code::BAD_REQUEST),
                }
            }
            code::PUT => {
                if let Err(e) = Self::check_postput_options(request) {
                    return Done(e);
                }

                let parsed: Result<H::Put, _> =
                    serde_cbor::de::from_slice_with_scratch(request.payload(), &mut []);
                match parsed {
                    Ok(p) => Done(self.handler.put(&p)),
                    Err(_) => Done(code::BAD_REQUEST),
                }
            }
            _ => Done(code::METHOD_NOT_ALLOWED),
        }
    }

    fn estimate_length(&mut self, request: &Self::RequestData) -> usize {
        match request {
            Done(_) => 4,
            Get(block) => (block.size() + 25).into(), // FIXME: hard-coded copied over from block2_write_with_cf's estimated overhead
        }
    }

    fn build_response(
        &mut self,
        response: &mut impl MutableWritableMessage,
        request: Self::RequestData,
    ) {
        match request {
            Done(r) => {
                response.set_code(codeconvert(r));
                response.set_payload(b"");
            }
            Get(block2) => {
                let repr = self.handler.get();
                match repr {
                    Err(e) => {
                        response.set_code(codeconvert(e));
                        response.set_payload(b"");
                    }
                    Ok(repr) => {
                        response.set_code(codeconvert(code::CONTENT));
                        match block2_write_with_cf(
                            block2,
                            response,
                            |win| repr.serialize(&mut serde_cbor::ser::Serializer::new(win)),
                            Some(60),
                        ) {
                            Ok(()) => (),
                            Err(_) => {
                                // FIXME: Rewind all the written options
                                response.set_code(codeconvert(code::INTERNAL_SERVER_ERROR));
                            }
                        }
                    }
                }
            }
        }
    }
}