custom_print/
fmt_writer.rs

1use core::fmt::{self, Arguments, Debug};
2
3use crate::{IntoWriteFn, WriteBytes, WriteStr};
4
5/// A writer that calls `write_str` for each formatted chunk, but do not require allocations.
6///
7/// Write function can return either `()` or `for<E> `[`Result`]`<(), E>`.
8///
9/// # Panics
10///
11/// Writer panics if the write function returns `Result::Err`.
12///
13/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub struct FmtWriter<F1>(F1);
16
17/// A helper trait used by [`FmtWriter`]
18/// to convert wrapped function result to [`fmt::Result`] with error unwrapping.
19///
20/// [`fmt::Result`]: https://doc.rust-lang.org/std/fmt/type.Result.html
21pub trait ExpectFmtWriteResult {
22    /// Performs the conversion with error unwrapping.
23    fn expect_fmt_write_result(self) -> fmt::Result;
24}
25
26impl<F1> FmtWriter<F1>
27where
28    F1: WriteStr,
29{
30    /// Creates a new `FmtWriter` from an object that implements [`WriteStr`].
31    pub fn new(write: F1) -> Self {
32        Self(write)
33    }
34
35    /// Creates a new `FmtWriter` with a [`WriteStr`] wrapper
36    /// deduced with [`IntoWriteFn`] by the closure signature and constructed from it.
37    pub fn from_closure<F, Ts>(closure: F) -> Self
38    where
39        F: IntoWriteFn<Ts, WriteFn = F1>,
40    {
41        Self(closure.into_write_fn())
42    }
43}
44
45impl<F1> FmtWriter<F1>
46where
47    Self: fmt::Write,
48{
49    /// Writes a formatted string into this writer.
50    ///
51    /// This method is primarily used to interface with the [`format_args!`] macro,
52    /// but it is rare that this should explicitly be called.
53    /// The [`write!`] macro should be favored to invoke this method instead.
54    ///
55    /// [`write!`]: https://doc.rust-lang.org/std/macro.write.html
56    /// [`format_args!`]: https://doc.rust-lang.org/std/macro.format_args.html
57    pub fn write_fmt(&mut self, args: Arguments<'_>) -> fmt::Result {
58        fmt::Write::write_fmt(self, args)
59    }
60}
61
62impl<F1> fmt::Write for FmtWriter<F1>
63where
64    Self: WriteStr<Output = fmt::Result>,
65{
66    fn write_str(&mut self, buf: &str) -> fmt::Result {
67        WriteStr::write_str(self, buf)
68    }
69}
70
71impl<F1> WriteStr for FmtWriter<F1>
72where
73    F1: WriteStr,
74    F1::Output: ExpectFmtWriteResult,
75{
76    type Output = fmt::Result;
77
78    fn write_str(&mut self, buf: &str) -> Self::Output {
79        self.0.write_str(buf).expect_fmt_write_result()
80    }
81}
82
83impl<F1> WriteBytes for FmtWriter<F1>
84where
85    F1: WriteBytes,
86    F1::Output: ExpectFmtWriteResult,
87{
88    type Output = fmt::Result;
89
90    fn write_bytes(&mut self, buf: &[u8]) -> Self::Output {
91        self.0.write_bytes(buf).expect_fmt_write_result()
92    }
93}
94
95impl ExpectFmtWriteResult for () {
96    fn expect_fmt_write_result(self) -> fmt::Result {
97        Ok(())
98    }
99}
100
101impl<E: Debug> ExpectFmtWriteResult for Result<(), E> {
102    fn expect_fmt_write_result(self) -> fmt::Result {
103        self.expect("failed writing");
104        Ok(())
105    }
106}