arrayvec_util/
lib.rs

1#![no_std]
2
3use core::fmt::{Display, Write};
4
5use arrayvec::ArrayString;
6
7pub trait ToArrayString {
8    fn to_array_string<const N: usize>(&self) -> ArrayString<N>;
9}
10
11impl<T: Display + ?Sized> ToArrayString for T {
12    #[inline]
13    fn to_array_string<const N: usize>(&self) -> ArrayString<N> {
14        let mut buf = ArrayString::new();
15        write!(buf, "{self}").expect("a Display implementation returned an error unexpectedly");
16        buf
17    }
18}
19
20#[macro_export]
21macro_rules! array_format {
22    ($($tt:tt)*) => {{
23        let mut w = arrayvec::ArrayString::new();
24        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");
25        w
26    }};
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    #[test]
34    fn to_array_string_trait() {
35        struct EndWithExclamationMark(&'static str);
36
37        impl Display for EndWithExclamationMark {
38            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
39                write!(f, "{}!", self.0)
40            }
41        }
42
43        let sentence = EndWithExclamationMark("The quick brown fox jumps over the lazy dog");
44        let sentence_str: ArrayString<44> = sentence.to_array_string();
45
46        assert_eq!(
47            ArrayString::from("The quick brown fox jumps over the lazy dog!"),
48            Ok(sentence_str)
49        );
50    }
51
52    #[test]
53    fn array_format_macro() {
54        let name = "John Doe";
55        let format: ArrayString<22> = array_format!("Hello World, {name}!");
56
57        assert_eq!(ArrayString::from("Hello World, John Doe!"), Ok(format));
58    }
59}