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
#[derive(Clone, Debug)]
pub(crate) struct DecodeColumnError {
    path: Path,
    error: DecodeColErrorKind,
}

impl std::error::Error for DecodeColumnError {}

impl std::fmt::Display for DecodeColumnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.error {
            DecodeColErrorKind::UnexpectedNull => {
                write!(f, "unexpected null in column {}", self.path)
            }
            DecodeColErrorKind::InvalidValue { reason } => {
                write!(f, "invalid value in column {}: {}", self.path, reason)
            }
        }
    }
}

#[derive(Clone, Debug)]
struct Path(Vec<String>);

impl std::fmt::Display for Path {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (index, elem) in self.0.iter().rev().enumerate() {
            if index != 0 {
                write!(f, ":")?;
            }
            write!(f, "{}", elem)?;
        }
        Ok(())
    }
}

impl Path {
    fn push<S: AsRef<str>>(&mut self, col: S) {
        self.0.push(col.as_ref().to_string())
    }
}

impl<S: AsRef<str>> From<S> for Path {
    fn from(p: S) -> Self {
        Self(vec![p.as_ref().to_string()])
    }
}

#[derive(Clone, Debug)]
enum DecodeColErrorKind {
    UnexpectedNull,
    InvalidValue { reason: String },
}

impl DecodeColumnError {
    pub(crate) fn decode_raw<S: AsRef<str>>(col: S, raw_err: super::raw::Error) -> Self {
        Self {
            path: col.into(),
            error: DecodeColErrorKind::InvalidValue {
                reason: raw_err.to_string(),
            },
        }
    }

    pub(crate) fn unexpected_null<S: AsRef<str>>(col: S) -> DecodeColumnError {
        Self {
            path: col.into(),
            error: DecodeColErrorKind::UnexpectedNull,
        }
    }

    pub(crate) fn invalid_value<S: AsRef<str>, R: AsRef<str>>(
        col: S,
        reason: R,
    ) -> DecodeColumnError {
        Self {
            path: col.into(),
            error: DecodeColErrorKind::InvalidValue {
                reason: reason.as_ref().to_string(),
            },
        }
    }

    pub(crate) fn in_column<S: AsRef<str>>(mut self, col: S) -> DecodeColumnError {
        self.path.push(col.as_ref());
        self
    }
}