Skip to main content

compose_lens/model/
cpu_rt_period.rs

1//! Raw-preserving service real-time CPU-period values.
2
3use super::lifecycle::valid_stop_grace_period;
4
5/// A service `cpu_rt_period` scalar category with exact authored spelling.
6#[derive(Debug, Clone, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum CpuRtPeriod {
9    /// A YAML numeric scalar retained without conversion or normalization.
10    YamlNumber(String),
11    /// A raw Compose duration retained without conversion or normalization.
12    Duration(String),
13    /// A dollar-bearing string retained as a deferred expression.
14    Expression(String),
15    /// A schema-valid string outside the duration policy, retained with a diagnostic.
16    Other(String),
17}
18
19impl CpuRtPeriod {
20    pub(crate) fn parse_string(value: String) -> Self {
21        if value.contains('$') {
22            Self::Expression(value)
23        } else if valid_stop_grace_period(value.trim_end_matches(['\r', '\n'])) {
24            Self::Duration(value)
25        } else {
26            Self::Other(value)
27        }
28    }
29
30    pub(crate) const fn is_valid(&self) -> bool {
31        !matches!(self, Self::Other(_))
32    }
33}
34
35#[cfg(test)]
36mod tests {
37    use super::CpuRtPeriod;
38
39    #[test]
40    fn classifies_duration_expression_and_other_spellings() {
41        for value in ["1us", "1m30s", "1.5s", ".5s"] {
42            assert!(matches!(
43                CpuRtPeriod::parse_string(value.to_owned()),
44                CpuRtPeriod::Duration(actual) if actual == value
45            ));
46        }
47        assert!(matches!(
48            CpuRtPeriod::parse_string("1m30s\n".to_owned()),
49            CpuRtPeriod::Duration(value) if value == "1m30s\n"
50        ));
51        assert!(matches!(
52            CpuRtPeriod::parse_string("${CPU_RT_PERIOD}".to_owned()),
53            CpuRtPeriod::Expression(value) if value == "${CPU_RT_PERIOD}"
54        ));
55        for value in ["", "1", "1ns", "1µs", "1μs", "1.s"] {
56            assert!(matches!(
57                CpuRtPeriod::parse_string(value.to_owned()),
58                CpuRtPeriod::Other(actual) if actual == value
59            ));
60        }
61    }
62}