1use std::fmt::{Debug, Display, Formatter};
2
3#[derive(Debug, Clone, Eq, PartialEq)]
4pub enum ErrorKind {
5 Message(String),
6 InvalidRange(InvalidRangeError),
8 #[cfg(feature = "zk-pok")]
11 InvalidZkProof,
12}
13
14#[derive(Debug, Clone)]
15pub struct Error {
16 kind: ErrorKind,
17}
18
19impl Error {
20 pub(crate) fn new(message: String) -> Self {
21 Self::from(ErrorKind::Message(message))
22 }
23
24 pub fn kind(&self) -> &ErrorKind {
25 &self.kind
26 }
27}
28
29#[cfg(feature = "shortint")]
30macro_rules! error{
31 ($($arg:tt)*) => {
32 $crate::error::Error::new(::std::format!($($arg)*))
33 }
34}
35
36#[cfg(feature = "shortint")]
37pub(crate) use error;
38
39impl Display for Error {
40 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
41 match self.kind() {
42 ErrorKind::Message(msg) => {
43 write!(f, "{msg}")
44 }
45 #[cfg(feature = "zk-pok")]
46 ErrorKind::InvalidZkProof => {
47 write!(f, "The zero knowledge proof and the content it is supposed to prove were not valid")
48 }
49 ErrorKind::InvalidRange(err) => write!(f, "Invalid range: {err}"),
50 }
51 }
52}
53
54impl From<ErrorKind> for Error {
55 fn from(kind: ErrorKind) -> Self {
56 Self { kind }
57 }
58}
59
60impl<'a> From<&'a str> for Error {
61 fn from(message: &'a str) -> Self {
62 Self::new(message.to_string())
63 }
64}
65
66impl From<String> for Error {
67 fn from(message: String) -> Self {
68 Self::new(message)
69 }
70}
71
72impl From<InvalidRangeError> for Error {
73 fn from(value: InvalidRangeError) -> Self {
74 let kind = ErrorKind::InvalidRange(value);
75 Self { kind }
76 }
77}
78
79impl std::error::Error for Error {}
80
81impl From<std::convert::Infallible> for Error {
83 fn from(_value: std::convert::Infallible) -> Self {
84 unreachable!()
86 }
87}
88
89#[derive(Debug, Clone, Eq, PartialEq)]
91pub enum InvalidRangeError {
92 SliceTooBig,
94 WrongOrder,
96}
97
98impl Display for InvalidRangeError {
99 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
100 match self {
101 Self::SliceTooBig => write!(
102 f,
103 "The upper bound of the range is greater than the size of the integer"
104 ),
105 Self::WrongOrder => {
106 write!(f, "The upper bound is smaller than the lower bound")
107 }
108 }
109 }
110}
111
112impl std::error::Error for InvalidRangeError {}