serde_html_form/ser/
error.rs1use std::{
2 borrow::Cow,
3 error, fmt,
4 str::{self, Utf8Error},
5};
6
7use serde::ser;
8
9#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct Error(ErrorKind);
12
13#[derive(Clone, Debug, PartialEq, Eq)]
14enum ErrorKind {
15 Custom(Cow<'static, str>),
16 Utf8(Utf8Error),
17}
18
19impl Error {
20 pub(super) fn done() -> Self {
21 Error(ErrorKind::Custom("this pair has already been serialized".into()))
22 }
23
24 pub(super) fn not_done() -> Self {
25 Error(ErrorKind::Custom("this pair has not yet been serialized".into()))
26 }
27
28 pub(super) fn unsupported_key() -> Self {
29 Error(ErrorKind::Custom("unsupported key".into()))
30 }
31
32 pub(super) fn unsupported_value() -> Self {
33 Error(ErrorKind::Custom("unsupported value".into()))
34 }
35
36 pub(super) fn unsupported_pair() -> Self {
37 Error(ErrorKind::Custom("unsupported pair".into()))
38 }
39
40 pub(super) fn top_level() -> Self {
41 Error(ErrorKind::Custom("top-level serializer supports only maps and structs".into()))
42 }
43
44 pub(super) fn no_key() -> Self {
45 Error(ErrorKind::Custom("tried to serialize a value before serializing key".into()))
46 }
47
48 pub(super) fn utf8(error: Utf8Error) -> Self {
49 Error(ErrorKind::Utf8(error))
50 }
51}
52
53impl fmt::Display for Error {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 match &self.0 {
56 ErrorKind::Custom(msg) => msg.fmt(f),
57 ErrorKind::Utf8(err) => write!(f, "invalid UTF-8: {}", err),
58 }
59 }
60}
61
62impl error::Error for Error {
63 fn cause(&self) -> Option<&dyn error::Error> {
65 match &self.0 {
66 ErrorKind::Custom(_) => None,
67 ErrorKind::Utf8(err) => Some(err),
68 }
69 }
70
71 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
73 match &self.0 {
74 ErrorKind::Custom(_) => None,
75 ErrorKind::Utf8(err) => Some(err),
76 }
77 }
78}
79
80impl ser::Error for Error {
81 fn custom<T: fmt::Display>(msg: T) -> Self {
82 Self(ErrorKind::Custom(format!("{}", msg).into()))
83 }
84}