error_kind/envelopes/core/
located.rs1#[cfg(test)]
7#[cfg(feature = "alloc")]
8#[path = "located.tests.rs"]
9mod tests;
10
11use crate::details::StaticString;
17use crate::envelopes::ErrorEnvelope;
18use crate::{Context, ErrorContext, ErrorKind};
19use core::fmt::{Display, Formatter};
20use core::panic::Location;
21
22#[derive(Clone, Debug)]
45pub struct Located<K> {
46 kind: K,
47 location: Option<&'static Location<'static>>,
48}
49
50impl<K: ErrorKind> Located<K> {
56 #[cfg(feature = "alloc")]
57 #[inline]
58 pub(crate) fn into_location(self) -> Option<&'static Location<'static>> {
59 self.location
60 }
61}
62
63impl<K> Located<K> {
65 #[inline]
66 pub(crate) fn error_kind_ref(&self) -> &K {
67 &self.kind
68 }
69}
70
71crate::envelopes::impl_error_adapter_traits! {
77 others={
78 alloc=[Described, Diagnostic],
79 core=[],
80 },
81 type=Located,
82}
83
84impl<K: ErrorKind> Display for Located<K> {
86 #[track_caller]
87 #[inline]
88 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
89 Display::fmt(&self.kind, f)?;
90 if f.alternate()
91 && let Some(location) = self.location
92 {
93 write!(f, "\n at {}", location)?;
94 }
95 Ok(())
96 }
97}
98
99impl<K: ErrorKind> ErrorEnvelope for Located<K> {
101 type Kind = K;
102 type Envelope<T: ErrorKind> = Located<T>;
103
104 #[track_caller]
105 #[inline]
106 fn convert<T>(self) -> Self::Envelope<T>
107 where
108 T: ErrorKind + From<Self::Kind>,
109 {
110 Located {
111 kind: From::from(self.kind),
112 location: self.location,
113 }
114 }
115
116 #[track_caller]
117 #[inline]
118 fn error_kind(&self) -> Self::Kind {
119 self.kind
120 }
121
122 #[track_caller]
123 #[inline]
124 fn new(kind: Self::Kind) -> Self {
125 Self {
126 kind,
127 location: Some(Location::caller()),
128 }
129 }
130
131 #[track_caller]
132 #[inline]
133 fn with_description<S>(kind: Self::Kind, _description: S) -> Self
134 where
135 S: StaticString,
136 {
137 Self::new(kind)
138 }
139}
140
141impl<K: ErrorKind> ErrorContext for Located<K> {
143 #[track_caller]
144 #[inline(always)]
145 fn with_context<C, F>(self, _context: F) -> Self
146 where
147 C: Context,
148 F: FnOnce() -> C,
149 {
150 self
151 }
152}
153
154#[cfg(feature = "alloc")]
156impl<K: ErrorKind> From<K> for Located<K> {
157 #[track_caller]
158 #[inline]
159 fn from(orig: K) -> Self {
160 Self {
161 kind: orig,
162 location: None,
163 }
164 }
165}
166
167#[cfg(feature = "alloc")]
169impl<K: ErrorKind> From<crate::envelopes::Described<K>> for Located<K> {
170 #[track_caller]
171 #[inline]
172 fn from(orig: crate::envelopes::Described<K>) -> Self {
173 Self {
174 kind: orig.error_kind(),
175 location: None,
176 }
177 }
178}
179
180#[cfg(feature = "alloc")]
182impl<K: ErrorKind> From<crate::envelopes::Diagnostic<K>> for Located<K> {
183 #[track_caller]
184 #[inline]
185 fn from(orig: crate::envelopes::Diagnostic<K>) -> Self {
186 Self {
187 kind: orig.error_kind(),
188 location: orig.into_location(),
189 }
190 }
191}