|
| 1 | +//! Defmt implementations for heapless types |
| 2 | +//! |
| 3 | +
|
| 4 | +use crate::Vec; |
| 5 | +use defmt::Formatter; |
| 6 | + |
| 7 | +impl<T, const N: usize> defmt::Format for Vec<T, N> |
| 8 | + where |
| 9 | + T: defmt::Format, |
| 10 | +{ |
| 11 | + fn format(&self, fmt: Formatter<'_>) { |
| 12 | + defmt::write!(fmt, "{=[?]}", self.as_slice()) |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +impl<const N: usize> defmt::Format for crate::String<N> |
| 17 | + where |
| 18 | + u8: defmt::Format, |
| 19 | +{ |
| 20 | + fn format(&self, fmt: Formatter<'_>) { |
| 21 | + defmt::write!(fmt, "{=str}", self.as_str()); |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +#[cfg(test)] |
| 26 | +mod tests { |
| 27 | + use crate::Vec; |
| 28 | + use defmt::Format; |
| 29 | + |
| 30 | + #[test] |
| 31 | + /// Tests encoding Vec with defmt, asserting these types may be serialized |
| 32 | + /// Note: the exact wire format is NOT checked since its an unstable implementation detail of an external crate. |
| 33 | + /// based on https://github.com/knurling-rs/defmt/blob/697a8e807bd766a80ada2d57514a9da1232dbc9a/tests/encode.rs#L523 |
| 34 | + fn test_defmt_format_vec() { |
| 35 | + let val: Vec<_, 8> = Vec::from_slice(b"abc").unwrap(); |
| 36 | + |
| 37 | + let mut f = defmt::InternalFormatter::new(); |
| 38 | + let g = defmt::Formatter { inner: &mut f }; |
| 39 | + val.format(g); |
| 40 | + f.finalize(); |
| 41 | + } |
| 42 | + |
| 43 | + /// Tests encoding String with defmt, asserting these types may be serialized |
| 44 | + /// Note: the exact wire format is NOT checked since its an unstable implementation detail of an external crate. |
| 45 | + /// based loosely on https://github.com/knurling-rs/defmt/blob/main/tests/encode.rs#L483 |
| 46 | + #[test] |
| 47 | + fn test_defmt_format_str() { |
| 48 | + let mut val: crate::String<32> = crate::String::new(); |
| 49 | + val.push_str("foo").unwrap(); |
| 50 | + |
| 51 | + let mut f = defmt::InternalFormatter::new(); |
| 52 | + let g = defmt::Formatter { inner: &mut f }; |
| 53 | + val.format(g); |
| 54 | + f.finalize(); |
| 55 | + } |
| 56 | +} |
0 commit comments