display_more/
display_result.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 `Result<T, E>` if T and E are `Display`.
18///
19/// It outputs a literal string `"Ok(T)"` if it is Ok. Otherwise it invokes the Display
20/// implementation for E.
21pub struct DisplayResult<'a, T: fmt::Display, E: fmt::Display>(pub &'a Result<T, E>);
22
23impl<T: fmt::Display, E: fmt::Display> fmt::Display for DisplayResult<'_, T, E> {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        match self.0 {
26            Ok(t) => write!(f, "Ok({})", t),
27            Err(e) => write!(f, "Err({})", e),
28        }
29    }
30}
31
32/// Implement `Display` for `Result<T, E>` if T and E are `Display`.
33///
34/// It outputs a literal string `"Ok(T)"` if it is Ok. Otherwise it invokes the Display
35/// implementation for E.
36///
37/// # Example
38///
39/// ```rust
40/// use display_more::DisplayResultExt;
41///
42/// let result = Result::<i32, i32>::Ok(1);
43/// assert_eq!(result.display().to_string(), "Ok(1)");
44///
45/// let result = Result::<i32, i32>::Err(2);
46/// assert_eq!(result.display().to_string(), "Err(2)");
47/// ```
48pub trait DisplayResultExt<'a, T: fmt::Display, E: fmt::Display> {
49    fn display(&'a self) -> DisplayResult<'a, T, E>;
50}
51
52impl<T: fmt::Display, E: fmt::Display> DisplayResultExt<'_, T, E> for Result<T, E> {
53    fn display(&self) -> DisplayResult<'_, T, E> {
54        DisplayResult(self)
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn test_display_result() {
64        let result = Result::<i32, i32>::Ok(1);
65        assert_eq!(result.display().to_string(), "Ok(1)");
66
67        let result = Result::<i32, i32>::Err(2);
68        assert_eq!(result.display().to_string(), "Err(2)");
69    }
70}