1use crate::std::fmt;
2
3#[derive(Debug)]
7pub struct Error(ErrorKind);
8
9#[derive(Debug)]
10enum ErrorKind {
11 Unsupported {
12 actual: &'static str,
13 expected: &'static str,
14 },
15 InvalidValue {
16 reason: &'static str,
17 },
18 OutsideContainer {
19 method: &'static str,
20 },
21 #[allow(dead_code)] NoAlloc {
23 method: &'static str,
24 },
25}
26
27impl fmt::Display for Error {
28 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
29 match self.0 {
30 ErrorKind::Unsupported { actual, expected } => {
31 write!(f, "unexpected {}, expected {}", actual, expected)
32 }
33 ErrorKind::InvalidValue { reason } => {
34 write!(f, "the value is invalid: {}", reason)
35 }
36 ErrorKind::OutsideContainer { method } => {
37 write!(f, "expected a fragment while buffering {}", method)
38 }
39 ErrorKind::NoAlloc { method } => write!(f, "cannot allocate for {}", method),
40 }
41 }
42}
43
44impl Error {
45 pub(crate) fn unsupported(expected: &'static str, actual: &'static str) -> Self {
46 Error(ErrorKind::Unsupported { actual, expected })
47 }
48
49 pub(crate) fn outside_container(method: &'static str) -> Self {
50 Error(ErrorKind::OutsideContainer { method })
51 }
52
53 pub(crate) fn invalid_value(reason: &'static str) -> Self {
57 Error(ErrorKind::InvalidValue { reason })
58 }
59
60 #[track_caller]
61 pub(crate) fn no_alloc(method: &'static str) -> Self {
62 #[cfg(all(debug_assertions, not(feature = "no_debug_assertions"), not(test)))]
73 {
74 panic!("attempt to allocate for {} would fail; add the `alloc` feature of `sval_buffer` or the depdendent `sval_*` library to support allocation. This call will error instead of panicking in release builds. Add the `feature = no_debug_assertions` feature of `sval_buffer` if this error is expected.", method);
75 }
76 #[cfg(not(all(debug_assertions, not(feature = "no_debug_assertions"), not(test))))]
77 {
78 Error(ErrorKind::NoAlloc { method })
79 }
80 }
81}
82
83#[cfg(feature = "std")]
84mod std_support {
85 use super::*;
86
87 use crate::std::error;
88
89 impl error::Error for Error {}
90}