gix_error/concrete/
parse.rs

1use crate::Message;
2use bstr::BString;
3use std::borrow::Cow;
4use std::fmt::{Debug, Display, Formatter};
5
6/// An error occurred when parsing input
7#[derive(Debug)]
8pub struct ParseError {
9    /// The error message.
10    pub message: Cow<'static, str>,
11    /// The input or portion of the input that failed to parse.
12    pub input: Option<BString>,
13}
14
15/// Lifecycle
16impl ParseError {
17    /// Create a new error with `message` and `input`. Note that `input` isn't printed.
18    pub fn new_with_input(message: impl Into<Cow<'static, str>>, input: impl Into<BString>) -> Self {
19        ParseError {
20            message: message.into(),
21            input: Some(input.into()),
22        }
23    }
24
25    /// Create a new instance that displays the given `message`.
26    pub fn new(message: impl Into<Cow<'static, str>>) -> Self {
27        ParseError {
28            message: message.into(),
29            input: None,
30        }
31    }
32}
33
34impl Display for ParseError {
35    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
36        match &self.input {
37            None => f.write_str(self.message.as_ref()),
38            Some(input) => {
39                write!(f, "{}: {input}", self.message)
40            }
41        }
42    }
43}
44
45impl std::error::Error for ParseError {}
46
47impl From<Message> for ParseError {
48    fn from(Message(msg): Message) -> Self {
49        ParseError::new(msg)
50    }
51}
52
53impl From<String> for ParseError {
54    fn from(msg: String) -> Self {
55        ParseError::new(msg)
56    }
57}
58
59impl From<&'static str> for ParseError {
60    fn from(msg: &'static str) -> Self {
61        ParseError::new(msg)
62    }
63}