tansu_model/
error.rs

1// Copyright ⓒ 2024-2025 Peter Morgan <peter.james.morgan@gmail.com>
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16    fmt::{self, Display},
17    io, num, str, string,
18};
19
20use serde::{de, ser};
21
22#[derive(Debug)]
23pub enum Error {
24    DryPop,
25    EmptyStack,
26    FromUtf8(string::FromUtf8Error),
27    Io(io::Error),
28    Json(serde_json::Error),
29    Message(String),
30    NoCurrentFieldMeta,
31    NoMessageMeta,
32    NoSuchField(&'static str),
33    NoSuchMessage(&'static str),
34    ParseBool(str::ParseBoolError),
35    ParseInt(num::ParseIntError),
36    Syn(syn::Error),
37    TryFromInt(num::TryFromIntError),
38    Utf8(str::Utf8Error),
39}
40
41impl std::error::Error for Error {}
42
43impl ser::Error for Error {
44    fn custom<T: Display>(msg: T) -> Self {
45        Error::Message(msg.to_string())
46    }
47}
48
49impl de::Error for Error {
50    fn custom<T: Display>(msg: T) -> Self {
51        Error::Message(msg.to_string())
52    }
53}
54
55impl From<io::Error> for Error {
56    fn from(value: io::Error) -> Self {
57        Self::Io(value)
58    }
59}
60
61impl From<str::Utf8Error> for Error {
62    fn from(value: str::Utf8Error) -> Self {
63        Self::Utf8(value)
64    }
65}
66
67impl From<string::FromUtf8Error> for Error {
68    fn from(value: string::FromUtf8Error) -> Self {
69        Self::FromUtf8(value)
70    }
71}
72
73impl From<num::TryFromIntError> for Error {
74    fn from(value: num::TryFromIntError) -> Self {
75        Self::TryFromInt(value)
76    }
77}
78
79impl From<str::ParseBoolError> for Error {
80    fn from(value: str::ParseBoolError) -> Self {
81        Self::ParseBool(value)
82    }
83}
84
85impl From<num::ParseIntError> for Error {
86    fn from(value: num::ParseIntError) -> Self {
87        Self::ParseInt(value)
88    }
89}
90
91impl From<serde_json::Error> for Error {
92    fn from(value: serde_json::Error) -> Self {
93        Self::Json(value)
94    }
95}
96
97impl From<syn::Error> for Error {
98    fn from(value: syn::Error) -> Self {
99        Self::Syn(value)
100    }
101}
102
103impl Display for Error {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match self {
106            Error::Message(e) => f.write_str(e),
107            e => write!(f, "{e:?}"),
108        }
109    }
110}