diff --git a/Cargo.toml b/Cargo.toml index b4897b4af7..fc217155a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ x86-sync-pool = [] __trybuild = [] # Enable larger MPMC sizes. mpmc_large = [] +defmt-impl = ["defmt"] [target.x86_64-unknown-linux-gnu.dev-dependencies] scoped_threadpool = "0.1.8" @@ -49,3 +50,12 @@ optional = true [dev-dependencies.ufmt] version = "0.1" + +[dependencies.defmt] +version = "0.2.1" +optional = true + +[dev-dependencies.defmt] +version = "0.2.1" +features = ["unstable-test"] + diff --git a/src/defmt.rs b/src/defmt.rs new file mode 100644 index 0000000000..c8a4ab824c --- /dev/null +++ b/src/defmt.rs @@ -0,0 +1,56 @@ +//! Defmt implementations for heapless types +//! + +use crate::Vec; +use defmt::Formatter; + +impl defmt::Format for Vec +where + T: defmt::Format, +{ + fn format(&self, fmt: Formatter<'_>) { + defmt::write!(fmt, "{=[?]}", self.as_slice()) + } +} + +impl defmt::Format for crate::String +where + u8: defmt::Format, +{ + fn format(&self, fmt: Formatter<'_>) { + defmt::write!(fmt, "{=str}", self.as_str()); + } +} + +#[cfg(test)] +mod tests { + use crate::Vec; + use defmt::Format; + + #[test] + /// Tests encoding Vec with defmt, asserting these types may be serialized + /// Note: the exact wire format is NOT checked since its an unstable implementation detail of an external crate. + /// based on https://github.com/knurling-rs/defmt/blob/697a8e807bd766a80ada2d57514a9da1232dbc9a/tests/encode.rs#L523 + fn test_defmt_format_vec() { + let val: Vec<_, 8> = Vec::from_slice(b"abc").unwrap(); + + let mut f = defmt::InternalFormatter::new(); + let g = defmt::Formatter { inner: &mut f }; + val.format(g); + f.finalize(); + } + + /// Tests encoding String with defmt, asserting these types may be serialized + /// Note: the exact wire format is NOT checked since its an unstable implementation detail of an external crate. + /// based loosely on https://github.com/knurling-rs/defmt/blob/main/tests/encode.rs#L483 + #[test] + fn test_defmt_format_str() { + let mut val: crate::String<32> = crate::String::new(); + val.push_str("foo").unwrap(); + + let mut f = defmt::InternalFormatter::new(); + let g = defmt::Formatter { inner: &mut f }; + val.format(g); + f.finalize(); + } +} diff --git a/src/lib.rs b/src/lib.rs index 54b4f65319..c52e854287 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -94,6 +94,8 @@ mod de; mod ser; pub mod binary_heap; +#[cfg(feature = "defmt-impl")] +mod defmt; #[cfg(all(has_cas, feature = "cas"))] pub mod mpmc; #[cfg(all(has_cas, feature = "cas"))]