Skip to content

Commit 4e9f3ed

Browse files
authored
Merge pull request #616 from quartiq/adapter-core-fmt-write
e-io-adapters: add ToFmt: impl fmt::Write
2 parents 5055422 + 86c39b3 commit 4e9f3ed

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

embedded-io-adapters/CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## Unreleased
99

10-
Add unreleased changes here
10+
- Added `ToFmt` adapter for `core::fmt::Write`.
1111

1212
## 0.6.1 - 2023-11-28
1313

embedded-io-adapters/src/fmt.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//! Adapters to the `core::fmt::Write`.
2+
3+
/// Adapter to the `core::fmt::Write` trait.
4+
#[derive(Clone, Default, PartialEq, Debug)]
5+
pub struct ToFmt<T: ?Sized> {
6+
inner: T,
7+
}
8+
9+
impl<T> ToFmt<T> {
10+
/// Create a new adapter.
11+
pub fn new(inner: T) -> Self {
12+
Self { inner }
13+
}
14+
15+
/// Consume the adapter, returning the inner object.
16+
pub fn into_inner(self) -> T {
17+
self.inner
18+
}
19+
}
20+
21+
impl<T: ?Sized> ToFmt<T> {
22+
/// Borrow the inner object.
23+
pub fn inner(&self) -> &T {
24+
&self.inner
25+
}
26+
27+
/// Mutably borrow the inner object.
28+
pub fn inner_mut(&mut self) -> &mut T {
29+
&mut self.inner
30+
}
31+
}
32+
33+
impl<T: embedded_io::Write + ?Sized> core::fmt::Write for ToFmt<T> {
34+
fn write_str(&mut self, s: &str) -> core::fmt::Result {
35+
self.inner.write_all(s.as_bytes()).or(Err(core::fmt::Error))
36+
}
37+
38+
// Use fmt::Write default impls for
39+
// * write_fmt(): better here than e-io::Write::write_fmt
40+
// since we don't need to bother with saving the Error
41+
// * write_char(): would be the same
42+
}

embedded-io-adapters/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
#![warn(missing_docs)]
44
#![doc = include_str!("../README.md")]
55

6+
pub mod fmt;
7+
68
#[cfg(feature = "std")]
79
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
810
pub mod std;

0 commit comments

Comments
 (0)