From 0209b3ff64b68c362465a170dba2798d2ff0313c Mon Sep 17 00:00:00 2001 From: Joshua Salzedo Date: Wed, 23 Sep 2020 11:05:07 -0700 Subject: [PATCH] Defmt impl for String --- src/defmt.rs | 69 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 15 deletions(-) diff --git a/src/defmt.rs b/src/defmt.rs index f070b9fea9..26a847de73 100644 --- a/src/defmt.rs +++ b/src/defmt.rs @@ -1,18 +1,29 @@ //! Defmt implementations for heapless types //! -use defmt::Formatter; -use generic_array::ArrayLength; - +use crate::ArrayLength; use crate::Vec; +use defmt::Formatter; impl defmt::Format for Vec - where N: ArrayLength, T: defmt::Format { +where + N: ArrayLength, + T: defmt::Format, +{ fn format(&self, fmt: &mut Formatter) { fmt.fmt_slice(self) } } +impl defmt::Format for crate::String +where + N: ArrayLength, + u8: defmt::Format, +{ + fn format(&self, fmt: &mut Formatter) { + fmt.str(self.as_str()); + } +} #[cfg(test)] mod tests { @@ -23,7 +34,7 @@ mod tests { #[test] /// Tests encoding Vec with defmt, /// based loosely on https://github.com/knurling-rs/defmt/blob/main/tests/encode.rs#L483 - fn test_defmt_format() { + fn test_defmt_format_vec() { let v: Vec<_, U8> = Vec::from_slice(b"abc").unwrap(); let index = defmt::export::fetch_string_index(); @@ -33,15 +44,43 @@ mod tests { let timestamp = defmt::export::fetch_timestamp(); let mut formatter = defmt::Formatter::new(); defmt::winfo!(formatter, "{:?}", v); - assert_eq!(formatter.bytes(), &[ - index, - timestamp, - v.len().try_into().unwrap(), - fake_interned, // Faked - // Data bytes. - 97u8, - 98u8, - 99u8, - ]); + assert_eq!( + formatter.bytes(), + &[ + index, + timestamp, + v.len().try_into().unwrap(), + fake_interned, // Faked + // Data bytes. + 97u8, + 98u8, + 99u8, + ] + ); + } + + /// Tests encoding String with defmt, + /// based loosely on https://github.com/knurling-rs/defmt/blob/main/tests/encode.rs#L483 + #[test] + fn test_defmt_format_str() { + let mut v: crate::String = crate::String::new(); + v.push_str("foo").unwrap(); + let index = defmt::export::fetch_string_index(); + + let timestamp = defmt::export::fetch_timestamp(); + let mut formatter = defmt::Formatter::new(); + defmt::winfo!(formatter, "{:?}", v); + assert_eq!( + formatter.bytes(), + &[ + index, + timestamp, + v.len().try_into().unwrap(), + // Data bytes. + 102u8, + 111u8, + 111u8, + ] + ); } }