error_kind/envelopes/alloc/
described.rs1#[cfg(test)]
7#[path = "described.tests.rs"]
8mod tests;
9
10use crate::details::StaticString;
16use crate::envelopes::{Diagnostic, ErrorEnvelope, Located};
17use crate::{Context, ErrorContext, ErrorKind};
18use core::fmt::{Display, Formatter};
19use std_alloc::string::String;
20
21#[derive(Clone, Debug)]
43pub struct Described<K> {
44 description: String,
45 kind: K,
46}
47
48impl<K: ErrorKind> Described<K> {
54 #[inline]
55 pub(crate) fn into_description(self) -> String {
56 self.description
57 }
58}
59
60impl<K> Described<K> {
62 #[inline]
63 pub(crate) fn error_kind_ref(&self) -> &K {
64 &self.kind
65 }
66}
67
68crate::envelopes::impl_error_adapter_traits! {
74 others={
75 alloc=[Diagnostic],
76 core=[Located],
77 },
78 type=Described,
79}
80
81impl<K: ErrorKind> Display for Described<K> {
83 #[track_caller]
84 #[inline]
85 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
86 Display::fmt(&self.kind, f)?;
87 if !self.description.is_empty() {
88 write!(f, ": {}", self.description)?;
89 }
90 Ok(())
91 }
92}
93
94impl<K: ErrorKind> ErrorEnvelope for Described<K> {
96 type Kind = K;
97 type Envelope<T: ErrorKind> = Described<T>;
98
99 #[track_caller]
100 #[inline]
101 fn convert<T>(self) -> Self::Envelope<T>
102 where
103 T: ErrorKind + From<Self::Kind>,
104 {
105 Described {
106 description: self.description,
107 kind: From::from(self.kind),
108 }
109 }
110
111 #[track_caller]
112 #[inline]
113 fn error_kind(&self) -> Self::Kind {
114 self.kind
115 }
116
117 #[track_caller]
118 #[inline]
119 fn new(kind: Self::Kind) -> Self {
120 Self::with_description(kind, String::new())
121 }
122
123 #[track_caller]
124 #[inline]
125 fn with_description<S>(kind: Self::Kind, description: S) -> Self
126 where
127 S: StaticString,
128 {
129 Self {
130 description: description.into_owned(),
131 kind,
132 }
133 }
134}
135
136impl<K: ErrorKind> ErrorContext for Described<K> {
138 #[track_caller]
139 #[inline(always)]
140 fn with_context<C, F>(self, _context: F) -> Self
141 where
142 C: Context,
143 F: FnOnce() -> C,
144 {
145 self
146 }
147}
148
149impl<K: ErrorKind> From<K> for Described<K> {
151 #[inline]
152 fn from(orig: K) -> Self {
153 Self {
154 kind: orig,
155 description: String::new(),
156 }
157 }
158}
159
160impl<K: ErrorKind> From<Diagnostic<K>> for Described<K> {
162 #[track_caller]
163 #[inline]
164 fn from(orig: Diagnostic<K>) -> Self {
165 Self {
166 kind: orig.error_kind(),
167 description: orig.into_description(),
168 }
169 }
170}
171
172impl<K: ErrorKind> From<Located<K>> for Described<K> {
174 #[track_caller]
175 #[inline]
176 fn from(orig: Located<K>) -> Self {
177 Self {
178 kind: orig.error_kind(),
179 description: String::new(),
180 }
181 }
182}