From 86c39b3b4663c401a051a115ddeebaa121de0647 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20J=C3=B6rdens?= Date: Fri, 12 Jul 2024 15:06:34 +0200 Subject: [PATCH] e-io-adapters: add ToFmt: impl fmt::Write --- embedded-io-adapters/CHANGELOG.md | 2 +- embedded-io-adapters/src/fmt.rs | 42 +++++++++++++++++++++++++++++++ embedded-io-adapters/src/lib.rs | 2 ++ 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 embedded-io-adapters/src/fmt.rs diff --git a/embedded-io-adapters/CHANGELOG.md b/embedded-io-adapters/CHANGELOG.md index b540b67b4..f427e0aa1 100644 --- a/embedded-io-adapters/CHANGELOG.md +++ b/embedded-io-adapters/CHANGELOG.md @@ -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 diff --git a/embedded-io-adapters/src/fmt.rs b/embedded-io-adapters/src/fmt.rs new file mode 100644 index 000000000..7a057668d --- /dev/null +++ b/embedded-io-adapters/src/fmt.rs @@ -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 { + inner: T, +} + +impl ToFmt { + /// 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 ToFmt { + /// 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 core::fmt::Write for ToFmt { + 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 +} diff --git a/embedded-io-adapters/src/lib.rs b/embedded-io-adapters/src/lib.rs index f9d0f1a5c..936546e66 100644 --- a/embedded-io-adapters/src/lib.rs +++ b/embedded-io-adapters/src/lib.rs @@ -15,6 +15,8 @@ feature(async_fn_in_trait, impl_trait_projections) )] +pub mod fmt; + #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] pub mod std;