duration_str/
error.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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use std::fmt::{Debug, Display, Formatter};
use thiserror::Error;
use winnow::error::{ErrorKind, FromExternalError, ParserError};
use winnow::stream::Stream;

pub trait RawDebug {
    fn raw(&self) -> String;
}

impl<A> RawDebug for A
where
    A: AsRef<str>,
{
    fn raw(&self) -> String {
        self.as_ref().to_string()
    }
}

#[derive(Error, Debug, PartialEq)]
pub enum DError {
    #[error("{0}")]
    ParseError(String),
    #[error("overflow error")]
    OverflowError,
}

const PARTIAL_INPUT_MAX_LEN: usize = 11;

#[derive(Debug, PartialEq, Eq)]
pub struct PError<I> {
    partial_input: I,
    kind: ErrorKind,
    cause: String,
}

impl<I> PError<I> {
    fn new(input: I, kind: ErrorKind) -> Self {
        PError {
            partial_input: input,
            kind,
            cause: "".to_string(),
        }
    }

    pub fn append_cause<C: AsRef<str>>(mut self, cause: C) -> Self {
        self.cause = cause.as_ref().to_string();
        self
    }

    pub fn partial_input(&self) -> String
    where
        I: RawDebug,
    {
        let raw = self.partial_input.raw();
        if let Some(offset) = raw
            .char_indices()
            .enumerate()
            .find_map(|(pos, (offset, _))| (PARTIAL_INPUT_MAX_LEN <= pos).then_some(offset))
        {
            format!("{}...", raw.split_at(offset).0)
        } else {
            raw
        }
    }
}

impl<I: Stream + Clone> ParserError<I> for PError<I> {
    fn from_error_kind(input: &I, kind: ErrorKind) -> Self {
        PError::new(input.clone(), kind)
    }

    fn append(self, _: &I, _: &<I as Stream>::Checkpoint, _: ErrorKind) -> Self {
        self
    }
}

impl<I: Clone, E: std::error::Error + Send + Sync + 'static> FromExternalError<I, E> for PError<I> {
    #[inline]
    fn from_external_error(input: &I, kind: ErrorKind, e: E) -> Self {
        let mut err = Self::new(input.clone(), kind);
        {
            err.cause = e.to_string();
        }
        err
    }
}

impl<I> Display for PError<I>
where
    I: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "partial_input:{}", self.partial_input)?;
        if !self.cause.is_empty() {
            write!(f, ", {}", self.cause)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_partial_input() {
        let error = PError::new("1234567890abcde", ErrorKind::Complete);
        let partial_input = error.partial_input();
        assert_eq!(partial_input, "1234567890a...");

        let error = PError::new("你好,龙骧虎步龙行龘龘龘", ErrorKind::Complete);
        let partial_input = error.partial_input();
        assert_eq!(partial_input, "你好,龙骧虎步龙行龘龘...");

        let error = PError::new("hello,你好", ErrorKind::Complete);
        let partial_input = error.partial_input();
        assert_eq!(partial_input, "hello,你好");

        let error = PError::new("1mins", ErrorKind::Complete);
        let partial_input = error.partial_input();
        assert_eq!(partial_input, "1mins");

        let error = PError::new("MILLISECONDhah", ErrorKind::Complete);
        let partial_input = error.partial_input();
        assert_eq!(partial_input, "MILLISECOND...");

        let error = PError::new("MILLISECOND", ErrorKind::Complete);
        let partial_input = error.partial_input();
        assert_eq!(partial_input, "MILLISECOND");
    }
}