Add optional ufmt impls

This commit is contained in:
Danilo Bargen 2020-05-03 13:29:59 +02:00
parent 75bcd7e496
commit 92d1a399e8
3 changed files with 90 additions and 0 deletions

View File

@ -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"

View File

@ -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<N>` and `Vec<u8, N>`
//!
//! [`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;

71
src/ufmt.rs Normal file
View File

@ -0,0 +1,71 @@
use ufmt_write::uWrite;
use crate::{
ArrayLength,
string::String,
vec::Vec,
};
impl<N> uWrite for String<N>
where
N: ArrayLength<u8>,
{
type Error = ();
fn write_str(&mut self, s: &str) -> Result<(), Self::Error> {
self.push_str(s)
}
}
impl<N> uWrite for Vec<u8, N>
where
N: ArrayLength<u8>,
{
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::<U32>::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::<U4>::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::<u8, U32>::new();
uwrite!(v, "{} -> {:?}", a, b).unwrap();
assert_eq!(v, b"123 -> Pair { x: 0, y: 1234 }");
}
}