Skip to main content

coap_message_implementations/inmemory/
buffer_impl_alloc.rs

1//! Implementations of storage buffers for messages that require `alloc`.
2
3extern crate alloc;
4use super::*;
5
6/// An owned (heap allocated) CoAP message buffer.
7///
8/// This is mostly practical for testing to have something similar to [`SliceBuffer`] /
9/// [`SliceBufferMut`] that is distinct from them, and shows how the
10/// [`MessageBuffer`]/[`…Mut`][MessageBufferMut] traits generalize over ownership.
11pub struct BoxBuffer {
12    code: u8,
13    data: alloc::boxed::Box<[u8]>,
14}
15
16impl BoxBuffer {
17    /// Creates a new instance with a given fixed length available for options and payload.
18    pub fn new(length: usize) -> Self {
19        Self {
20            code: 0,
21            data: alloc::vec![0; length].into_boxed_slice(),
22        }
23    }
24}
25
26impl MessageBuffer for BoxBuffer {
27    fn code(&self) -> u8 {
28        self.code
29    }
30
31    fn tail(&self) -> &[u8] {
32        &self.data
33    }
34
35    #[cfg(feature = "downcast")]
36    fn static_variant() -> Option<LifetimesMatterLittle<impl 'static + MessageBuffer>> {
37        // SAFETY: This is the type used here, and it is already 'static
38        Some(unsafe { LifetimesMatterLittle::<Self>::new() })
39    }
40}
41
42impl MessageBufferMut for BoxBuffer {
43    fn code_mut(&mut self) -> &mut u8 {
44        &mut self.code
45    }
46
47    fn tail_mut(&mut self) -> &mut [u8] {
48        &mut self.data
49    }
50
51    #[cfg(feature = "downcast")]
52    fn static_mut_variant() -> Option<LifetimesMatterLittle<impl 'static + MessageBufferMut>> {
53        // SAFETY: This is the type used here, and it is already 'static
54        Some(unsafe { LifetimesMatterLittle::<Self>::new() })
55    }
56}