tl_build/parser/tl/
flag.rs

1use std::fmt;
2use std::str::FromStr;
3
4use crate::errors::ParamParseError;
5
6/// Data attached to parameters conditional on flags.
7#[derive(Debug, PartialEq, Eq, Hash)]
8pub struct Flag {
9    /// The name of the parameter containing the flags in its bits.
10    pub name: String,
11
12    /// The bit index used by this flag inside the flags parameter.
13    pub index: usize,
14}
15
16impl fmt::Display for Flag {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        write!(f, "{}.{}", self.name, self.index)
19    }
20}
21
22impl FromStr for Flag {
23    type Err = ParamParseError;
24
25    /// Parses a flag.
26    ///
27    /// # Examples
28    ///
29    /// ```
30    /// use tl_build::tl::Flag;
31    ///
32    /// assert!("flags.1".parse::<Flag>().is_ok());
33    /// ```
34    fn from_str(ty: &str) -> Result<Self, Self::Err> {
35        if let Some(dot_pos) = ty.find('.') {
36            Ok(Flag {
37                name: ty[..dot_pos].into(),
38                index: ty[dot_pos + 1..]
39                    .parse()
40                    .map_err(|_| ParamParseError::InvalidFlag)?,
41            })
42        } else {
43            Err(ParamParseError::InvalidFlag)
44        }
45    }
46}