Skip to content

Commit

Permalink
Merge pull request #616 from quartiq/adapter-core-fmt-write
Browse files Browse the repository at this point in the history
e-io-adapters: add ToFmt: impl fmt::Write
  • Loading branch information
Dirbaio authored Jul 26, 2024
2 parents 5055422 + 86c39b3 commit 4e9f3ed
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion embedded-io-adapters/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

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

## 0.6.1 - 2023-11-28

Expand Down
42 changes: 42 additions & 0 deletions embedded-io-adapters/src/fmt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//! Adapters to the `core::fmt::Write`.
/// Adapter to the `core::fmt::Write` trait.
#[derive(Clone, Default, PartialEq, Debug)]
pub struct ToFmt<T: ?Sized> {
inner: T,
}

impl<T> ToFmt<T> {
/// Create a new adapter.
pub fn new(inner: T) -> Self {
Self { inner }
}

/// Consume the adapter, returning the inner object.
pub fn into_inner(self) -> T {
self.inner
}
}

impl<T: ?Sized> ToFmt<T> {
/// Borrow the inner object.
pub fn inner(&self) -> &T {
&self.inner
}

/// Mutably borrow the inner object.
pub fn inner_mut(&mut self) -> &mut T {
&mut self.inner
}
}

impl<T: embedded_io::Write + ?Sized> core::fmt::Write for ToFmt<T> {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
self.inner.write_all(s.as_bytes()).or(Err(core::fmt::Error))
}

// Use fmt::Write default impls for
// * write_fmt(): better here than e-io::Write::write_fmt
// since we don't need to bother with saving the Error
// * write_char(): would be the same
}
2 changes: 2 additions & 0 deletions embedded-io-adapters/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]

pub mod fmt;

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub mod std;
Expand Down

0 comments on commit 4e9f3ed

Please sign in to comment.