ctb_formats_dcdata/support/
data_constraint.rs1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29pub 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#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum NumberConstraintClause<'a> {
63 Target(&'a str),
65 LowerBound {
67 exclusive: bool,
68 bound: crate::graph_ledger::NumericBoundValue,
69 },
70 UpperBound {
72 exclusive: bool,
73 bound: crate::graph_ledger::NumericBoundValue,
74 },
75}
76
77pub 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}