Skip to content

Commit

Permalink
Defmt impl for String
Browse files Browse the repository at this point in the history
  • Loading branch information
theunkn0wn1 committed Dec 9, 2020
1 parent 143a7b1 commit 0209b3f
Showing 1 changed file with 54 additions and 15 deletions.
69 changes: 54 additions & 15 deletions src/defmt.rs
Original file line number Diff line number Diff line change
@@ -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<T, N> defmt::Format for Vec<T, N>
where N: ArrayLength<T>, T: defmt::Format {
where
N: ArrayLength<T>,
T: defmt::Format,
{
fn format(&self, fmt: &mut Formatter) {
fmt.fmt_slice(self)
}
}

impl<N> defmt::Format for crate::String<N>
where
N: ArrayLength<u8>,
u8: defmt::Format,
{
fn format(&self, fmt: &mut Formatter) {
fmt.str(self.as_str());
}
}

#[cfg(test)]
mod tests {
Expand All @@ -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();

Expand All @@ -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::consts::U32> = 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,
]
);
}
}

0 comments on commit 0209b3f

Please sign in to comment.