Skip to main content

c0/
validator.rs

1//! Checks a buffer against GRAMMAR.md by parsing it with the [`Parser`].
2//! [`validate`] fails on the first structural error; [`canonical`]
3//! additionally applies the canonical constraints and answers `false`
4//! instead of failing.
5
6use crate::*;
7
8/// The well-formedness and canonicality checker. Use [`validate`] and
9/// [`canonical`] unless you want the reasons a span is not canonical.
10pub struct Validator<'a> {
11    buf: &'a [u8],
12    parser: Parser<'a>,
13}
14
15/// Fail on the first structural error.
16pub fn validate(buf: &[u8]) -> Result<()> {
17    Validator::new(buf, false).run()
18}
19
20/// Well-formed and canonical: no layout, one spelling per value, keys
21/// unique within a keyed record, no framing, no comments. Supersession is
22/// content and is kept.
23pub fn canonical(buf: &[u8]) -> bool {
24    let mut v = Validator::new(buf, true);
25    v.run().is_ok() && v.ok()
26}
27
28impl<'a> Validator<'a> {
29    pub fn new(buf: &'a [u8], canonical: bool) -> Self {
30        Validator {
31            buf,
32            parser: Parser::new(buf, canonical),
33        }
34    }
35
36    /// Parse the whole buffer as a container of documents.
37    pub fn run(&mut self) -> Result<()> {
38        Container::parse(self.buf, self.buf.len(), &mut self.parser).map(|_| ())
39    }
40
41    /// Whether every canonical constraint held (meaningful after `run`).
42    pub fn ok(&self) -> bool {
43        self.parser.ok()
44    }
45
46    /// Why the span is not canonical, one entry per finding.
47    pub fn warnings(&self) -> &[&'static str] {
48        self.parser.warnings()
49    }
50}