core_extensions/option_result_ext/
result_extensions.rs

1#[cfg(feature = "alloc")]
2use std_::fmt;
3
4#[cfg(feature = "alloc")]
5use alloc::string::String;
6
7use super::ResultLike;
8
9use type_identity::TypeIdentity;
10
11/// Extension trait for [`Result`].
12///
13/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
14pub trait ResultExt<T, E>: Sized + ResultLike + TypeIdentity<Type = Result<T, E>> {
15    /// Maps `Err` variants to a `Debug` formated String.
16    ///
17    /// Equivalent to `.map_err(|e| format!("{:?}", e))`.
18    ///
19    /// # Example
20    /// ```
21    /// use core_extensions::ResultExt;
22    ///
23    /// let err_msg = "what \"is\" this";
24    /// let err_: Result<(), &str> = Err(err_msg);
25    ///
26    /// assert_eq!(err_.format_debug_err(), Err(format!("{:?}", err_msg)));
27    ///
28    /// ```
29    #[inline]
30    #[cfg(feature = "alloc")]
31    fn format_debug_err(self) -> Result<T, String>
32    where
33        E: fmt::Debug,
34    {
35        self.into_type().map_err(|e| format!("{:?}", e))
36    }
37    /// Maps `Err` variants to an alternate `Debug` formated String.
38    ///
39    /// Equivalent to `.map_err(|e| format!("{:#?}", e))`.
40    ///
41    /// # Example
42    /// ```
43    /// use core_extensions::ResultExt;
44    ///
45    /// let err_msg = "what \"is\" this";
46    /// let err_: Result<(), &str> = Err(err_msg);
47    ///
48    /// assert_eq!(err_.format_alt_debug_err(), Err(format!("{:#?}", err_msg)));
49    ///
50    /// ```
51    #[inline]
52    #[cfg(feature = "alloc")]
53    fn format_alt_debug_err(self) -> Result<T, String>
54    where
55        E: fmt::Debug,
56    {
57        self.into_type().map_err(|e| format!("{:#?}", e))
58    }
59}
60
61impl<E, T> ResultExt<T, E> for Result<T, E> {}
62
63impl<E, T> ResultLike for Result<T, E> {
64    type Item = T;
65    type Error = E;
66    
67    #[inline]
68    fn is_item(&self) -> bool {
69        self.is_ok()
70    }
71    #[inline]
72    fn into_result_(self) -> Result<Self::Item, Self::Error> {
73        self
74    }
75
76    #[inline]
77    fn from_result_(from: Self) -> Self {
78        from
79    }
80
81    #[inline]
82    fn from_item(item: Self::Item) -> Self {
83        Ok(item)
84    }
85    
86    #[inline]
87    fn from_error(err: Self::Error) -> Self {
88        Err(err)
89    }
90}