serde/
expected.rs

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
use std::fmt::{Debug, Display};

use super::{de::Unexpected, visitor::Visitor};

/// To display an error when the expected type is different from the current value.
pub trait Expected {
    fn expected(&self) -> &'static str;
}

impl<T> Expected for T
where
    T: Visitor + ?Sized,
{
    fn expected(&self) -> &'static str {
        T::expected(self)
    }
}

impl Expected for &'static str {
    fn expected(&self) -> &'static str {
        self
    }
}

#[derive(Debug)]
pub struct TypeMismatchError {
    unexpected: Unexpected,
    expected: &'static str,
}

impl TypeMismatchError {
    pub fn new<T>(unexpected: Unexpected, expected: T) -> Self
    where
        T: Expected,
    {
        TypeMismatchError {
            unexpected,
            expected: expected.expected(),
        }
    }
}

impl Display for TypeMismatchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "unexpected `{}`, expected `{}`",
            self.unexpected, self.expected
        )
    }
}