Skip to main content

openakb_validate/
result.rs

1//! Diagnostic model.
2
3use std::collections::BTreeSet;
4
5use serde::Serialize;
6
7use crate::Code;
8
9/// One segment in a JSON Pointer path.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum Segment<'a> {
12    /// Object member key.
13    Key(&'a str),
14    /// Array index.
15    Index(usize),
16}
17
18/// Builds an RFC 6901 JSON Pointer from path segments.
19#[must_use]
20pub fn json_pointer<'a>(segments: impl IntoIterator<Item = Segment<'a>>) -> String {
21    let mut pointer = String::new();
22
23    for segment in segments {
24        pointer.push('/');
25        match segment {
26            Segment::Key(key) => push_escaped_key(&mut pointer, key),
27            Segment::Index(index) => pointer.push_str(&index.to_string()),
28        }
29    }
30
31    pointer
32}
33
34fn push_escaped_key(pointer: &mut String, key: &str) {
35    for character in key.chars() {
36        match character {
37            '~' => pointer.push_str("~0"),
38            '/' => pointer.push_str("~1"),
39            _ => pointer.push(character),
40        }
41    }
42}
43
44/// A validation finding with a stable diagnostic code.
45///
46/// The derived ordering is intentional: findings sort by `(code, path, message)`
47/// for deterministic diagnostics.
48#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
49pub struct Finding {
50    /// Stable diagnostic code.
51    pub code: Code,
52    /// JSON Pointer path to the affected value, or an empty string for the root.
53    pub path: String,
54    /// Human-readable diagnostic message.
55    pub message: String,
56}
57
58impl Finding {
59    /// Returns the stable name of this finding's diagnostic code.
60    #[must_use]
61    pub const fn name(&self) -> &'static str {
62        self.code.name()
63    }
64}
65
66/// A non-fatal validation advisory.
67///
68/// The derived ordering is intentional: advisories sort by `(path, message)`.
69#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
70pub struct Advisory {
71    /// JSON Pointer path to the affected value, or an empty string for the root.
72    pub path: String,
73    /// Human-readable advisory message.
74    pub message: String,
75}
76
77/// Complete validation outcome.
78#[derive(Debug, Clone, Default, Serialize)]
79pub struct ValidationResult {
80    /// Fatal validation findings.
81    pub findings: Vec<Finding>,
82    /// Non-fatal validation warnings.
83    pub warnings: Vec<Advisory>,
84}
85
86impl ValidationResult {
87    /// Returns true when validation produced no fatal findings.
88    #[must_use]
89    pub fn ok(&self) -> bool {
90        self.findings.is_empty()
91    }
92
93    /// Returns the deduplicated set of fatal diagnostic codes in this result.
94    #[must_use]
95    pub fn codes(&self) -> BTreeSet<Code> {
96        self.findings.iter().map(|finding| finding.code).collect()
97    }
98}