| 1 | use core::fmt::Display; |
| 2 | #[cfg (feature = "std" )] |
| 3 | use std::path::{self, Path, PathBuf}; |
| 4 | |
| 5 | #[doc (hidden)] |
| 6 | pub trait AsDisplay<'a>: Sealed { |
| 7 | // TODO: convert to generic associated type. |
| 8 | // https://github.com/dtolnay/thiserror/pull/253 |
| 9 | type Target: Display; |
| 10 | |
| 11 | fn as_display(&'a self) -> Self::Target; |
| 12 | } |
| 13 | |
| 14 | impl<'a, T> AsDisplay<'a> for &T |
| 15 | where |
| 16 | T: Display + ?Sized + 'a, |
| 17 | { |
| 18 | type Target = &'a T; |
| 19 | |
| 20 | fn as_display(&'a self) -> Self::Target { |
| 21 | *self |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | #[cfg (feature = "std" )] |
| 26 | impl<'a> AsDisplay<'a> for Path { |
| 27 | type Target = path::Display<'a>; |
| 28 | |
| 29 | #[inline ] |
| 30 | fn as_display(&'a self) -> Self::Target { |
| 31 | self.display() |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | #[cfg (feature = "std" )] |
| 36 | impl<'a> AsDisplay<'a> for PathBuf { |
| 37 | type Target = path::Display<'a>; |
| 38 | |
| 39 | #[inline ] |
| 40 | fn as_display(&'a self) -> Self::Target { |
| 41 | self.display() |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | #[doc (hidden)] |
| 46 | pub trait Sealed {} |
| 47 | impl<T: Display + ?Sized> Sealed for &T {} |
| 48 | #[cfg (feature = "std" )] |
| 49 | impl Sealed for Path {} |
| 50 | #[cfg (feature = "std" )] |
| 51 | impl Sealed for PathBuf {} |
| 52 | |
| 53 | // Add a synthetic second impl of AsDisplay to prevent the "single applicable |
| 54 | // impl" rule from making too weird inference decision based on the single impl |
| 55 | // for &T, which could lead to code that compiles with thiserror's std feature |
| 56 | // off but breaks under feature unification when std is turned on by an |
| 57 | // unrelated crate. |
| 58 | #[cfg (not(feature = "std" ))] |
| 59 | mod placeholder { |
| 60 | use super::{AsDisplay, Sealed}; |
| 61 | use core::fmt::{self, Display}; |
| 62 | |
| 63 | pub struct Placeholder; |
| 64 | |
| 65 | impl<'a> AsDisplay<'a> for Placeholder { |
| 66 | type Target = Self; |
| 67 | |
| 68 | #[inline ] |
| 69 | fn as_display(&'a self) -> Self::Target { |
| 70 | Placeholder |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | impl Display for Placeholder { |
| 75 | fn fmt(&self, _formatter: &mut fmt::Formatter) -> fmt::Result { |
| 76 | unreachable!() |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | impl Sealed for Placeholder {} |
| 81 | } |
| 82 | |