knitting_parse/
error.rs

1//! The standard error types used to make understanding parse errors easier
2
3use std::error::Error;
4
5/// What type of parsing issue was it
6#[derive(Debug)]
7pub enum ParseErrorType {
8    /// Used when a range of syntax is unparsable giving the start and end locations
9    InvalidSyntaxRange(usize, usize),
10
11    /// Used when the stitch count is not right giving the found count.  Stitch counts should go up or down by even numbers from one row to the next.
12    InvalidStitchCount(usize),
13
14    /// The passed in reader has errored out
15    UnableToReadFromReader(Box<dyn Error>),
16}
17
18impl std::fmt::Display for ParseErrorType {
19    fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        match self {
21            ParseErrorType::InvalidStitchCount(count) => write!(out, "{{ \"type\" : \"Invalid stitch count\", \"count\" : {} }}", count),
22            ParseErrorType::InvalidSyntaxRange(range_start, range_end) => write!(
23                out,
24                "{{ \"type\" : \"Invalid syntax range\", \"start\" : {}, \"end\" : {} }}",
25                range_start, range_end
26            ),
27            ParseErrorType::UnableToReadFromReader(error) => write!(out, "{{ \"type\" : \"Error reading from stream\", \"underlying\" : \"{}\" }}", error),
28        }
29    }
30}
31
32/// The parse error.
33///
34/// The is the error type returned from all parsing functions.
35#[derive(Debug)]
36pub struct ParseError {
37    error_type: Box<ParseErrorType>,
38    line_number: usize,
39}
40
41impl ParseError {
42    /// Creates a new instance.
43    ///
44    /// # Arguments
45    ///
46    /// * `error_type` - What type of error it is
47    /// * `line_number` - What line did it occure on
48    pub fn new(error_type: ParseErrorType, line_number: usize) -> ParseError {
49        ParseError {
50            error_type: Box::new(error_type),
51            line_number,
52        }
53    }
54
55    /// Returns the contained error type
56    pub fn error_type(&self) -> &ParseErrorType {
57        &self.error_type
58    }
59
60    /// Returns the contained line number
61    pub fn line_number(&self) -> usize {
62        self.line_number
63    }
64}
65
66impl std::fmt::Display for ParseError {
67    fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        write!(out, "{{ \"error\":{}, \"line\":{} }}", self.error_type, self.line_number)
69    }
70}
71
72impl std::error::Error for ParseError {}