termimad/parse/
parse_line_style.rs

1use {
2    super::*,
3    crate::LineStyle,
4};
5
6/// Read a line_style from a string.
7pub fn parse_line_style(s: &str) -> Result<LineStyle, ParseStyleTokenError> {
8    let tokens = parse_style_tokens(s)?;
9    Ok(tokens.as_slice().into())
10}
11
12impl From<&[StyleToken]> for LineStyle {
13    fn from(tokens: &[StyleToken]) -> Self {
14        let compound_style = tokens.into();
15        let mut left_margin = None;
16        let mut right_margin = None;
17        let mut align = Default::default();
18        for token in tokens {
19            match token {
20                StyleToken::Align(a) => {
21                    align = *a;
22                }
23                StyleToken::Dimension(number) => {
24                    if left_margin.is_some() {
25                        right_margin = Some(*number);
26                    } else {
27                        left_margin = Some(*number);
28                    }
29                }
30                _ => {}
31            }
32        }
33        let left_margin = left_margin.unwrap_or_default() as usize;
34        let right_margin = right_margin.unwrap_or_default() as usize;
35        LineStyle {
36            compound_style,
37            align,
38            left_margin,
39            right_margin,
40        }
41    }
42}
43
44impl PushStyleTokens for LineStyle {
45    fn push_style_tokens(&self, tokens: &mut Vec<StyleToken>) {
46        self.compound_style.push_style_tokens(tokens);
47        tokens.push(StyleToken::Align(self.align));
48        if self.left_margin > 0 || self.right_margin > 0 {
49            tokens.push(StyleToken::Dimension(self.left_margin.min(65536) as u16));
50            tokens.push(StyleToken::Dimension(self.right_margin.min(65536) as u16));
51        }
52    }
53}