Skip to content

Commit

Permalink
Merge pull request #276 from knurling-rs/book-write
Browse files Browse the repository at this point in the history
document write! in the book
  • Loading branch information
japaric authored Nov 25, 2020
2 parents 24cb700 + 471b618 commit 6576533
Showing 1 changed file with 51 additions and 4 deletions.
55 changes: 51 additions & 4 deletions book/src/format.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# `#[derive(Format)]`
# Implementing `Format`

To implement the `Format` trait for a struct or enum use the `derive` attribute.
## `#[derive(Format)]`

The easiest way to implement the `Format` trait for a struct or enum is to use the `derive` attribute.

``` rust
# extern crate defmt;
Expand All @@ -24,5 +26,50 @@ enum Request {

NOTE: Like built-in derives like `#[derive(Debug)]`, `#[derive(Format)]` will add `Format` bounds to the generic type parameters of the struct.

NOTE: At the moment is not possible to implement the `Format` trait manually. Do *not* use the API
used by the expansion of the `derive(Format)` macro; it is currently *unstable*.
NOTE: Do *not* use the API used by the expansion of the `derive(Format)` macro; it is *unstable*.

## `write!`

It is also possible to implement the `Format` trait manually.
This trait has a single required method: `format`.
In this method you need to format the value (`self`) into the given `Formatter` argument using the `defmt::write!` macro.
Example below:

``` rust
# extern crate defmt;
// value read from a MMIO register named "CRCCNF"
struct CRCCNF {
bits: u32,
}

impl defmt::Format for CRCCNF {
fn format(&self, f: &mut defmt::Formatter) {
// format the bitfields of the register as struct fields
defmt::write!(
f,
"CRCCNF {{ LEN: {0:0..2}, SKIPADDR: {0:8..10} }}",
self.bits,
)
}
}
```

NOTE: in defmt v0.1.x the `write!` macro must be invoked at most once within the implementation of the `fmt` method. Invoking the method more than once will produce a panic

## Newtypes

If you need to implement `Format` for some "newtype" struct you can delegate the formatting to the inner type.
Example below:

``` rust
# extern crate defmt;
struct MyU8 { inner: u8 }

impl defmt::Format for MyU8 {
fn format(&self, f: &mut defmt::Formatter) {
self.inner.format(f)
}
}
```

**WARNING** never call `format` more than once, since this will corrupt the data stream!

0 comments on commit 6576533

Please sign in to comment.