ifc_rs/parser/
optional.rs

1use std::fmt::Display;
2
3use winnow::{combinator::alt, Parser};
4
5use crate::parser::{IFCParse, IFCParser};
6
7use super::place_holder::{Inherited, Omitted};
8
9#[derive(Debug, Clone)]
10pub enum OptionalParameter<T: IFCParse> {
11    Omitted(Omitted),
12    Inherited(Inherited),
13    Custom(T),
14}
15
16impl<T: IFCParse> OptionalParameter<T> {
17    pub fn omitted() -> Self {
18        Self::Omitted(Omitted)
19    }
20
21    pub fn inherited() -> Self {
22        Self::Inherited(Inherited)
23    }
24
25    pub fn is_custom(&self) -> bool {
26        matches!(self, OptionalParameter::Custom(_))
27    }
28
29    pub fn custom(&self) -> Option<&T> {
30        match self {
31            OptionalParameter::Custom(t) => Some(t),
32            _ => None,
33        }
34    }
35
36    pub fn custom_mut(&mut self) -> Option<&mut T> {
37        match self {
38            OptionalParameter::Custom(t) => Some(t),
39            _ => None,
40        }
41    }
42
43    pub fn is_inherited(&self) -> bool {
44        matches!(self, OptionalParameter::Inherited(_))
45    }
46
47    pub fn is_omitted(&self) -> bool {
48        matches!(self, OptionalParameter::Omitted(_))
49    }
50}
51
52impl<T: IFCParse> From<Option<T>> for OptionalParameter<T> {
53    fn from(value: Option<T>) -> Self {
54        match value {
55            Some(t) => Self::Custom(t),
56            None => Self::omitted(),
57        }
58    }
59}
60
61impl<T: IFCParse> From<T> for OptionalParameter<T> {
62    fn from(value: T) -> Self {
63        Self::Custom(value)
64    }
65}
66
67impl<T: IFCParse> IFCParse for OptionalParameter<T> {
68    fn parse<'a>() -> impl IFCParser<'a, Self> {
69        alt((
70            Omitted::parse().map(Self::Omitted),
71            Inherited::parse().map(Self::Inherited),
72            T::parse().map(Self::Custom),
73            T::fallback(),
74        ))
75    }
76}
77
78impl<T: IFCParse> Display for OptionalParameter<T> {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        match self {
81            OptionalParameter::Omitted(p) => write!(f, "{p}"),
82            OptionalParameter::Inherited(p) => write!(f, "{p}"),
83            OptionalParameter::Custom(t) => write!(f, "{t}"),
84        }
85    }
86}