Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

document write! in the book #276

Merged
merged 4 commits into from
Nov 25, 2020
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 46 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,45 @@ 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;
struct S {
x: u8,
y: u16,
}

impl defmt::Format for S {
fn format(&self, f: &mut defmt::Formatter) {
defmt::write!(f, "S {{ x: {:u8}, y: {:u16} }}", self.x, self.y)
}
}
```

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!