Skip to main content

gix_error/concrete/
validate.rs

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