arch_pkg_text/value/
dependency_specification_operator.rs

1use strum::{AsRefStr, Display, EnumString, IntoStaticStr};
2
3/// Operator at the start of a [`DependencySpecification`](super::DependencySpecification).
4#[derive(Debug, Clone, Copy, PartialEq, Eq)] // core traits
5#[derive(AsRefStr, Display, EnumString, IntoStaticStr)] // strum traits
6pub enum DependencySpecificationOperator {
7    #[strum(serialize = "<")]
8    Less = -2,
9    #[strum(serialize = "<=")]
10    LessOrEqual = -1,
11    #[strum(serialize = "=")]
12    Equal = 0,
13    #[strum(serialize = ">=")]
14    GreaterOrEqual = 1,
15    #[strum(serialize = ">")]
16    Greater = 2,
17}
18
19impl DependencySpecificationOperator {
20    /// Parse a dependency spec operator from an input string.
21    ///
22    /// ```
23    /// # use arch_pkg_text::value::DependencySpecificationOperator;
24    /// # use pretty_assertions::assert_eq;
25    /// assert_eq!(
26    ///     DependencySpecificationOperator::parse("<1.27.0-1"),
27    ///     Some((DependencySpecificationOperator::Less, "1.27.0-1")),
28    /// );
29    /// assert_eq!(
30    ///     DependencySpecificationOperator::parse("<=1.27.0-1"),
31    ///     Some((DependencySpecificationOperator::LessOrEqual, "1.27.0-1")),
32    /// );
33    /// assert_eq!(
34    ///     DependencySpecificationOperator::parse("=1.27.0-1"),
35    ///     Some((DependencySpecificationOperator::Equal, "1.27.0-1")),
36    /// );
37    /// assert_eq!(
38    ///     DependencySpecificationOperator::parse(">=1.27.0-1"),
39    ///     Some((DependencySpecificationOperator::GreaterOrEqual, "1.27.0-1")),
40    /// );
41    /// assert_eq!(
42    ///     DependencySpecificationOperator::parse(">1.27.0-1"),
43    ///     Some((DependencySpecificationOperator::Greater, "1.27.0-1")),
44    /// );
45    /// assert_eq!(DependencySpecificationOperator::parse("1.27.0-1"), None);
46    /// ```
47    pub fn parse(input: &str) -> Option<(Self, &'_ str)> {
48        use DependencySpecificationOperator::*;
49        [LessOrEqual, GreaterOrEqual, Less, Equal, Greater] // XOrEqual must place before X
50            .into_iter()
51            .find_map(|candidate| {
52                input
53                    .strip_prefix(candidate.as_ref())
54                    .map(|rest| (candidate, rest))
55            })
56    }
57}