display_more/display_option/mod.rs
1// Copyright 2021 Datafuse Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16
17/// Implement `Display` for `Option<T>` if T is `Display`.
18///
19/// It outputs a literal string `"None"` if it is None. Otherwise it invokes the Display
20/// implementation for T.
21pub struct DisplayOption<'a, T: fmt::Display>(pub &'a Option<T>);
22
23impl<T: fmt::Display> fmt::Display for DisplayOption<'_, T> {
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 match &self.0 {
26 None => {
27 write!(f, "None")
28 }
29 Some(x) => x.fmt(f),
30 }
31 }
32}
33
34/// Implement `Display` for `Option<T>` if T is `Display`.
35///
36/// It outputs a literal string `"None"` if it is None. Otherwise it invokes the Display
37/// implementation for T.
38///
39/// # Example
40///
41/// ```rust
42/// use display_more::DisplayOptionExt;
43///
44/// let option = Some(1);
45/// assert_eq!(option.display().to_string(), "1");
46/// ```
47pub trait DisplayOptionExt<'a, T: fmt::Display> {
48 fn display(&'a self) -> DisplayOption<'a, T>;
49}
50
51impl<T> DisplayOptionExt<'_, T> for Option<T>
52where T: fmt::Display
53{
54 fn display(&self) -> DisplayOption<T> {
55 DisplayOption(self)
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn test_display_option() {
65 let option = Some(1);
66 assert_eq!(option.display().to_string(), "1");
67 }
68
69 #[test]
70 fn test_display_option_none() {
71 let option = None::<u64>;
72 assert_eq!(option.display().to_string(), "None");
73 }
74}