plog/impls/result_log.rs
1//! Plog implementation for Result
2//! defines some methods to work with `plog` using `std::result::Result` wrapper
3//! Due to adhension to method chains, every method consumes and return the ownership
4//! like `Result::map`, `Result::inspect`, etc.
5
6#[cfg(feature = "impls")]
7use crate::{self as plog, error, ok};
8use std::fmt::{Debug, Display};
9
10/// Methods to work with. Where `log = show_ok + show_err`
11pub trait ResultLog<T> {
12 /// Show the content of a `Result` in a `plog::ok!` log or
13 /// a "{name} was failed with " message in `plog::error!` when it's `Result::Err`
14 fn log(self, _: T) -> Self;
15
16 /// Just shows when `Result::is_ok` returns true
17 fn show_ok(self, _: T) -> Self;
18
19 /// Just shows when `Result::is_err` returns true
20 fn show_err(self, _: T) -> Self;
21}
22
23impl<T, U, N> ResultLog<N> for Result<T, U>
24where
25 T: Debug,
26 U: Debug,
27 N: Display,
28{
29 /// Default implementation. Shows "{name} returned {ok:?}" for `Result::Ok`
30 /// and "{name} was failed with {err:?}" for `Result::Err`
31 /// ```rust
32 /// use plog::impls::ResultLog;
33 /// type Res = Result<u8, ()>;
34 ///
35 ///
36 /// let opt_err: Res = Err(());
37 /// let opt_ok: Res = Ok(0);
38 /// opt_ok.log("opt_error"); // Logs "[ERRO]: opt_error was failed with ()"
39 /// opt_err.log("opt_ok"); // Logs "[OKAY]: opt_ok succeed 0"
40 /// ```
41 fn log(self, _name: N) -> Self {
42 #[cfg(feature = "impls")]
43 match self {
44 Ok(ref val) => ok!("{_name} succeed {val:?}"),
45 Err(ref err) => error!("{_name} was failed with {err:?}"),
46 }
47 self
48 }
49
50 /// Like `ResultLog::log`, but just shows for `Option::None`
51 /// ```rust
52 /// use plog::impls::ResultLog;
53 /// type Res = Result<u8, ()>;
54 ///
55 /// let opt_err: Res = Err(());
56 /// opt_err.log("opt_err"); // Logs "[ERRO]: opt_err was failed with ()"
57 /// ```
58 fn show_err(self, _name: N) -> Self {
59 #[cfg(feature = "impls")]
60 if let Err(ref err) = self {
61 error!("{_name} was failed with {err:?}");
62 }
63 self
64 }
65
66 /// Like `ResultLog::log`, but just shows for `Option::Some`
67 /// ```rust
68 /// use plog::impls::ResultLog;
69 /// type Res = Result<u8, ()>;
70 ///
71 /// let opt_ok: Res = Ok(0);
72 /// opt_ok.log("opt_ok"); // Logs "[OKAY]: opt_ok succeed with "Hello world""
73 /// ```
74 fn show_ok(self, _name: N) -> Self {
75 #[cfg(feature = "impls")]
76 if let Ok(ref val) = self {
77 ok!("{_name} succeed with {val:?}");
78 }
79 self
80 }
81}