serde_teamspeak_querystring/
error.rs1use std::fmt;
2
3#[derive(Debug, Eq, PartialEq)]
4pub enum ErrorKind {
5 UnexpectedType,
6 InvalidLength,
7 InvalidEncoding,
8 InvalidNumber,
9 InvalidBoolean,
10 Other,
11}
12
13#[derive(Debug, Eq, PartialEq)]
14pub struct Error {
15 pub kind: ErrorKind,
16 pub message: String,
17
18 pub key: String,
20
21 pub value: Option<String>,
23
24 pub index: Option<usize>,
27}
28
29impl Error {
30 pub(crate) fn new(kind: ErrorKind) -> Self {
31 Error {
32 kind,
33 message: String::new(),
34 key: String::new(),
35 value: None,
36 index: None,
37 }
38 }
39
40 pub(crate) fn message(mut self, message: String) -> Self {
41 self.message = message;
42 self
43 }
44
45 pub(crate) fn key(mut self, key: &[u8]) -> Self {
46 self.key = String::from_utf8_lossy(key).to_string();
47 self
48 }
49
50 pub(crate) fn value(mut self, value: &[u8]) -> Self {
51 self.value = Some(String::from_utf8_lossy(value).to_string());
52 self
53 }
54
55 pub(crate) fn index(mut self, index: usize) -> Self {
56 self.index = Some(index);
57 self
58 }
59}
60
61impl serde::de::Error for Error {
62 fn custom<T>(msg: T) -> Self
63 where
64 T: fmt::Display,
65 {
66 Error::new(ErrorKind::Other).message(msg.to_string())
67 }
68}
69
70impl std::error::Error for Error {}
71
72impl fmt::Display for Error {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
74 match &self.value {
75 Some(v) => match self.index {
76 Some(i) => f.write_fmt(format_args!(
77 "Error {:?}: {} in '{}={}' at index {}",
78 self.kind,
79 self.message,
80 self.key,
81 v,
82 i + self.key.len() + 2
83 )),
84 None => f.write_fmt(format_args!(
85 "Error {:?}: {} in '{}={}'",
86 self.kind, self.message, self.key, v
87 )),
88 },
89 None => f.write_fmt(format_args!(
90 "Error {:?}: {} for key '{}'",
91 self.kind, self.message, self.key
92 )),
93 }
94 }
95}
96
97pub type Result<T> = std::result::Result<T, Error>;