#![no_std]
use core::fmt::{Display, Write};
use arrayvec::ArrayString;
pub trait ToArrayString {
fn to_array_string<const N: usize>(&self) -> ArrayString<N>;
}
impl<T: Display + ?Sized> ToArrayString for T {
#[inline]
fn to_array_string<const N: usize>(&self) -> ArrayString<N> {
let mut buf = ArrayString::new();
write!(buf, "{self}").expect("a Display implementation returned an error unexpectedly");
buf
}
}
#[macro_export]
macro_rules! array_format {
($($tt:tt)*) => {{
let mut w = arrayvec::ArrayString::new();
core::fmt::Write::write_fmt(&mut w, core::format_args!($($tt)*)).expect("a formatting trait implementation returned an error when the underlying stream did not");
w
}};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn to_array_string_trait() {
struct EndWithExclamationMark(&'static str);
impl Display for EndWithExclamationMark {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}!", self.0)
}
}
let sentence = EndWithExclamationMark("The quick brown fox jumps over the lazy dog");
let sentence_str: ArrayString<44> = sentence.to_array_string();
assert_eq!(
ArrayString::from("The quick brown fox jumps over the lazy dog!"),
Ok(sentence_str)
);
}
#[test]
fn array_format_macro() {
let name = "John Doe";
let format: ArrayString<22> = array_format!("Hello World, {name}!");
assert_eq!(ArrayString::from("Hello World, John Doe!"), Ok(format));
}
}