compact_encoding/
error.rs1use std::fmt;
3
4#[derive(fmt::Debug, Clone, PartialEq)]
6pub enum EncodingErrorKind {
7 OutOfBounds,
9 Overflow,
11 InvalidData,
13 External,
15}
16
17#[derive(fmt::Debug, Clone, PartialEq)]
19pub struct EncodingError {
20 pub kind: EncodingErrorKind,
22 pub message: String,
24}
25
26impl std::error::Error for EncodingError {
27 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
28 None
29 }
30}
31
32impl EncodingError {
33 pub fn new(kind: EncodingErrorKind, message: &str) -> Self {
35 Self {
36 kind,
37 message: message.to_string(),
38 }
39 }
40 pub fn overflow(message: &str) -> Self {
42 Self {
43 kind: EncodingErrorKind::Overflow,
44 message: message.to_string(),
45 }
46 }
47 pub fn out_of_bounds(message: &str) -> Self {
49 Self {
50 kind: EncodingErrorKind::OutOfBounds,
51 message: message.to_string(),
52 }
53 }
54 pub fn invalid_data(message: &str) -> Self {
56 Self {
57 kind: EncodingErrorKind::InvalidData,
58 message: message.to_string(),
59 }
60 }
61 pub fn external(message: &str) -> Self {
63 Self {
64 kind: EncodingErrorKind::External,
65 message: message.to_string(),
66 }
67 }
68}
69
70impl fmt::Display for EncodingError {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 let prefix = match self.kind {
73 EncodingErrorKind::OutOfBounds => "Compact encoding failed, out of bounds",
74 EncodingErrorKind::Overflow => "Compact encoding failed, overflow",
75 EncodingErrorKind::InvalidData => "Compact encoding failed, invalid data",
76 EncodingErrorKind::External => {
77 "An external error caused a compact encoding operation to fail"
78 }
79 };
80 write!(f, "{}: {}", prefix, self.message,)
81 }
82}
83
84impl From<EncodingError> for std::io::Error {
85 fn from(e: EncodingError) -> Self {
86 match e.kind {
87 EncodingErrorKind::InvalidData => {
88 std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{e}"))
89 }
90 _ => std::io::Error::new(std::io::ErrorKind::Other, format!("{e}")),
91 }
92 }
93}