forked from datrs/compact-encoding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.rs
More file actions
93 lines (87 loc) · 2.83 KB
/
error.rs
File metadata and controls
93 lines (87 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//! Basic types of compact_encoding.
use std::fmt;
/// Specific type [EncodingError]
#[derive(fmt::Debug, Clone, PartialEq)]
pub enum EncodingErrorKind {
/// Encoding or decoding did not stay within the bounds of the buffer
OutOfBounds,
/// Buffer data overflowed type during encoding or decoding.
Overflow,
/// Buffer contained invalid data during decoding.
InvalidData,
/// Some external error occurred causing a [`crate::CompactEncoding`] method to fail.
External,
}
/// Encoding/decoding error.
#[derive(fmt::Debug, Clone, PartialEq)]
pub struct EncodingError {
/// Specific type of error
pub kind: EncodingErrorKind,
/// Message for the error
pub message: String,
}
impl std::error::Error for EncodingError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl EncodingError {
/// Create EncodingError
pub fn new(kind: EncodingErrorKind, message: &str) -> Self {
Self {
kind,
message: message.to_string(),
}
}
/// Helper function for making an overflow error
pub fn overflow(message: &str) -> Self {
Self {
kind: EncodingErrorKind::Overflow,
message: message.to_string(),
}
}
/// Helper function for making an out of bounds error
pub fn out_of_bounds(message: &str) -> Self {
Self {
kind: EncodingErrorKind::OutOfBounds,
message: message.to_string(),
}
}
/// Helper function for making an invalid data error
pub fn invalid_data(message: &str) -> Self {
Self {
kind: EncodingErrorKind::InvalidData,
message: message.to_string(),
}
}
/// Helper function for making an invalid data error
pub fn external(message: &str) -> Self {
Self {
kind: EncodingErrorKind::External,
message: message.to_string(),
}
}
}
impl fmt::Display for EncodingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let prefix = match self.kind {
EncodingErrorKind::OutOfBounds => "Compact encoding failed, out of bounds",
EncodingErrorKind::Overflow => "Compact encoding failed, overflow",
EncodingErrorKind::InvalidData => "Compact encoding failed, invalid data",
EncodingErrorKind::External => {
"An external error caused a compact encoding operation to fail"
}
};
write!(f, "{}: {}", prefix, self.message,)
}
}
impl From<EncodingError> for std::io::Error {
fn from(e: EncodingError) -> Self {
match e.kind {
EncodingErrorKind::InvalidData => {
std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{e}"))
}
_ => std::io::Error::other(format!("{e}")),
}
}
}