Debian Codegraph @

src/concrete/validate.rs

raw symbols SCIP
1 use crate::Message;
2 use bstr::BString;
3 use std::borrow::Cow;
4 use 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)]
10 pub 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
18 impl ValidationError {
19 /// Create a new error with `message` and `input`. The `input` is displayed with debug formatting to not hide whitespace related issues.
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
36 impl 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
47 impl std::error::Error for ValidationError {}
48
49 impl From<Message> for ValidationError {
50 fn from(Message(msg): Message) -> Self {
51 ValidationError::new(msg)
52 }
53 }
54
55 impl From<String> for ValidationError {
56 fn from(msg: String) -> Self {
57 ValidationError::new(msg)
58 }
59 }
60
61 impl From<&'static str> for ValidationError {
62 fn from(msg: &'static str) -> Self {
63 ValidationError::new(msg)
64 }
65 }