Skip to content

Commit

Permalink
Merge pull request #172 from theunkn0wn1/feature/defmt
Browse files Browse the repository at this point in the history
defmt impl for Vec
  • Loading branch information
korken89 authored May 23, 2021
2 parents afd7eb9 + 63d0ed8 commit 6d1a2ed
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"]

56 changes: 56 additions & 0 deletions src/defmt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! Defmt implementations for heapless types
//!

use crate::Vec;
use defmt::Formatter;

impl<T, const N: usize> defmt::Format for Vec<T, N>
where
T: defmt::Format,
{
fn format(&self, fmt: Formatter<'_>) {
defmt::write!(fmt, "{=[?]}", self.as_slice())
}
}

impl<const N: usize> defmt::Format for crate::String<N>
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();
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))]
Expand Down

0 comments on commit 6d1a2ed

Please sign in to comment.