ctb_formats_dcdata/support/
data_constraint.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Data constraint parsing shared by the Dc syntax parser and validator.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29/// Parses an optional format and decoded byte count for a data construct.
30pub fn parse_data_constraint(
31    subtype: &str,
32) -> anyhow::Result<(Option<&str>, Option<usize>)> {
33    let (format, length) = if subtype.starts_with("bytes=") {
34        (None, Some(subtype))
35    } else if let Some((format, length)) = subtype.split_once(';') {
36        (Some(format.trim()), Some(length.trim()))
37    } else {
38        (Some(subtype.trim()), None)
39    };
40    anyhow::ensure!(
41        format.is_none_or(|format| !format.is_empty()),
42        "Missing data format"
43    );
44    let bytes = if let Some(length) = length {
45        let digits = length.strip_prefix("bytes=").ok_or_else(|| {
46            anyhow::anyhow!("Expected bytes=N data constraint")
47        })?;
48        anyhow::ensure!(
49            !digits.is_empty()
50                && digits.bytes().all(|byte| byte.is_ascii_digit()),
51            "Data byte count must be a nonnegative integer"
52        );
53        Some(digits.parse::<usize>()?)
54    } else {
55        None
56    };
57    Ok((format, bytes))
58}
59
60/// A single clause in a `&`-separated `[number:...]` subtype constraint.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum NumberConstraintClause<'a> {
63    /// A format shorthand (`f<N>`), format identifier (`Natural0`), or named construct.
64    Target(&'a str),
65    /// A lower bound (`>=` when `exclusive == false`, `>` when `exclusive == true`).
66    LowerBound {
67        exclusive: bool,
68        bound: crate::graph_ledger::NumericBoundValue,
69    },
70    /// An upper bound (`<=` when `exclusive == false`, `<` when `exclusive == true`).
71    UpperBound {
72        exclusive: bool,
73        bound: crate::graph_ledger::NumericBoundValue,
74    },
75}
76
77/// Parses a `[number:...]` subtype constraint into its `&`-separated clauses.
78pub fn parse_number_constraint(
79    subtype: &str,
80) -> anyhow::Result<Vec<NumberConstraintClause<'_>>> {
81    let trimmed = subtype.trim();
82    anyhow::ensure!(
83        !trimmed.is_empty(),
84        "Empty [number:] subtype constraint"
85    );
86    let mut clauses = Vec::new();
87    for raw_part in trimmed.split('&') {
88        let part = raw_part.trim();
89        anyhow::ensure!(
90            !part.is_empty(),
91            "Empty clause in [number:{subtype}] subtype constraint"
92        );
93        if let Some(rest) = part.strip_prefix(">=") {
94            clauses.push(NumberConstraintClause::LowerBound {
95                exclusive: false,
96                bound: crate::graph_ledger::NumericBoundValue::parse_dsl_bound(
97                    rest,
98                )?,
99            });
100        } else if let Some(rest) = part.strip_prefix('>') {
101            clauses.push(NumberConstraintClause::LowerBound {
102                exclusive: true,
103                bound: crate::graph_ledger::NumericBoundValue::parse_dsl_bound(
104                    rest,
105                )?,
106            });
107        } else if let Some(rest) = part.strip_prefix("<=") {
108            clauses.push(NumberConstraintClause::UpperBound {
109                exclusive: false,
110                bound: crate::graph_ledger::NumericBoundValue::parse_dsl_bound(
111                    rest,
112                )?,
113            });
114        } else if let Some(rest) = part.strip_prefix('<') {
115            clauses.push(NumberConstraintClause::UpperBound {
116                exclusive: true,
117                bound: crate::graph_ledger::NumericBoundValue::parse_dsl_bound(
118                    rest,
119                )?,
120            });
121        } else {
122            clauses.push(NumberConstraintClause::Target(part));
123        }
124    }
125    Ok(clauses)
126}