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
//! This is a CoAP server application that exposes SAUL entries.
//!
//! For discovery, this exposes all entries as
//! rt="tag:chrysn@fsfe.org,2020-10-02:saul";saul=ACT_LED_RGB or similar.
//!
//! For GETs, the supported formats are:
//! * text/plain;encoding=utf-8 -- renders through the phydat's Display implementation, or uses the
//!   command-line listing on the index
//! * application/cbor (individuals only) -- renders CBOR equivalent to RIOT's phydat_to_json
//!   output
//!
//!   The implementation of the CBOR serialization doubles as a playground for comparing individual
//!   embedded CBOR libraries (serde_cbor, minicbor, ciborium-ll); all are implemented, but all but
//!   minicbor are commented out in the renderer.
//! * application/link-format (index only) -- gives the index as produced by the `saul.rs` command
//!   line output
//!
//! For actor PUTs, the supported formats are:
//! * text/plain;charset=utf-8 -- only single integer values and no units are supported.
//! * application/cbor -- like in GETs (but with limited units support). Numerics are accepted as
//!   integers or decimal fractions; unlike fractions are processed to the GCD.
//! * 65362 (experimental) -- RGB hex color codes in '#rrggbb' format as used with CSS (but
//!   without the named colors or alternative forms); those are fed in without units.

use coap_message_utils::{option_value::Block2RequestData, OptionsExt};
use coap_handler_implementations::{wkc, helpers::block2_write};
use coap_message::{Code, MessageOption, MinimalWritableMessage, MutableWritableMessage, ReadableMessage, error::RenderableOnMinimal};
use coap_numbers::{code, option};
use core::fmt::Write;
use riot_wrappers::error::NumericError;
use riot_wrappers::saul::{Phydat, RegistryEntry, Unit};

/// An extended phydat that almost behaves like phydat_to_json but with CBOR
///
/// It produces a map containing a "u" entry with the text form of the unit, and a "d" entry with
/// either a single numeric of a vector of 2 or 3 numeric entries. Numeric entries are integers or
/// decimal fractions (thus easily expressing the phydat's scale value without actually
/// calculating)
///
/// It can be serialized using serde, minicbor or ciborium_ll. (ciborium would use serde, but is
/// not an option here as it uses alloc).
struct JsonStylePhydat(Phydat);

impl serde::Serialize for JsonStylePhydat {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use serde::ser::{Error, SerializeStruct};

        if self.0.scale() != 0 {
            // The simple workaround of expressing it as a tag-unwrapped(?) array would be
            // ambiguous against the possibly elided outer array
            return Err(S::Error::custom("has scale"));
        }

        let unit = self.0.unit().and_then(|u| u.name_verbose());
        let length = 1 + unit.is_some() as usize;

        // dont-serialize: For the desired CBOR outcome the struct's name won't be serialized
        // anyway (it also has none)
        let mut map = s.serialize_struct("dont-serialize", length)?;
        if let Some(u) = unit {
            map.serialize_field("u", u)?;
        }
        match self.0.value() {
            // Single values are mapped without an outer array
            &[v] => map.serialize_field("d", &v)?,
            v => map.serialize_field("d", v)?,
        };
        map.end()
    }
}

impl<C> minicbor::Encode<C> for JsonStylePhydat {
    fn encode<W: minicbor::encode::Write>(
        &self,
        e: &mut minicbor::Encoder<W>,
        _ctx: &mut C,
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        let unit = self.0.unit().and_then(|u| u.name_verbose());
        let length = 1 + unit.is_some() as usize;

        let mut map = e.map(length as _)?;
        if let Some(u) = unit {
            map.encode("u")?;
            map.encode(u)?;
        }
        map.encode("d");
        // minicbor is incredibly lax when it comes to what items are actually written to, but then
        // again, that makes work very easy in this case
        let item_encoder = match self.0.value().len() {
            1 => map,
            n => map.array(n as _)?,
        };
        for v in self.0.value() {
            if self.0.scale() != 0 {
                let tagged = item_encoder.tag(minicbor::data::Tag::Decimal)?;
                let list = tagged.array(2)?;
                list.encode(self.0.scale())?;
                list.encode(v)?;
            } else {
                item_encoder.encode(v)?;
            }
        }

        Ok(())
    }
}

impl<'a, C> minicbor::Decode<'a, C> for JsonStylePhydat {
    /// Decode a JsonStylePhydat item from CBOR
    ///
    /// This decoder is generally strict, it currently accepts one oddity: It lets unrecognized
    /// units slip silently; consequently it also doesn't complain if the unit is given multiple
    /// times if it's nonsensical.
    // Yikes, that's a lot of code for "matching that CDDL, give me..."
    fn decode(d: &mut minicbor::Decoder<'_>, _ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
        #[derive(Default)]
        struct NumericState {
            values: heapless::Vec<i16, 3>,
            minscale: Option<i8>,
        }

        impl NumericState {
            fn push(&mut self, val: ScaledI16) -> Result<(), minicbor::decode::Error> {
                let ScaledI16(mut value, mut scale) = val;
                if self.values.len() == 0 {
                    self.values.push(value);
                    self.minscale = Some(scale);
                    return Ok(());
                }

                while scale > self.minscale.unwrap() {
                    scale -= 1;
                    value = value
                        .checked_mul(10)
                        .ok_or(minicbor::decode::Error::message(
                            "Phydat can't express that range",
                        ))?;
                }
                while scale < self.minscale.unwrap() {
                    self.minscale = Some(self.minscale.unwrap() - 1);
                    for v in self.values.iter_mut() {
                        *v = v.checked_mul(10).ok_or(minicbor::decode::Error::message(
                            "Phydat can't express that range",
                        ))?;
                    }
                }
                self.values.push(value);
                Ok(())
            }
        }

        struct ScaledI16(i16, i8);

        impl<'b, C> minicbor::Decode<'b, C> for ScaledI16 {
            fn decode(d: &mut minicbor::Decoder<'_>, _ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
                if d.probe().tag().is_err() {
                    return Ok(ScaledI16(d.decode()?, 0));
                }
                if d.tag()? != minicbor::data::Tag::Decimal {
                    return Err(minicbor::decode::Error::message("Unsupported tag"));
                }
                if !matches!(d.array(), Ok(Some(2))) {
                    return Err(minicbor::decode::Error::message("Unsupported array length"));
                }
                let scale = d.decode()?;
                let value = d.decode()?;
                Ok(ScaledI16(value, scale))
            }
        }

        let mut unit = None;
        let mut state: NumericState = Default::default();
        let mut d_seen = false;

        let mut items_remaining = d.map()?;
        while match items_remaining {
            Some(0) => false,
            Some(n) => {
                items_remaining = Some(n - 1);
                true
            }
            None => matches!(d.probe().simple(), Ok(0x1f)),
        } {
            match d.str()? {
                "u" => {
                    if unit.is_some() {
                        return Err(minicbor::decode::Error::message("Duplicate unit"));
                    }
                    unit = match d.str()? {
                        "%" => Some(Unit::Percent),
                        "none" => Some(Unit::None),
                        // FIXME: List is incomplete, should use utility function, maybe even in
                        // RIOT -- as it's incomplete, failing silently
                        _ => None,
                    };
                }
                "d" => {
                    if d_seen {
                        return Err(minicbor::decode::Error::message("Duplicate data"));
                    }
                    d_seen = true;
                    if d.probe().array().is_ok() {
                        for val in d.array_iter()? {
                            state.push(val?)?;
                        }
                    } else {
                        let val = d.decode()?;
                        state.push(val)?;
                    }
                }
                _ => {
                    return Err(minicbor::decode::Error::message("Unknown key"));
                }
            }
        }
        if items_remaining.is_none() {
            // To allow the wrapper to do the assertion on being at EOF
            let _ = d.simple();
        }

        Ok(Self(Phydat::new(
            &state.values,
            unit,
            state.minscale.unwrap_or(0),
        )))
    }
}

impl JsonStylePhydat {
    fn push_to_ciborium<W: ciborium_io::Write>(
        &self,
        e: &mut ciborium_ll::Encoder<W>,
    ) -> Result<(), W::Error> {
        use ciborium_ll::Header;

        fn numeric(n: impl Into<i64>) -> Header {
            let n = n.into();
            if n > 0 {
                Header::Positive(n as u64)
            } else {
                Header::Negative((!n) as u64)
            }
        }

        let unit = self.0.unit().and_then(|u| u.name_verbose());
        let length = 1 + unit.is_some() as usize;

        let mut map = e.push(Header::Map(Some(length as _)))?;
        if let Some(u) = unit {
            e.text("u", None)?;
            e.text(u, None)?;
        }
        e.text("d", None)?;

        match self.0.value().len() {
            1 => {}
            n => {
                e.push(Header::Array(Some(n)))?;
            }
        };
        for v in self.0.value() {
            if self.0.scale() != 0 {
                e.push(Header::Tag(4))?;
                e.push(Header::Array(Some(2)))?;
                e.push(numeric(self.0.scale()))?;
                e.push(numeric(*v))?;
            } else {
                e.push(numeric(*v))?;
            }
        }

        Ok(())
    }
}

#[derive(Copy, Clone, Debug)]
pub enum ContentFormat {
    TextPlain,
    LinkFormat,
    Cbor, // a CBOR-JSON convertible mapping of the Json format
    RGB,  // An ad-hoc '#RRGGBB' hex format used with code point 65362
}

impl ContentFormat {
    fn from_option(opt: &impl MessageOption) -> Result<Self, ()> {
        Ok(match opt.value_uint().ok_or(())? {
            0u16 => ContentFormat::TextPlain,
            40 => ContentFormat::LinkFormat,
            60 => ContentFormat::Cbor,
            65362 => ContentFormat::RGB,
            _ => Err(())?,
        })
    }

    fn as_number(self) -> u16 {
        match self {
            ContentFormat::TextPlain => 0,
            ContentFormat::LinkFormat => 40,
            ContentFormat::Cbor => 60,
            ContentFormat::RGB => 65362,
        }
    }
}

pub enum SaulRequest {
    GetIndex {
        accept: ContentFormat,
        block2: Block2RequestData,
    },
    Get {
        entry: RegistryEntry,
        accept: ContentFormat,
        block2: Block2RequestData,
    },
    // No details at all -- the request was already acted on in the extraction part
    Put,
}

use SaulRequest::*;

#[derive(Debug)]
pub enum Error {
    // some on which we may provide extra text
    ReadError(NumericError),
    WriteError(NumericError),
    UnsupportedContentFormat,
    FormatError(ContentFormat),
    NotAcceptableForIndex,
    NotAcceptableForItem,
    UnknownContentFormat,
    MethodNotAllowedRoot,
    MethodNotAllowedItem,
    // some are just "the weird stack can't express simple things"
    MissingCoAPStackSupport,
    // ... and some straightforward general ones
    BadOption,
    NotFound,
}

use Error::*;

impl Error {
    fn code(&self) -> u8 {
        match self {
            // maybe say something smarter on unreadable devices?
            ReadError(_) => code::INTERNAL_SERVER_ERROR,
            WriteError(_) => code::INTERNAL_SERVER_ERROR,

            UnsupportedContentFormat => code::UNSUPPORTED_CONTENT_FORMAT,
            FormatError(ContentFormat) => code::BAD_REQUEST,
            NotAcceptableForIndex => code::NOT_ACCEPTABLE,
            NotAcceptableForItem => code::NOT_ACCEPTABLE,
            UnknownContentFormat => code::UNSUPPORTED_CONTENT_FORMAT,
            MethodNotAllowedRoot => code::METHOD_NOT_ALLOWED,
            MethodNotAllowedItem => code::METHOD_NOT_ALLOWED,
            BadOption => code::BAD_OPTION,
            NotFound => code::NOT_FOUND,

            MissingCoAPStackSupport => code::INTERNAL_SERVER_ERROR,
        }
    }

    fn message(&self) -> &'static str {
        match self {
            // maybe say something smarter on unreadable devices?
            ReadError(_) => "Read error or unsupported",
            WriteError(_) => "Write error or unsupported",

            UnsupportedContentFormat => "Try text/plain, CBOR or 65362",

            FormatError(ContentFormat::RGB) => "Format is hex #RRGGBB",
            FormatError(ContentFormat::TextPlain) => "Only single ASCII int supported",
            FormatError(ContentFormat::Cbor) => r#"like {"u":"%","d":[0,0,100]}"#,
            FormatError(ContentFormat::LinkFormat) => "", // inapplicable, won't happen

            NotAcceptableForIndex => "Try text/plain or link-format",
            NotAcceptableForItem => "Try text/plain or CBOR",
            UnknownContentFormat => "",
            MethodNotAllowedRoot => "",
            MethodNotAllowedItem => "",
            BadOption => "",
            NotFound => "",

            // and likely it won't be able to send that either, but let's try.
            MissingCoAPStackSupport => "CoAP stack can not send message",
        }
    }
}

impl RenderableOnMinimal for Error {
    type Error<IE: RenderableOnMinimal + core::fmt::Debug> = IE;
    fn render<M: MinimalWritableMessage>(self, msg: &mut M) -> Result<(), M::UnionError> {
        msg.set_code(Code::new(self.code())?);
        let _ = msg.set_payload(self.message().as_bytes());
        Ok(())
    }
}

/// A handler for SAUL requests, using SAUL_MATCH_SUBTREE to manage its resources.
///
/// The path this is registered at must be passed in as the prefix, as link-format responses
/// necessitate knowing one's own path, and the prefix needs to be stripped off when processing the
/// Uri-Path options.
///
/// As the link-format handler is bad, the name must be simple.
pub struct SaulHandler {
    prefix: &'static [&'static str],
}

impl SaulHandler {
    /// Create a SaulHandler
    ///
    /// The prefix needs to be passed in in order to produce proper link-format responses which can
    /// not be path-relative, and should thus be equal to the prefix assigned in the tree.
    pub fn new(prefix: &'static [&'static str]) -> Self {
        Self { prefix }
    }

    fn put_value(
        &self,
        entry: RegistryEntry,
        content_format: ContentFormat,
        body: &[u8],
    ) -> Result<(), Error> {
        let phydat = match content_format {
            ContentFormat::TextPlain => {
                let val: i16 = core::str::from_utf8(body)
                    .ok()
                    .and_then(|s| s.parse().ok())
                    .ok_or_else(|| FormatError(ContentFormat::TextPlain))?;
                Phydat::new(&[val], None, 0)
            }
            ContentFormat::Cbor => {
                let mut decoder = minicbor::Decoder::new(body);
                let jsp: JsonStylePhydat = decoder
                    .decode()
                    .map_err(|e| FormatError(ContentFormat::Cbor))?;

                if decoder.datatype().map_err(|e| e.is_end_of_input()) != Err(true) {
                    return Err(FormatError(ContentFormat::Cbor));
                }
                jsp.0
            }
            ContentFormat::RGB => {
                if body.len() != 7 || body[0] != b'#' {
                    return Err(FormatError(ContentFormat::RGB));
                }
                let mut bytes = [0u8; 3];
                hex::decode_to_slice(&body[1..], bytes.as_mut())
                    .map_err(|_| FormatError(ContentFormat::RGB))?;

                Phydat::new(
                    &[bytes[0].into(), bytes[1].into(), bytes[2].into()],
                    None,
                    0,
                )
            }
            _ => Err(UnsupportedContentFormat)?,
        };
        entry
            .write(phydat)
            // in the rough anticipation that maybe one day this won't return a NumericError but
            // something more wrapped that would then still implement Into<NumericError> for
            // exactly this kind of compatibility
            .map_err(|e| WriteError(e.into()))
    }
}

impl coap_handler::Handler for SaulHandler {
    type RequestData = SaulRequest;

    type ExtractRequestError = Error;
    type BuildResponseError<M: MinimalWritableMessage> = Error;

    fn extract_request_data<M: ReadableMessage>(
        &mut self,
        request: &M,
    ) -> Result<SaulRequest, Error> {
        #[derive(PartialEq, Copy, Clone)]
        enum Path {
            Initial,
            Root,
            Index(usize),
            NotFound,
        }

        impl Path {
            fn crank(&mut self, optval: &str) {
                *self = match (*self, optval) {
                    (Path::Initial, "") => Path::Root,
                    (Path::Initial, x) => {
                        if let Ok(i) = x.parse() {
                            Path::Index(i)
                        } else {
                            Path::NotFound
                        }
                    }
                    (_, _) => Path::NotFound,
                };
            }
        }

        let mut path = Path::Initial;
        let mut block2 = None;
        let mut accept = None;
        let mut content_format = None;

        for opt in request
            .options()
            .take_uri_path(|p| path.crank(p))
            .take_block2(&mut block2)
        {
            match opt.number() {
                option::ACCEPT => {
                    // Not converting the error here...
                    accept = Some(ContentFormat::from_option(&opt));
                }
                option::CONTENT_FORMAT => {
                    content_format =
                        Some(ContentFormat::from_option(&opt).map_err(|_| UnknownContentFormat)?);
                }
                x => match option::get_criticality(x) {
                    option::Criticality::Critical => return Err(BadOption),
                    _ => {}
                },
            }
        }

        let block2 = block2.unwrap_or_default();
        let content_format = content_format.unwrap_or(ContentFormat::TextPlain);
        let accept = accept
            .unwrap_or(Ok(ContentFormat::TextPlain))
            // ... but delaying error conversion until here when we know (well we did before but
            // Rust can't know that) the path
            .map_err(|_| match path {
                Path::Root => NotAcceptableForIndex,
                _ => NotAcceptableForItem,
            })?;

        match path {
            Path::Root => {
                if request.code().into() == code::GET {
                    Ok(GetIndex { accept, block2 })
                } else {
                    Err(MethodNotAllowedRoot)
                }
            }
            Path::Index(index) => {
                let entry = RegistryEntry::nth(index).ok_or(NotFound)?;
                match request.code().into() {
                    code::GET => Ok(Get {
                        entry,
                        accept,
                        block2,
                    }),
                    code::PUT => {
                        self.put_value(entry, content_format, request.payload())?;
                        Ok(Put)
                    }
                    _ => Err(MethodNotAllowedItem),
                }
            }
            _ => Err(NotFound),
        }
    }
    fn estimate_length(&mut self, _: &<Self as coap_handler::Handler>::RequestData) -> usize {
        // Still enough to get a reasonable block in there if it comes to Block2 through countless
        // sensors or a read-all
        200
    }
    fn build_response<M: MutableWritableMessage>(
        &mut self,
        response: &mut M,
        request: Self::RequestData,
    ) -> Result<(), Self::BuildResponseError<M>> {
        let code = match request {
            GetIndex { accept, block2 } => block2_write(block2, response, |w| {
                match accept {
                    ContentFormat::TextPlain => {
                        riot_shell_commands::saul(w, ["saul"].iter().map(|x| *x));
                    }
                    ContentFormat::LinkFormat => {
                        coap_handler_implementations::wkc::write_link_format(w, self, self.prefix)
                            .unwrap();
                    }
                    _ => Err(NotAcceptableForItem)?,
                };
                Ok(code::CONTENT)
            })?,
            Get {
                entry,
                accept,
                block2,
            } => {
                // FIXME: Not sending the content format because it goes between ETag and Block2
                // and the block2_writer won't let us put data inbetween there
                block2_write(block2, response, |w| {
                    // FIXME: In the error case, block and content-format are still there :-(
                    // Worse yet, serde errors are not caught.
                    let phydat = entry.read().map_err(|e| ReadError(e.into()))?;
                    match accept {
                        ContentFormat::TextPlain => writeln!(w, "{}", phydat).unwrap(),
                        ContentFormat::Cbor => {
                            use serde::Serialize;
                            let phydat = JsonStylePhydat(phydat);

                            // Enable this to use serde_cbor
                            // phydat.serialize(&mut serde_cbor::ser::Serializer::new(w));

                            // Usually, this is serialized using minicbor
                            minicbor::encode(&phydat, w);

                            // Enable this to try out ciborium
                            // let mut encoder = ciborium_ll::Encoder::from(w);
                            // phydat.push_to_ciborium(&mut encoder).unwrap();
                            // use ciborium_io::Write;
                            // encoder.flush().unwrap();
                        }
                        _ => Err(NotAcceptableForItem)?,
                    };

                    Ok(code::CONTENT)
                })?
            }
            Put => code::CHANGED,
        };

        response.set_code(Code::new(code).map_err(|_| Error::MissingCoAPStackSupport)?);
        Ok(())
    }
}

pub enum Record {
    Root,
    Entry(usize, RegistryEntry),
}

impl coap_handler::Record for Record {
    type PathElement = heapless::String<4>;
    // FIXME: Once TAIT is stable, replace with the simpler forms below
    type PathElements = core::iter::Once<heapless::String<4>>;
    type Attributes = core::iter::Cloned<core::slice::Iter<'static, coap_handler::Attribute>>;
    // type PathElements = impl Iterator<Item = Self::PathElement>;
    // type Attributes = impl Iterator<Item = coap_handler::Attribute>;

    fn path(&self) -> Self::PathElements {
        let mut buf = heapless::String::new();
        if let Record::Entry(i, _e) = self {
            // Error for i > 9999 checked elsewhere, so this shouldn't happened (but we'll let it
            // slide)
            let _ = write!(buf, "{}", i);
        } // else, Root is just rendered as "" which is already in there
        core::iter::once(buf)
    }
    fn rel(&self) -> core::option::Option<&str> {
        None
    }
    fn attributes(&self) -> Self::Attributes {
        match self {
            Record::Root => [coap_handler::Attribute::Title("SAUL index")].iter().cloned(),
            // FIXME: produce rt="tag:chrysn@fsfe.org,2020-10-02:saul";saul=ACT_LED_RGB
            Record::Entry(_i, e) => [
                coap_handler::Attribute::ResourceType("tag:chrysn@fsfe.org,2020-10-02:saul"),
                // Title would be nice but requires more elaborate structure than [] even though
                // it's a &'static string because the array itself will need to be passed; might
                // work with a heapless::Vec
                // coap_handler::Attribute::Title(e.name().unwrap_or("unnamed")),
                // ... but still, where do we transport the custom saul attribute?
            ]
            .iter()
            .cloned(),
        }
    }
}

// To be removed with TAIT, see below
fn first_arg_fits_in_4_bytes(data: &(usize, RegistryEntry)) -> bool {
    data.0 <= 9999
}

// To be removed with TAIT, see below
fn make_record(data: (usize, RegistryEntry)) -> Record {
    Record::Entry(data.0, data.1)
}

/// A SaulHandler lists all its SAUL devices in /.well-known/core. This is especially useful when
/// registering at a Resource Directory using simple registration and lookup clients try to
/// discover sensors.
impl coap_handler::Reporting for SaulHandler {
    type Record<'res> = Record;
    // FIXME: Once TAIT is stable, this all can become its simple form again, and the filter/map
    // workhorses can become (empty) closures.
    type Reporter<'res> = core::iter::Chain<
        core::iter::Once<Record>,
        core::iter::Map<
            core::iter::Filter<
                core::iter::Enumerate<riot_wrappers::saul::AllRegistryEntries>,
                fn(&(usize, RegistryEntry)) -> bool,
            >,
            fn((usize, RegistryEntry)) -> Record,
        >,
    >;
    // or type Reporter<'res> = impl Iterator<Item=Record>;
    fn report(&self) -> Self::Reporter<'_> {
        core::iter::once(Record::Root).chain(
            RegistryEntry::all()
                .enumerate()
                // for the String<4>, but whoever has so many sensors will have a hard time
                // listing them all in .wk/c anyway
                .filter(first_arg_fits_in_4_bytes as _)
                // or .filter(|(i, _r)| *i <= 9999)
                .map(make_record as _),
                // or .map(|(i, r)| Record::Entry(i, r))
        )
    }
}