mx_message/
parse_result.rs1use crate::error::ValidationError;
21use serde::{Deserialize, Serialize};
22
23#[derive(Debug, Clone, PartialEq)]
25pub enum ParseResult<T> {
26 Success(T),
28 PartialSuccess(T, Vec<ValidationError>),
30 Failure(Vec<ValidationError>),
32}
33
34impl<T> ParseResult<T> {
35 pub fn is_success(&self) -> bool {
37 matches!(self, ParseResult::Success(_))
38 }
39
40 pub fn is_failure(&self) -> bool {
42 matches!(self, ParseResult::Failure(_))
43 }
44
45 pub fn value(&self) -> Option<&T> {
47 match self {
48 ParseResult::Success(val) | ParseResult::PartialSuccess(val, _) => Some(val),
49 ParseResult::Failure(_) => None,
50 }
51 }
52
53 pub fn errors(&self) -> Vec<&ValidationError> {
55 match self {
56 ParseResult::Success(_) => vec![],
57 ParseResult::PartialSuccess(_, errors) | ParseResult::Failure(errors) => {
58 errors.iter().collect()
59 }
60 }
61 }
62
63 pub fn to_result(self) -> Result<T, Vec<ValidationError>> {
65 match self {
66 ParseResult::Success(val) => Ok(val),
67 ParseResult::PartialSuccess(val, _) => Ok(val),
68 ParseResult::Failure(errors) => Err(errors),
69 }
70 }
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct ParserConfig {
76 pub fail_fast: bool,
78 pub validate_optional_fields: bool,
80 pub collect_all_errors: bool,
82}
83
84impl Default for ParserConfig {
85 fn default() -> Self {
86 ParserConfig {
87 fail_fast: false,
88 validate_optional_fields: true,
89 collect_all_errors: true,
90 }
91 }
92}
93
94impl ParserConfig {
95 pub fn fail_fast() -> Self {
97 ParserConfig {
98 fail_fast: true,
99 validate_optional_fields: true,
100 collect_all_errors: false,
101 }
102 }
103
104 pub fn lenient() -> Self {
106 ParserConfig {
107 fail_fast: false,
108 validate_optional_fields: false,
109 collect_all_errors: false,
110 }
111 }
112}
113
114#[derive(Debug, Default)]
116pub struct ErrorCollector {
117 errors: Vec<ValidationError>,
118 has_critical_errors: bool,
119}
120
121impl ErrorCollector {
122 pub fn new() -> Self {
123 ErrorCollector {
124 errors: Vec::new(),
125 has_critical_errors: false,
126 }
127 }
128
129 pub fn add_error(&mut self, error: ValidationError) {
131 self.errors.push(error);
132 }
133
134 pub fn add_critical_error(&mut self, error: ValidationError) {
136 self.has_critical_errors = true;
137 self.errors.push(error);
138 }
139
140 pub fn has_errors(&self) -> bool {
142 !self.errors.is_empty()
143 }
144
145 pub fn has_critical_errors(&self) -> bool {
147 self.has_critical_errors
148 }
149
150 pub fn errors(self) -> Vec<ValidationError> {
152 self.errors
153 }
154
155 pub fn error_count(&self) -> usize {
157 self.errors.len()
158 }
159}