smart_format/combinator/
conditional.rs1use core::fmt;
2
3pub struct If<T> {
5 inner: T,
6 condition: bool,
7}
8
9impl<T> If<T> {
10 pub(crate) fn new(inner: T, condition: bool) -> Self {
11 If { inner, condition }
12 }
13}
14
15impl<T: fmt::Display> fmt::Display for If<T> {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 if self.condition {
18 self.inner.fmt(f)
19 } else {
20 Ok(())
21 }
22 }
23}
24
25pub struct Or<T, U> {
28 inner: T,
29 use_fallback: bool,
30 fallback: U,
31}
32
33impl<T, U> Or<T, U> {
34 pub(crate) fn new(inner: T, use_fallback: bool, fallback: U) -> Self {
35 Or {
36 inner,
37 use_fallback,
38 fallback,
39 }
40 }
41}
42
43impl<T: fmt::Display, U: fmt::Display> fmt::Display for Or<T, U> {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 if self.use_fallback {
46 self.fallback.fmt(f)
47 } else {
48 self.inner.fmt(f)
49 }
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 use crate::combinator::SmartFormat;
56
57 #[test]
58 fn if_true_displays() {
59 assert_eq!("hello", "hello".display_if(true).to_string());
60 }
61
62 #[test]
63 fn if_false_is_empty() {
64 assert_eq!("", "hello".display_if(false).to_string());
65 }
66
67 #[test]
68 fn if_chain_with_wrap() {
69 let result = "hello".display_if(true).display_wrap("[", "]").to_string();
70 assert_eq!("[hello]", result);
71 }
72
73 #[test]
74 fn if_false_chain_with_wrap() {
75 let result = "hello".display_if(false).display_wrap("[", "]").to_string();
76 assert_eq!("[]", result);
77 }
78
79 #[test]
80 fn or_uses_self() {
81 assert_eq!(
82 "hello",
83 "hello".display_or_if(false, "fallback").to_string()
84 );
85 }
86
87 #[test]
88 fn or_uses_fallback() {
89 assert_eq!(
90 "fallback",
91 "hello".display_or_if(true, "fallback").to_string()
92 );
93 }
94
95 #[test]
96 fn or_with_different_types() {
97 let n: i32 = 42;
98 assert_eq!("42", n.display_or_if(false, "N/A").to_string());
99 assert_eq!("N/A", n.display_or_if(true, "N/A").to_string());
100 }
101}