Skip to main content

annotated/
report.rs

1use std::borrow::Cow;
2use std::mem;
3
4use crate::{Issue, Issues, Location, Problem};
5
6/// The issues found so far in one validation. Validation adds to it as it goes through a value.
7///
8/// It allocates when it records its first issue, not before, so a valid value never pays for it.
9///
10/// A report started with [`Report::failing_fast`] keeps only its first issue. Once it has that issue,
11/// it [is finished](Report::is_finished) and records nothing more.
12#[derive(Debug, Default)]
13pub struct Report {
14    issues: Vec<Issue>,
15    is_failing_fast: bool,
16}
17
18impl Report {
19    /// An empty report that keeps every issue found.
20    #[must_use]
21    pub const fn new() -> Self {
22        Self {
23            issues: Vec::new(),
24            is_failing_fast: false,
25        }
26    }
27
28    /// An empty report that keeps only the first issue found.
29    #[must_use]
30    pub const fn failing_fast() -> Self {
31        Self {
32            issues: Vec::new(),
33            is_failing_fast: true,
34        }
35    }
36
37    /// An empty report that gathers as this one does: every issue, or only the first when this report is failing
38    /// fast.
39    ///
40    /// Use it to keep the issues found in one part of a value apart, until [`append`](Report::append)
41    /// moves them into this report.
42    #[must_use]
43    pub const fn new_alike(&self) -> Self {
44        Self {
45            issues: Vec::new(),
46            is_failing_fast: self.is_failing_fast,
47        }
48    }
49
50    /// Whether validation should stop, because the report is failing fast and already has its issue. A report that
51    /// keeps every issue is never finished.
52    #[must_use]
53    pub fn is_finished(&self) -> bool {
54        self.is_failing_fast && !self.issues.is_empty()
55    }
56
57    /// Records `problem` at the location `at`, unless the report is finished.
58    pub fn push(&mut self, at: &Location<'_>, problem: Problem) {
59        if self.is_finished() {
60            return;
61        }
62        self.issues.push(Issue::new(at.to_path(), problem));
63    }
64
65    /// Records `problem` at the location `at`, with `message` in place of the problem's own message, unless the report
66    /// is finished.
67    ///
68    /// `{name}` in the message is replaced by the problem's parameter `name`. Write `{{` and `}}` for literal braces.
69    pub fn push_with_message(&mut self, at: &Location<'_>, problem: Problem, message: impl Into<Cow<'static, str>>) {
70        if self.is_finished() {
71            return;
72        }
73        self.issues
74            .push(Issue::new(at.to_path(), problem).with_message(message));
75    }
76
77    /// Moves the issues in `other` to the end of this report, keeping their order, and leaves `other` empty.
78    ///
79    /// A finished report takes none of them, and a report that is failing fast takes only the first. An empty report
80    /// takes them without copying them.
81    pub fn append(&mut self, other: &mut Report) {
82        if self.is_finished() {
83            other.issues.clear();
84            return;
85        }
86        if self.is_failing_fast {
87            other.issues.truncate(1);
88        }
89        if self.issues.is_empty() {
90            mem::swap(&mut self.issues, &mut other.issues);
91            return;
92        }
93        self.issues.append(&mut other.issues);
94    }
95
96    pub(crate) fn push_issue(&mut self, issue: Issue) {
97        if self.is_finished() {
98            return;
99        }
100        self.issues.push(issue);
101    }
102
103    /// Moves every issue after the first `kept` into a new report that gathers as this one does, and leaves the
104    /// first `kept` here.
105    pub(crate) fn take_those_after(&mut self, kept: usize) -> Report {
106        let taken = if kept == 0 {
107            mem::take(&mut self.issues)
108        } else {
109            self.issues.split_off(kept)
110        };
111        Self {
112            issues: taken,
113            is_failing_fast: self.is_failing_fast,
114        }
115    }
116
117    pub(crate) fn into_issues(self) -> Vec<Issue> {
118        self.issues
119    }
120
121    /// How many issues were found so far.
122    #[must_use]
123    pub fn len(&self) -> usize {
124        self.issues.len()
125    }
126
127    /// Whether no issue was found so far.
128    #[must_use]
129    pub fn is_empty(&self) -> bool {
130        self.issues.is_empty()
131    }
132
133    /// Turns the report into a result: `Ok(())` when no issue was found.
134    ///
135    /// # Errors
136    ///
137    /// Returns the [`Issues`] found, in the order they were found, when there is at least one.
138    pub fn into_result(self) -> Result<(), Issues> {
139        Issues::of(self.issues).map_or(Ok(()), Err)
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use crate::Path;
146
147    use super::*;
148
149    fn reserved_name() -> Problem {
150        Problem::custom("reserved_name", "is reserved")
151    }
152
153    fn passwords_differ() -> Problem {
154        Problem::custom("passwords_differ", "must match the password")
155    }
156
157    #[test]
158    fn finding_no_issue_is_no_error() {
159        let found = Report::new();
160
161        assert_eq!(found.into_result(), Ok(()));
162    }
163
164    #[test]
165    fn an_issue_is_found_at_the_path_of_its_location() {
166        let root = Location::root();
167        let members = root.field("members");
168        let mut found = Report::new();
169
170        found.push(&members.index(1).field("name"), reserved_name());
171
172        let issues = found.into_result().unwrap_err();
173        assert_eq!(
174            issues.as_slice(),
175            [Issue::new(
176                Path::root().field("members").index(1).field("name"),
177                reserved_name()
178            )]
179        );
180    }
181
182    #[test]
183    fn issues_are_answered_in_the_order_they_were_found() {
184        let root = Location::root();
185        let mut found = Report::new();
186
187        found.push(&root.field("repeatedPassword"), passwords_differ());
188        found.push(&root.field("name"), reserved_name());
189
190        let issues = found.into_result().unwrap_err();
191        assert_eq!(
192            issues.into_iter().collect::<Vec<_>>(),
193            [
194                Issue::new(Path::root().field("repeatedPassword"), passwords_differ()),
195                Issue::new(Path::root().field("name"), reserved_name()),
196            ]
197        );
198    }
199
200    #[test]
201    fn issues_are_iterated_by_reference_in_the_order_they_were_found() {
202        let root = Location::root();
203        let mut found = Report::new();
204        found.push(&root.field("repeatedPassword"), passwords_differ());
205        found.push(&root.field("name"), reserved_name());
206        let issues = found.into_result().unwrap_err();
207
208        let iterated = (&issues).into_iter().collect::<Vec<_>>();
209
210        assert_eq!(
211            iterated,
212            [
213                &Issue::new(Path::root().field("repeatedPassword"), passwords_differ()),
214                &Issue::new(Path::root().field("name"), reserved_name()),
215            ]
216        );
217    }
218
219    #[test]
220    fn an_issue_found_with_a_message_keeps_it() {
221        let root = Location::root();
222        let mut found = Report::new();
223
224        found.push_with_message(&root.field("name"), reserved_name(), "is taken");
225
226        let issues = found.into_result().unwrap_err();
227        assert_eq!(issues.to_string(), "name: is taken");
228    }
229
230    #[test]
231    fn issues_read_as_one_issue_per_line() {
232        let root = Location::root();
233        let mut found = Report::new();
234        found.push(&root.field("name"), reserved_name());
235        found.push(&root, passwords_differ());
236
237        let issues = found.into_result().unwrap_err();
238
239        assert_eq!(issues.to_string(), "name: is reserved\nmust match the password");
240    }
241
242    #[test]
243    fn a_report_failing_fast_is_finished_once_it_has_an_issue() {
244        let root = Location::root();
245        let mut found = Report::failing_fast();
246
247        found.push(&root.field("name"), reserved_name());
248
249        assert!(found.is_finished());
250    }
251
252    #[test]
253    fn a_report_failing_fast_is_not_finished_before_its_first_issue() {
254        let found = Report::failing_fast();
255
256        assert!(!found.is_finished());
257    }
258
259    #[test]
260    fn a_report_of_every_issue_is_never_finished() {
261        let root = Location::root();
262        let mut found = Report::new();
263
264        found.push(&root.field("name"), reserved_name());
265
266        assert!(!found.is_finished());
267    }
268
269    #[test]
270    fn a_finished_report_records_no_later_issue() {
271        let root = Location::root();
272        let mut found = Report::failing_fast();
273        found.push(&root.field("name"), reserved_name());
274
275        found.push(&root.field("repeatedPassword"), passwords_differ());
276        found.push_with_message(&root, passwords_differ(), "passwords must match");
277
278        let issues = found.into_result().unwrap_err();
279        assert_eq!(
280            issues.as_slice(),
281            [Issue::new(Path::root().field("name"), reserved_name())]
282        );
283    }
284
285    #[test]
286    fn a_report_started_alike_a_report_failing_fast_fails_fast() {
287        let root = Location::root();
288        let mut found = Report::failing_fast().new_alike();
289
290        found.push(&root.field("name"), reserved_name());
291
292        assert!(found.is_finished());
293    }
294
295    #[test]
296    fn a_report_started_alike_a_report_of_every_issue_keeps_every_issue() {
297        let root = Location::root();
298        let mut found = Report::new().new_alike();
299
300        found.push(&root.field("name"), reserved_name());
301        found.push(&root, passwords_differ());
302
303        assert_eq!(found.len(), 2);
304    }
305
306    #[test]
307    fn appended_issues_come_after_those_found_before_in_their_order() {
308        let root = Location::root();
309        let mut found = Report::new();
310        found.push(&root.field("name"), reserved_name());
311        let mut found_in_a_part = Report::new();
312        found_in_a_part.push(&root.field("repeatedPassword"), passwords_differ());
313        found_in_a_part.push(&root, passwords_differ());
314
315        found.append(&mut found_in_a_part);
316
317        let issues = found.into_result().unwrap_err();
318        assert_eq!(
319            issues.as_slice(),
320            [
321                Issue::new(Path::root().field("name"), reserved_name()),
322                Issue::new(Path::root().field("repeatedPassword"), passwords_differ()),
323                Issue::new(Path::root(), passwords_differ()),
324            ]
325        );
326    }
327
328    #[test]
329    fn appended_issues_are_kept_by_an_empty_report() {
330        let root = Location::root();
331        let mut found = Report::new();
332        let mut found_in_a_part = Report::new();
333        found_in_a_part.push(&root.field("name"), reserved_name());
334
335        found.append(&mut found_in_a_part);
336
337        let issues = found.into_result().unwrap_err();
338        assert_eq!(
339            issues.as_slice(),
340            [Issue::new(Path::root().field("name"), reserved_name())]
341        );
342    }
343
344    #[test]
345    fn appending_issues_leaves_the_report_they_came_from_empty() {
346        let root = Location::root();
347        let mut found = Report::new();
348        let mut found_in_a_part = Report::new();
349        found_in_a_part.push(&root.field("name"), reserved_name());
350
351        found.append(&mut found_in_a_part);
352
353        assert!(found_in_a_part.is_empty());
354    }
355
356    #[test]
357    fn a_finished_report_takes_no_appended_issue() {
358        let root = Location::root();
359        let mut found = Report::failing_fast();
360        found.push(&root.field("name"), reserved_name());
361        let mut found_in_a_part = Report::failing_fast();
362        found_in_a_part.push(&root.field("repeatedPassword"), passwords_differ());
363
364        found.append(&mut found_in_a_part);
365
366        let issues = found.into_result().unwrap_err();
367        assert_eq!(
368            issues.as_slice(),
369            [Issue::new(Path::root().field("name"), reserved_name())]
370        );
371    }
372
373    #[test]
374    fn a_report_failing_fast_takes_only_the_first_appended_issue() {
375        let root = Location::root();
376        let mut found = Report::failing_fast();
377        let mut found_in_a_part = Report::new();
378        found_in_a_part.push(&root.field("repeatedPassword"), passwords_differ());
379        found_in_a_part.push(&root, passwords_differ());
380
381        found.append(&mut found_in_a_part);
382
383        let issues = found.into_result().unwrap_err();
384        assert_eq!(
385            issues.as_slice(),
386            [Issue::new(Path::root().field("repeatedPassword"), passwords_differ())]
387        );
388    }
389
390    #[test]
391    fn a_report_counts_what_was_found_so_far() {
392        let root = Location::root();
393        let mut found = Report::new();
394
395        found.push(&root.field("name"), reserved_name());
396
397        assert_eq!((found.len(), found.is_empty()), (1, false));
398    }
399}