diff --git a/Cargo.toml b/Cargo.toml index 5a164076..f1a0cb11 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ version = "0.5.4" [features] default = ["cas"] cas = [] +ufmt-impl = ["ufmt-write"] # only for tests __trybuild = [] @@ -41,3 +42,10 @@ default-features = false [dependencies.stable_deref_trait] version = "1" default-features = false + +[dependencies.ufmt-write] +version = "0.1" +optional = true + +[dev-dependencies.ufmt] +version = "0.1" diff --git a/src/lib.rs b/src/lib.rs index c4141b87..221e169c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,6 +56,14 @@ //! - [`mpmc::Q*`](mpmc/index.html) -- multiple producer multiple consumer lock-free queue //! - [`spsc::Queue`](spsc/struct.Queue.html) -- single producer single consumer lock-free queue //! +//! # Optional Features +//! +//! The `heapless` crate provides the following optional Cargo features: +//! +//! - `ufmt-impl`: Implement [`ufmt_write::uWrite`] for `String` and `Vec` +//! +//! [`ufmt_write::uWrite`]: https://docs.rs/ufmt-write/ +//! //! # Minimum Supported Rust Version (MSRV) //! //! This crate is guaranteed to compile on stable Rust 1.36 and up with its default set of features. @@ -99,4 +107,7 @@ pub mod pool; #[cfg(has_atomics)] pub mod spsc; +#[cfg(feature = "ufmt-impl")] +mod ufmt; + mod sealed; diff --git a/src/ufmt.rs b/src/ufmt.rs new file mode 100644 index 00000000..b3f30e63 --- /dev/null +++ b/src/ufmt.rs @@ -0,0 +1,71 @@ +use ufmt_write::uWrite; + +use crate::{ + ArrayLength, + string::String, + vec::Vec, +}; + +impl uWrite for String +where + N: ArrayLength, +{ + type Error = (); + fn write_str(&mut self, s: &str) -> Result<(), Self::Error> { + self.push_str(s) + } +} + +impl uWrite for Vec +where + N: ArrayLength, +{ + type Error = (); + fn write_str(&mut self, s: &str) -> Result<(), Self::Error> { + self.extend_from_slice(s.as_bytes()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use ufmt::{derive::uDebug, uwrite}; + + use crate::consts::*; + + #[derive(uDebug)] + struct Pair { + x: u32, + y: u32, + } + + #[test] + fn test_string() { + let a = 123; + let b = Pair { x: 0, y: 1234 }; + + let mut s = String::::new(); + uwrite!(s, "{} -> {:?}", a, b).unwrap(); + + assert_eq!(s, "123 -> Pair { x: 0, y: 1234 }"); + } + + #[test] + fn test_string_err() { + let p = Pair { x: 0, y: 1234 }; + let mut s = String::::new(); + assert!(uwrite!(s, "{:?}", p).is_err()); + } + + #[test] + fn test_vec() { + let a = 123; + let b = Pair { x: 0, y: 1234 }; + + let mut v = Vec::::new(); + uwrite!(v, "{} -> {:?}", a, b).unwrap(); + + assert_eq!(v, b"123 -> Pair { x: 0, y: 1234 }"); + } +}