restd/fmt/
adapters.rs

1use super::{Debug, Display, Error, Format, Pretty, Result, Write};
2use core::fmt;
3
4/// A wrapper around a type implementing [`core::fmt::Debug`] to make it
5/// implement [`restd::fmt::Debug`](struct@Debug).
6pub struct StdDebug<T>(pub T);
7
8impl<T: fmt::Debug> Format<Debug> for StdDebug<T> {
9    fn fmt(&self, f: &mut dyn Write, _: &Debug) -> Result {
10        use fmt::Write as _;
11        core::write!(RestdWrite(f), "{:?}", self.0).map_err(|_| Error)
12    }
13}
14
15impl<T: fmt::Debug> Format<Pretty> for StdDebug<T> {
16    fn fmt(&self, f: &mut dyn Write, _: &Pretty) -> Result {
17        use fmt::Write as _;
18        core::write!(RestdWrite(f), "{:#?}", self.0).map_err(|_| Error)
19    }
20}
21
22/// A wrapper around a type implementing [`core::fmt::Display`] to make it
23/// implement [`restd::fmt::Display`](Display).
24pub struct StdDisplay<T>(pub T);
25super::derive!(struct StdDisplay<T!>(t));
26
27impl<T: fmt::Display> Format<Display> for StdDisplay<T> {
28    fn fmt(&self, f: &mut dyn Write, _: &Display) -> Result {
29        use fmt::Write as _;
30        core::write!(RestdWrite(f), "{}", self.0).map_err(|_| Error)
31    }
32}
33
34/// A wrapper around a type implementing [`core::fmt::Write`] to make it
35/// implement [`restd::fmt::Write`](Write).
36pub struct StdWrite<T>(pub T);
37super::derive!(struct StdWrite<T!>(t));
38
39impl<T: fmt::Write> Write for StdWrite<T> {
40    fn write_str(&mut self, s: &str) -> Result {
41        fmt::Write::write_str(&mut self.0, s).map_err(|_| Error)
42    }
43
44    fn write_char(&mut self, ch: char) -> Result {
45        fmt::Write::write_char(&mut self.0, ch).map_err(|_| Error)
46    }
47}
48
49/// A wrapper around a type implementing [`restd::fmt::Write`](Write) to make it
50/// implement [`core::fmt::Write`].
51pub struct RestdWrite<T>(pub T);
52super::derive!(struct RestdWrite<T!>(t));
53
54impl<T: Write> fmt::Write for RestdWrite<T> {
55    fn write_str(&mut self, s: &str) -> fmt::Result {
56        Write::write_str(&mut self.0, s).map_err(|_| fmt::Error)
57    }
58
59    fn write_char(&mut self, ch: char) -> fmt::Result {
60        Write::write_char(&mut self.0, ch).map_err(|_| fmt::Error)
61    }
62}