vimwiki_core/lang/elements/blocks/
math.rs1use crate::StrictEq;
2use derive_more::{Constructor, Index, IndexMut, IntoIterator};
3use serde::{Deserialize, Serialize};
4use std::{borrow::Cow, iter::FromIterator};
5
6#[derive(
7    Constructor,
8    Clone,
9    Debug,
10    Eq,
11    PartialEq,
12    Hash,
13    Index,
14    IndexMut,
15    IntoIterator,
16    Serialize,
17    Deserialize,
18)]
19pub struct MathBlock<'a> {
20    #[index]
22    #[index_mut]
23    #[into_iterator(owned, ref, ref_mut)]
24    pub lines: Vec<Cow<'a, str>>,
25
26    pub environment: Option<Cow<'a, str>>,
28}
29
30impl<'a> MathBlock<'a> {
31    pub fn from_lines<I: IntoIterator<Item = L>, L: Into<Cow<'a, str>>>(
33        iter: I,
34    ) -> Self {
35        Self {
36            lines: iter.into_iter().map(Into::into).collect(),
37            environment: None,
38        }
39    }
40}
41
42impl MathBlock<'_> {
43    pub fn to_borrowed(&self) -> MathBlock {
44        use self::Cow::*;
45
46        MathBlock {
47            lines: self
48                .lines
49                .iter()
50                .map(|x| {
51                    Cow::Borrowed(match x {
52                        Borrowed(x) => *x,
53                        Owned(x) => x.as_str(),
54                    })
55                })
56                .collect(),
57            environment: self.environment.as_ref().map(|x| {
58                Cow::Borrowed(match &x {
59                    Borrowed(x) => *x,
60                    Owned(x) => x.as_str(),
61                })
62            }),
63        }
64    }
65
66    pub fn into_owned(self) -> MathBlock<'static> {
67        MathBlock {
68            lines: self
69                .lines
70                .into_iter()
71                .map(|x| Cow::from(x.into_owned()))
72                .collect(),
73            environment: self.environment.map(|x| Cow::from(x.into_owned())),
74        }
75    }
76}
77
78impl<'a> FromIterator<&'a str> for MathBlock<'a> {
79    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
82        Self::from_lines(iter)
83    }
84}
85
86impl FromIterator<String> for MathBlock<'static> {
87    fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
90        Self::from_lines(iter)
91    }
92}
93
94impl<'a> FromIterator<Cow<'a, str>> for MathBlock<'a> {
95    fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> Self {
98        Self::from_lines(iter)
99    }
100}
101
102impl<'a> StrictEq for MathBlock<'a> {
103    fn strict_eq(&self, other: &Self) -> bool {
105        self == other
106    }
107}