Skip to content

Commit 09c7505

Browse files
committed
add impl Format for std::sync::Mutex
this introduces a new optional feature `std` and an initial `Format` implementation just for `Mutex`. the hope is that over time more and more `Format` impls for `std` can be added for those who need it. the trigger for this is that i broke the `embassy-sync` build for `std` by adding a `Format` derive to something which was using `Mutex` internally and it wasn't covered by CI there (which by now is rectified). in the ensuing conversation on Matrix it was stated that it might be nice to have `defmt` impls for `std` as well, even if only very few users would exist for this (i'm not one of them, which is how i ended up breaking CI).
1 parent 8e517f8 commit 09c7505

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

defmt/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ homepage = "https://knurling.ferrous-systems.com/"
1818
version = "1.0.1"
1919

2020
[features]
21+
std = ["alloc"]
2122
alloc = []
2223
avoid-default-panic = []
2324
ip_in_core = []

defmt/src/impls/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ mod arrays;
3434
mod core_;
3535
mod primitives;
3636
mod tuples;
37+
#[cfg(feature = "std")]
38+
mod std_;
3739

3840
use defmt_macros::internp;
3941

defmt/src/impls/std_.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use std::sync::TryLockError;
2+
use super::*;
3+
4+
impl<T> Format for std::sync::Mutex<T>
5+
where
6+
T: ?Sized + Format,
7+
{
8+
#[inline]
9+
fn format(&self, fmt: Formatter) {
10+
match self.try_lock() {
11+
Ok(guard) => crate::write!(fmt, "Mutex {{ data: {=?} }}", guard),
12+
Err(TryLockError::Poisoned(err)) => crate::write!(fmt, "Mutex {{ data: {=?} }}", err.get_ref()),
13+
Err(TryLockError::WouldBlock) => crate::write!(fmt, "Mutex {{ data: <locked> }}"),
14+
}
15+
}
16+
}
17+
18+
impl<T> Format for std::sync::MutexGuard<'_, T>
19+
where
20+
T: ?Sized + Format,
21+
{
22+
delegate_format!(T, self, &*self);
23+
}
24+
25+
#[cfg(test)]
26+
mod tests {
27+
use std::sync::Mutex;
28+
use crate as defmt;
29+
30+
#[test]
31+
fn mutex() {
32+
let m = Mutex::new(42);
33+
defmt::info!("{}", m);
34+
}
35+
}

0 commit comments

Comments
 (0)