coap-message-implementations 0.1.11

Implementations of coap-message traits, and tools for building them
Documentation
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! Implementation of [`coap_message::MutableWritableMessage`] on a slice of memory
//!
//! [`GenericMessage`] is the main struct of this module, with [`Message`] being the legacy version
//! thereof that only supports slices (it is a type alias). A [`GenericMessage`] is constructed
//! based on an [`EncodedMessage`], which can encapsulate anything from slices (when `EM` is a
//! [`SliceMessage`]), to owned data, or something inbetween (like a single [`core::cell::RefMut`]
//! that is being sliced into).
//!
//! Note that the [`crate::inmemory`] has a similar mechanism but uses a
//! [`crate::inmemory::EncodedMessageView`] struct between the message and its encoded type; at the
//! next breaking revision, those might be unified.
#![cfg_attr(feature = "downcast", allow(unsafe_code))]

pub use crate::error::WriteError;

/// A message writing into a preallocated buffer consisting of slices
pub type Message<'a> = GenericMessage<SliceMessage<'a>>;

/// A message writing into a preallocated buffer
#[derive(Clone)]
pub struct GenericMessage<EM: EncodedMessage> {
    /// Pointers to the actuall message data.
    encoded: EM,

    /// Latest option that has been written
    latest: u16,
    /// Index after the last written byte
    end: usize,
    /// First byte of any written payload
    ///
    /// If this has been set, the byte before it was written 0xff. This is None if the was an empty
    /// payload.
    payload_start: Option<usize>,
}

impl<EM: EncodedMessage> core::fmt::Debug for GenericMessage<EM> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("GenericMessage")
            .field("EncodedMessage impl", &core::any::type_name::<EM>())
            .field("encoded.code", &self.encoded.code())
            .field("encoded.tail", &self.encoded.tail())
            .field("latest", &self.latest)
            .field("end", &self.end)
            .field("payload_start", &self.payload_start)
            .finish()
    }
}

#[cfg(feature = "defmt")]
impl<EM: EncodedMessage> defmt::Format for GenericMessage<EM> {
    fn format(&self, f: defmt::Formatter<'_>) {
        defmt::write!(
            f,
            "GenericMessage {{ EncodedMessage impl {=str}, code {=u8}, tail {=[u8]}, latest {=u16}, end {}, payload_start {} }}",
            &core::any::type_name::<EM>(),
            self.encoded.code(),
            self.encoded.tail(),
            self.latest,
            self.end,
            self.payload_start
        );
    }
}

/// Data backing a [`GenericMessage`].
///
/// Think of this as [`core::convert::AsMut`] but with differentiated access to two areas (the code
/// and the options-and-payload).
pub trait EncodedMessage {
    fn code(&self) -> &u8;
    fn code_mut(&mut self) -> &mut u8;
    fn tail(&self) -> &[u8];
    fn tail_mut(&mut self) -> &mut [u8];
}

/// The easiest implementation of [`EncodedMessage`] that is backed by exclusive references.
pub struct SliceMessage<'a> {
    code: &'a mut u8,
    tail: &'a mut [u8],
}

impl EncodedMessage for SliceMessage<'_> {
    fn code_mut(&mut self) -> &mut u8 {
        self.code
    }

    fn tail_mut(&mut self) -> &mut [u8] {
        self.tail
    }

    fn code(&self) -> &u8 {
        self.code
    }

    fn tail(&self) -> &[u8] {
        self.tail
    }
}

/// A CoAP messag that resides in contiguous mutable memory
///
/// Exceeding the guarantees of `MutableWritableMessage`, this does allow some out-of-sequence
/// invocations: Even after payload has been written to, options can be added, memmove'ing
/// (right-rotating) the written payload, possibly truncating it out of the buffer. This is needed
/// to accommodate libOSCORE's requirements (because while libOSCORE can also do without a
/// memmove-ing message, that'd require its use through `WritableMessage` to adhere to in-OSCORE
/// write sequence conventions, making the whole situation no easier on the coap-message
/// abstraction). Data will only be moved if an option is added after content has been set, so this
/// comes at no runtime cost for those who do not need it. (It may be later turned into a feature.
/// Then, the memmove code would be removed; carrying the latest option number in the `WriteState`
/// should come at no extra cost due to the struct's content and alignment).
///
/// When viewed through the [`coap_message::ReadableMessage`] trait, this will behave as if writing
/// had stopped (but still allows writes after reading); in particular, the payload will be shown
/// as empty. (This may be obvious from most points of view, but when coming from a
/// [`coap_message::MutableWritableMessage`] point of view where payloads can only ever be truncated and not
/// made longer, this clarification is relevant).
///
/// The type is covariant over its lifetime. This also means that we can never add any methods
/// where we move references into Self, but we don't do this: The lifetime `'a` only serves to
/// describe the memory backing it; data is moved in there, not stored by reference.
///
/// FIXME: The covaraint property is not available through ... how would it even be made available?
impl<'a> Message<'a> {
    pub fn new(code: &'a mut u8, tail: &'a mut [u8]) -> Self {
        Message {
            encoded: SliceMessage { code, tail },
            latest: 0,
            end: 0,
            payload_start: None,
        }
    }

    /// Create a `MutableWritableMessage` on a buffer that already contains a serialized message
    ///
    /// While this is generally not useful (a parsed message has its paylod already set, and if
    /// there's no payload, there's no space to add options or any payload), it allows mutable
    /// access to the option bytes and the payload. This is primarily useful in situations when
    /// data is processed in place, eg. decrypted (in OSCORE), or CBOR is shifted around to get
    /// contiguous slices out of indefinite length strings.
    ///
    /// This uses the same strategy for errors as [`crate::inmemory::Message`]: Validation happens
    /// incrementally.
    pub fn new_from_existing(code: &'a mut u8, tail: &'a mut [u8]) -> Self {
        // We'll use a read-only message to get the cursor parameters. This is not terribly great
        // performance-wise (this will iterate over the options, and then the user will do that
        // again); can still be improved to keep the cursor in an indefinite state until the
        // options have been iterated over, preferably when the inmemory message gains the
        // corresponding memoization.
        let read_only = crate::inmemory::Message::new(*code, tail);
        // We don't do thorough parsing, just enough to get an easy index. Either the message is
        // valid, then this will be OK, or it's not and the user will get garbage at read time.
        use coap_message::ReadableMessage;
        let payload_len = read_only.payload().len();

        let payload_start = match payload_len {
            0 => None,
            n => Some(tail.len() - n),
        };
        let end = tail.len();

        Message {
            encoded: SliceMessage { code, tail },
            payload_start,
            end,
            // No point in determining what the actual last option is: This is for mutating
            // options, not adding new ones
            latest: u16::MAX,
        }
    }

    #[cfg(feature = "downcast")]
    pub fn downcast_from<M: coap_message::MinimalWritableMessage>(
        generic: &'a mut M,
    ) -> Option<&'a mut Self> {
        let (reference, type_id) = generic.with_static_type_annotation()?.into_inner();
        if type_id != core::any::TypeId::of::<Message<'static>>() {
            return None;
        }
        // One of us, one of us.
        let ptr = reference as *mut M as *mut Self;
        // SAFETY: The RefWithStaticType matching our type ID will only be constructed if M is
        // Message, and whatever Message<'b> it was before, it will live at least for 'a (because
        // we got a &'a Message<'b> and is covariant.
        Some(unsafe { &mut *ptr })
    }
}

impl<T: EncodedMessage> GenericMessage<T> {
    pub fn new_from_empty_encoded(encoded: T) -> Self {
        GenericMessage {
            encoded,
            latest: 0,
            end: 0,
            payload_start: None,
        }
    }
}

fn get_option_header_len(header: u8) -> u8 {
    let mut res = 1;
    match header >> 4 {
        14 => res += 2,
        13 => res += 1,
        _ => (),
    }
    match header & 0b1111 {
        14 => res += 2,
        13 => res += 1,
        _ => (),
    }
    res
}

impl<EM: EncodedMessage> GenericMessage<EM> {
    /// Index up to which the last option was written.
    fn options_end(&self) -> usize {
        self.payload_start.map_or(self.end, |s| s - 1)
    }

    /// Insert an option.
    ///
    /// This behaves similarly to [`add_option()`][coap_message::MinimalWritableMessage::add_option()], but without the limitation of needing to
    /// uphold option ordering manually.
    ///
    /// This comes at the cost of iterating over all options and re-encoding one.
    ///
    /// # Errors
    ///
    /// This function returns a [`WriteError`] if either the message contains malformed options, or
    /// there isn't sufficient space left for the insertion.
    pub fn insert_option(&mut self, number: u16, data: &[u8]) -> Result<(), WriteError> {
        use crate::{
            option_extension::encode_extensions,
            option_iteration::{OptItem, OptPayloadReader},
        };

        let Ok(data_len) = u16::try_from(data.len()) else {
            return Err(WriteError::BadEncoding);
        };

        let mut insertion_point = 0;
        let mut previous_option = 0u16;
        let mut next_option = 0u16;
        let mut next_len = None;

        let options_end = self.options_end();

        let tail = self.encoded.tail_mut();

        if self.latest <= number {
            insertion_point = options_end;
            previous_option = self.latest;
        } else {
            let mut opt_iter = OptPayloadReader::new(tail);
            loop {
                match opt_iter.next() {
                    Some(OptItem::Option { number: num, data }) => {
                        if num <= number {
                            let (slice, base) = opt_iter.destruct();
                            insertion_point = tail.len() - slice.len();
                            previous_option = base;
                            opt_iter = OptPayloadReader::new_from(slice, base);
                            continue;
                        }

                        next_option = num;
                        next_len = Some(
                            u16::try_from(data.len()).expect("Guaranteed by OptPayloadReader"),
                        );
                        break;
                    }
                    _ => return Err(WriteError::BadEncoding),
                }
            }
        }

        // Encode the to-be-inserted option.
        let delta = number.checked_sub(previous_option).expect("Checked above");
        let new_encoded = encode_extensions(delta, data_len);
        let new_encoded = new_encoded.as_ref();

        let current_encoded_len = get_option_header_len(tail[insertion_point]);

        // Except in edgecases this will be 0.
        let encoding_length_delta;
        let next_encoded;

        // Check if option is last.
        let added_len = if let Some(next_len) = next_len {
            // Re-encode following option. After that encoding doesn't change due to being a delta.
            let next_delta = next_option - number;
            let next_encoded_tmp = encode_extensions(next_delta, next_len);

            // Due to changes in option-number-delta the encoding of the option header could shrink
            // by one or two bytes.
            encoding_length_delta = usize::from(current_encoded_len)
                .checked_sub(next_encoded_tmp.as_ref().len())
                .expect("Encoding length can only shrink");

            next_encoded = Some(next_encoded_tmp);
            new_encoded.len() - encoding_length_delta + data.len()
        } else {
            next_encoded = None;

            encoding_length_delta = 0;
            new_encoded.len() + data.len()
        };

        if self.end + added_len > tail.len() {
            return Err(WriteError::OutOfSpace);
        }

        // Could also rotate_right, but we don't need the shifted-out bytes preserved in the
        // area we'll overwrite in the next instructions.
        //
        // This range is always less than `added_len`, as the new encoding always fits into the same space as (or less than) the
        // old encoding.
        let src = insertion_point + encoding_length_delta..self.end;
        self.encoded
            .tail_mut()
            .copy_within(src, insertion_point + added_len);

        if let Some(payload_start) = self.payload_start {
            self.payload_start = Some(payload_start + added_len);
        }

        self.encoded
            .tail_mut()
            .get_mut(insertion_point..insertion_point + new_encoded.len())
            .expect("Remaining length has been checked")
            .copy_from_slice(new_encoded);
        insertion_point += new_encoded.len();
        self.encoded
            .tail_mut()
            .get_mut(insertion_point..insertion_point + data.len())
            .expect("Remaining length has been checked")
            .copy_from_slice(data);
        insertion_point += data.len();

        if let Some(next_encoded) = next_encoded {
            self.encoded
                .tail_mut()
                .get_mut(insertion_point..insertion_point + next_encoded.as_ref().len())
                .expect("Remaining length has been checked")
                .copy_from_slice(next_encoded.as_ref());
        } else {
            self.latest = number;
        }

        self.end += added_len;

        Ok(())
    }

    /// Remove an option from a slice located at `index`.
    /// Requires the current `end` of the message contained in `tail` and the previous option,
    /// in case a following option exists and needs to be re-encoded.
    ///
    /// # Errors
    ///
    /// This function will return an error, if either the message is badly encoded, or tail can't
    /// fit the new encoding (it can be larger by 2 bytes).
    fn remove_option_at(
        tail: &mut [u8],
        index: usize,
        end: usize,
        previous_option: u16,
    ) -> Result<isize, WriteError> {
        use crate::{
            option_extension::encode_extensions,
            option_iteration::{OptItem, OptPayloadReader},
        };

        let mut opt_iter = OptPayloadReader::new_from(&tail[index..], previous_option);

        // Get nescessary info from the to-be-removed option.
        let (number, data) = match opt_iter.next().ok_or(WriteError::BadEncoding)? {
            OptItem::Option { number, data } => (number, data),
            _ => return Err(WriteError::BadEncoding),
        };

        // Get next option if any.
        let next_opt = match opt_iter.next().ok_or(WriteError::BadEncoding)? {
            OptItem::Option { number, data } => Some((number, data)),
            OptItem::Payload(_) => None,
            _ => return Err(WriteError::BadEncoding),
        };

        let current_encoded_len = isize::from(get_option_header_len(tail[index]));

        // Except in edgecases this will be 0.
        let encoding_length_delta;
        let next_encoded;

        // Check if option is last.
        let len_removed = if let Some((next_number, next_data)) = next_opt {
            let next_data_len =
                u16::try_from(next_data.len()).map_err(|_| WriteError::BadEncoding)?;

            // Get the current length of the option header encoding of the next option.
            let current_next_delta = next_number - number;
            let current_next_encoded = encode_extensions(current_next_delta, next_data_len);
            let current_next_encoded_len = current_next_encoded.as_ref().len() as isize;

            // Re-encode following option. After that encoding doesn't change due to being a delta.
            let next_delta = next_number - previous_option;
            let next_encoded_tmp = encode_extensions(next_delta, next_data_len);

            // Due to changes in option-number-delta the encoding of the option header could grow
            // by one or two bytes.
            encoding_length_delta =
                next_encoded_tmp.as_ref().len() as isize - current_next_encoded_len;

            next_encoded = Some(next_encoded_tmp);
            current_encoded_len - encoding_length_delta + data.len() as isize
        } else {
            next_encoded = None;

            encoding_length_delta = 0;
            current_encoded_len + data.len() as isize
        };

        // Encoding length can grow in rare cases (possible if data_len < 3).
        if tail.len() < (end as isize - len_removed) as usize {
            return Err(WriteError::OutOfSpace);
        }

        // Check if we hit the end of the message
        if end.saturating_sub(index + current_encoded_len as usize + data.len()) != 0 {
            // Move remaining options and payload in place.
            let src =
                index + current_encoded_len as usize + data.len() + encoding_length_delta as usize
                    ..end;
            tail.copy_within(src, index + encoding_length_delta as usize);
        }

        // Check if last.
        if let Some(next_encoded) = next_encoded {
            // Insert re-encoded option header.
            tail.get_mut(index..index + next_encoded.as_ref().len())
                .expect("checked above")
                .copy_from_slice(next_encoded.as_ref());
        }

        Ok(len_removed)
    }

    /// Retain all options the `predicate` applies to, the rest will be removed.
    ///
    /// # Errors
    ///
    /// This function will return an error, if the message is either badly encoded, or can't
    /// fit the new encoding (it can be larger by 2 bytes per removed option).
    pub fn retain_options<P>(&mut self, predicate: P) -> Result<(), WriteError>
    where
        P: Fn(u16, &[u8]) -> bool,
    {
        use crate::option_iteration::{OptItem, OptPayloadReader};

        if self.latest == 0 {
            return Ok(());
        }

        let tail = self.encoded.tail_mut();
        let mut opt_iter = OptPayloadReader::new(tail);
        let mut previous_option = 0u16;
        let mut opt_index = 0;

        loop {
            match opt_iter.next() {
                Some(OptItem::Option { number, data }) => {
                    let (slice, _) = opt_iter.destruct();

                    if predicate(number, data) {
                        previous_option = number;
                        opt_index = tail.len() - slice.len();

                        opt_iter = OptPayloadReader::new_from(slice, number);
                        continue;
                    }

                    let len_removed =
                        Self::remove_option_at(tail, opt_index, self.end, previous_option)?;

                    self.end = (self.end as isize - len_removed) as usize;
                    let options_end = if let Some(payload_start) = self.payload_start {
                        let new = (payload_start as isize - len_removed) as usize;
                        self.payload_start = Some(new);
                        new - 1
                    } else {
                        self.end
                    };

                    if opt_index == options_end {
                        self.latest = previous_option;
                        return Ok(());
                    }

                    opt_iter = OptPayloadReader::new_from(&tail[opt_index..], previous_option);
                }
                None | Some(OptItem::Payload(_)) => return Ok(()),
                Some(OptItem::Error(_)) => return Err(WriteError::BadEncoding),
            }
        }
    }

    /// Discard anything that has been written in the message, and allow any operation that would
    /// be allowed after calling [`Self::new()`].
    ///
    /// This is a short-cut to messages that can be snapshotted and rewound, and a band-aid until
    /// that is available in traits.
    pub fn reset(&mut self) {
        self.latest = 0;
        self.end = 0;
        self.payload_start = None;
        // This is not strictly necessary, but at least a temporarily useful thing that will keep
        // users from relying on the code to be persisted.
        *self.encoded.code_mut() = 0;
    }

    /// Expand the bounds of the payload by `added_len`.
    ///
    /// Similar to [`payload_mut_with_len()`][coap_message::MutableWritableMessage::payload_mut_with_len()],
    /// but it has no restriction on length (beyond the length of the underlying buffer).
    pub fn untruncate(&mut self, mut added_len: usize) -> Result<(), WriteError> {
        if self.payload_start.is_none() {
            added_len += 1;
        }

        if self.encoded.tail().len() < self.end + added_len {
            return Err(WriteError::OutOfSpace);
        }

        if self.payload_start.is_none() {
            // Insert payload marker.
            self.encoded.tail_mut()[self.end] = 0xff;
            self.payload_start = Some(self.end + 1);
        }

        self.end += added_len;

        Ok(())
    }

    /// Return the number of bytes that were populated inside tail
    pub fn finish(self) -> usize {
        self.end
    }

    /// Returns the number of bytes that were populated inside tail, along with the encoded data.
    ///
    /// Unlike the more common [`.finish()`][Self::finish], this makes sense mostly for owned EMs,
    /// where the caller has to move it out again and can not use the shadowed reference the caller
    /// retained.
    pub fn finish_and_return(self) -> (usize, EM) {
        (self.end, self.encoded)
    }
}

impl<EM: EncodedMessage> coap_message::ReadableMessage for GenericMessage<EM> {
    type Code = u8;
    type MessageOption<'b>
        = crate::inmemory::MessageOption<'b>
    where
        Self: 'b;
    type OptionsIter<'b>
        = crate::inmemory::OptionsIter<'b>
    where
        Self: 'b;
    fn code(&self) -> u8 {
        *self.encoded.code()
    }
    // Funny detail on the side: If this is called often, an inmemory_write::Message might be more
    // efficient even for plain reading than an inmemory::Message (because we don't have to iterate)
    fn payload(&self) -> &[u8] {
        match self.payload_start {
            None => &[],
            Some(start) => &self.encoded.tail()[start..self.end],
        }
    }
    fn options(&self) -> <Self as coap_message::ReadableMessage>::OptionsIter<'_> {
        crate::inmemory::OptionsIter(crate::option_iteration::OptPayloadReader::new(
            &self.encoded.tail()[..self.end],
        ))
    }
}

impl<EM: EncodedMessage> coap_message::WithSortedOptions for GenericMessage<EM> {}

impl<EM: EncodedMessage> coap_message::MinimalWritableMessage for GenericMessage<EM> {
    type Code = u8;
    type OptionNumber = u16;
    type UnionError = WriteError;
    type AddOptionError = WriteError;
    type SetPayloadError = WriteError;

    fn set_code(&mut self, code: u8) {
        *self.encoded.code_mut() = code;
    }

    fn add_option(&mut self, number: u16, data: &[u8]) -> Result<(), WriteError> {
        let delta = number
            .checked_sub(self.latest)
            .ok_or(WriteError::OutOfSequence)?;
        self.latest = number;
        let encoded = crate::option_extension::encode_extensions(delta, data.len() as u16);
        let encoded = encoded.as_ref();
        let added_len = encoded.len() + data.len();

        // Where we encode the option
        let option_cursor;
        // What .end will be after this operation
        let eventual_end;
        if let Some(payload_start) = self.payload_start {
            option_cursor = payload_start - 1;
            let Some(start_dropping_at) = self.encoded.tail().len().checked_sub(added_len) else {
                // We couldn't even add this if we're completely empty.
                return Err(WriteError::OutOfSpace);
            };
            if start_dropping_at < option_cursor {
                // Can't add it even by dropping all the payload.
                return Err(WriteError::OutOfSpace);
            }
            let retained_payload_with_marker = start_dropping_at - option_cursor;
            // > 1 because we only set the payload marker if there's also non-empty payload
            if retained_payload_with_marker > 1 {
                // Could also rotate_right, but we don't need the shifted-out bytes preserved in the
                // area we'll overwrite in the next instructions
                let src = option_cursor..start_dropping_at;
                self.encoded
                    .tail_mut()
                    .copy_within(src, option_cursor + added_len);

                self.payload_start = Some(payload_start + added_len);
                eventual_end = (self.end + added_len).clamp(0, self.encoded.tail().len());
            } else {
                self.payload_start = None;
                // Difference is 0 or 1
                eventual_end = self.encoded.tail().len() - retained_payload_with_marker;
            }
        } else {
            option_cursor = self.end;
            eventual_end = self.end + added_len;
        }

        self.encoded
            .tail_mut()
            .get_mut(option_cursor..option_cursor + encoded.len())
            .ok_or(WriteError::OutOfSpace)?
            .copy_from_slice(encoded);
        let option_cursor = option_cursor + encoded.len();
        self.encoded
            .tail_mut()
            .get_mut(option_cursor..option_cursor + data.len())
            .ok_or(WriteError::OutOfSpace)?
            .copy_from_slice(data);
        self.end = eventual_end;

        Ok(())
    }

    fn set_payload(&mut self, payload: &[u8]) -> Result<(), WriteError> {
        if self.payload_start.is_some() {
            // We might allow double setting the payload through later extensions, but as for this
            // interface it's once only. We don't detect double setting of empty payloads, but it's
            // not this implementation's purpose to act as a linter.
            //
            // (And whoever uses the options-and-payload-mixed properties will use payload_mut
            // instead).
            return Err(WriteError::OutOfSequence);
        }
        if !payload.is_empty() {
            *self
                .encoded
                .tail_mut()
                .get_mut(self.end)
                .ok_or(WriteError::OutOfSpace)? = 0xff;
            let start = self.end + 1;
            self.end = start + payload.len();
            self.encoded
                .tail_mut()
                .get_mut(start..self.end)
                .ok_or(WriteError::OutOfSpace)?
                .copy_from_slice(payload);
            self.payload_start = Some(start);
        }
        Ok(())
    }

    #[cfg(feature = "downcast")]
    fn with_static_type_annotation(
        &mut self,
    ) -> Option<coap_message::helpers::RefMutWithStaticType<'_, Self>> {
        // SAFETY: It is this type's policy that its RefMutWithStaticType ID is the given
        // Message<'static>.
        Some(unsafe {
            coap_message::helpers::RefMutWithStaticType::new(
                self,
                core::any::TypeId::of::<Message<'static>>(),
            )
        })
    }

    #[inline]
    #[allow(refining_impl_trait_reachable)]
    fn promote_to_mutable_writable_message(&mut self) -> Option<&mut Self> {
        Some(self)
    }
}

impl<EM: EncodedMessage> coap_message::MutableWritableMessage for GenericMessage<EM> {
    fn available_space(&self) -> usize {
        self.encoded.tail().len() - self.options_end()
    }

    fn payload_mut_with_len(&mut self, len: usize) -> Result<&mut [u8], WriteError> {
        if len == 0 {
            // Just finish the side effect and return something good enough; this allows the easier
            // path for the rest of the function to pick a start, end, and serve that.
            self.truncate(0)?;
            return Ok(&mut []);
        }

        let start = match self.payload_start {
            None => {
                self.encoded.tail_mut()[self.end] = 0xff;
                self.end + 1
            }
            Some(payload_start) => payload_start,
        };
        let end = start + len;

        let end = end.clamp(0, self.encoded.tail().len());

        self.payload_start = Some(start);
        self.end = end;
        self.encoded
            .tail_mut()
            .get_mut(start..end)
            .ok_or(WriteError::OutOfSpace)
    }

    fn truncate(&mut self, len: usize) -> Result<(), WriteError> {
        match (len, self.payload_start) {
            (0, Some(payload_start)) => {
                self.end = payload_start - 1;
                self.payload_start = None;
            }
            (0, None) => {}
            (len, Some(payload_start)) if self.end - payload_start >= len => {
                self.end = payload_start + len;
            }
            _ => return Err(WriteError::OutOfSpace),
        }
        Ok(())
    }

    fn mutate_options<F>(&mut self, mut f: F)
    where
        F: FnMut(u16, &mut [u8]),
    {
        // TBD this is excessively complex, and grounds for finding a better interface. ("Set
        // option and give me a key to update it later with a mutable reference")?

        let optend = self.options_end();

        // May end in a payload marker or just plain end
        let mut slice = &mut self.encoded.tail_mut()[..optend];

        let mut option_base = 0;

        while !slice.is_empty() {
            // This is copied and adapted from
            // coap_messsage_utils::option_iteration::OptPayloadReader and not used through it,
            // because that'd be a whole separate implementation there with mut.
            // (It's bad enough that take_extension needs the trickery)
            let delta_len = slice[0];
            slice = &mut slice[1..];

            if delta_len == 0xff {
                break;
            }

            let mut delta = u16::from(delta_len) >> 4;
            let mut len = u16::from(delta_len) & 0x0f;

            let new_len = {
                // Workaround for https://github.com/rust-lang/rust-clippy/issues/10608
                #[allow(clippy::redundant_slicing)]
                // To get take_extension to cooperate...
                let mut readable = &slice[..];

                crate::option_extension::take_extension(&mut delta, &mut readable)
                    .expect("Invalid encoded option in being-written message");
                crate::option_extension::take_extension(&mut len, &mut readable)
                    .expect("Invalid encoded option in being-written message");

                readable.len()
            };
            // ... and get back to a mutable form
            let trim = slice.len() - new_len;
            slice = &mut slice[trim..];

            option_base += delta;

            let len = len.into();
            f(option_base, &mut slice[..len]);
            slice = &mut slice[len..];
        }
    }
}