num_format/
to_formatted_string.rs

1#![cfg(feature = "std")]
2
3use std::fmt;
4use std::io;
5
6use crate::constants::MAX_BUF_LEN;
7use crate::sealed::Sealed;
8use crate::{Buffer, Format, ToFormattedStr};
9
10/// <b><u>A key trait</u></b>. Gives numbers the [`to_formatted_string`] method.
11///
12/// This trait is sealed; so you may not implement it on your own types.
13///
14/// [`to_formatted_string`]: trait.ToFormattedString.html#method.to_formatted_string
15pub trait ToFormattedString: Sealed + Sized {
16    #[doc(hidden)]
17    fn read_to_fmt_writer<F, W>(&self, w: W, format: &F) -> Result<usize, fmt::Error>
18    where
19        F: Format,
20        W: fmt::Write;
21
22    #[doc(hidden)]
23    fn read_to_io_writer<F, W>(&self, w: W, format: &F) -> Result<usize, io::Error>
24    where
25        F: Format,
26        W: io::Write;
27
28    /// Returns a string representation of the number formatted according to the provided format.
29    fn to_formatted_string<F>(&self, format: &F) -> String
30    where
31        F: Format,
32    {
33        let mut s = String::with_capacity(MAX_BUF_LEN);
34        let _ = self.read_to_fmt_writer(&mut s, format).unwrap();
35        s
36    }
37}
38
39impl<T> ToFormattedString for T
40where
41    T: ToFormattedStr,
42{
43    #[inline(always)]
44    fn read_to_fmt_writer<F, W>(&self, mut w: W, format: &F) -> Result<usize, fmt::Error>
45    where
46        F: Format,
47        W: fmt::Write,
48    {
49        let mut buf = Buffer::default();
50        let c = self.read_to_buffer(&mut buf, format);
51        w.write_str(buf.as_str())?;
52        Ok(c)
53    }
54
55    #[inline(always)]
56    fn read_to_io_writer<F, W>(&self, mut w: W, format: &F) -> Result<usize, io::Error>
57    where
58        F: Format,
59        W: io::Write,
60    {
61        let mut buf = Buffer::default();
62        let c = self.read_to_buffer(&mut buf, format);
63        w.write_all(buf.as_bytes())?;
64        Ok(c)
65    }
66}