devela/code/result/opt_res/
fmt.rs

1// devela::code::result::option::fmt
2//
3//!
4//
5
6use super::ExtOption;
7use core::fmt::{
8    Binary, Debug, Display, Formatter, LowerExp, LowerHex, Octal, Pointer, Result, UpperExp,
9    UpperHex,
10};
11
12/// The type returned from [`ExtOption::fmt_or_empty`].
13#[derive(Eq, PartialEq)]
14pub struct OptionFmt<'t, T>(pub(super) &'t Option<T>);
15
16/// The type returned from [`ExtOption::fmt_or`].
17pub struct OptionFmtOr<'t, T, U>(pub(super) &'t Option<T>, pub(super) U);
18
19/// The type returned from [`ExtOption::fmt_or_else`].
20pub struct OptionFmtOrElse<'t, T, F>(pub(super) &'t Option<T>, pub(super) F);
21
22impl<T> Copy for OptionFmt<'_, T> {}
23impl<T> Clone for OptionFmt<'_, T> {
24    fn clone(&self) -> Self {
25        *self
26    }
27}
28
29impl<T, U: Copy> Copy for OptionFmtOr<'_, T, U> {}
30impl<T, U: Clone> Clone for OptionFmtOr<'_, T, U> {
31    fn clone(&self) -> Self {
32        Self(self.0, self.1.clone())
33    }
34}
35
36impl<T, F: Copy> Copy for OptionFmtOrElse<'_, T, F> {}
37impl<T, F: Clone> Clone for OptionFmtOrElse<'_, T, F> {
38    fn clone(&self) -> Self {
39        Self(self.0, self.1.clone())
40    }
41}
42
43macro_rules! impl_option_fmt {
44    ($($trait:ident),*$(,)?) => { $(
45
46        impl<T> $trait for OptionFmt<'_, T>
47        where
48            T: $trait,
49        {
50            fn fmt(&self, out: &mut Formatter<'_>) -> Result {
51                $trait::fmt(&self.0.fmt_or(""), out)
52            }
53        }
54
55        impl<'t, T, U> $trait for OptionFmtOr<'t, T, U>
56        where
57            T: $trait,
58            U: Display,
59        {
60            fn fmt(&self, out: &mut Formatter<'_>) -> Result {
61                $trait::fmt(&self.0.fmt_or_else(||&self.1), out)
62            }
63        }
64
65        impl<'t, T, F, U> $trait for OptionFmtOrElse<'t, T, F>
66        where
67            T: $trait,
68            F: Fn() -> U,
69            U: Display,
70        {
71            fn fmt(&self, out: &mut Formatter<'_>) -> Result {
72                if let Some(t) = self.0 {
73                    <T as $trait>::fmt(t, out)
74                } else {
75                    Display::fmt(&self.1(), out)
76                }
77            }
78        }
79
80    )*}
81}
82impl_option_fmt!(Binary, Debug, Display, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex);