Debian Codegraph @

debian/missing-sources/winnow/examples/custom_error.rs

raw
1 use winnow::error::AddContext;
2 use winnow::error::ErrMode;
3 use winnow::error::FromExternalError;
4 use winnow::error::ParserError;
5 use winnow::prelude::*;
6 use winnow::stream::Stream;
7
8 #[derive(Debug)]
9 pub enum CustomError<I> {
10 MyError,
11 Winnow(I),
12 External {
13 cause: Box<dyn std::error::Error + Send + Sync + 'static>,
14 input: I,
15 },
16 }
17
18 impl<I: Stream + Clone> ParserError<I> for CustomError<I> {
19 type Inner = Self;
20
21 fn from_input(input: &I) -> Self {
22 CustomError::Winnow(input.clone())
23 }
24
25 fn into_inner(self) -> Result<Self::Inner, Self> {
26 Ok(self)
27 }
28 }
29
30 impl<C, I: Stream> AddContext<I, C> for CustomError<I> {
31 #[inline]
32 fn add_context(
33 self,
34 _input: &I,
35 _token_start: &<I as Stream>::Checkpoint,
36 _context: C,
37 ) -> Self {
38 self
39 }
40 }
41
42 impl<I: Stream + Clone, E: std::error::Error + Send + Sync + 'static> FromExternalError<I, E>
43 for CustomError<I>
44 {
45 #[inline]
46 fn from_external_error(input: &I, e: E) -> Self {
47 CustomError::External {
48 cause: Box::new(e),
49 input: input.clone(),
50 }
51 }
52 }
53
54 pub fn parse<'s>(_input: &mut &'s str) -> ModalResult<&'s str, CustomError<&'s str>> {
55 Err(ErrMode::Backtrack(CustomError::MyError))
56 }
57
58 fn main() {}
59
60 #[cfg(test)]
61 mod tests {
62 use super::*;
63
64 #[test]
65 fn it_works() {
66 let err = parse.parse_next(&mut "").unwrap_err();
67 assert!(matches!(err, ErrMode::Backtrack(CustomError::MyError)));
68 }
69 }