flex_error/tracer_impl/
string.rs

1use crate::tracer::{ErrorMessageTracer, ErrorTracer};
2use alloc::string::String;
3use core::fmt::{Debug, Display, Formatter};
4
5/// A naive string tracer serializes error messages into
6/// string and simply concatenate them together.
7/// This can be used for example in `no_std` environment,
8/// which may not support more complex error tracers.
9pub struct StringTracer(pub String);
10
11impl ErrorMessageTracer for StringTracer {
12    fn new_message<E: Display>(err: &E) -> Self {
13        StringTracer(alloc::format!("{}", err))
14    }
15
16    fn add_message<E: Display>(self, err: &E) -> Self {
17        StringTracer(alloc::format!("{0}: {1}", err, self.0))
18    }
19
20    #[cfg(feature = "std")]
21    fn as_error(&self) -> Option<&(dyn std::error::Error + 'static)> {
22        None
23    }
24}
25
26impl<E: Display> ErrorTracer<E> for StringTracer {
27    fn new_trace(err: E) -> Self {
28        StringTracer(alloc::format!("{}", err))
29    }
30
31    fn add_trace(self, err: E) -> Self {
32        StringTracer(alloc::format!("{0}: {1}", err, self.0))
33    }
34}
35
36impl Debug for StringTracer {
37    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
38        write!(f, "StringTracer: {0}", self.0)
39    }
40}
41
42impl Display for StringTracer {
43    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
44        write!(f, "{0}", self.0)
45    }
46}