vimwiki_core/lang/elements/blocks/
blockquotes.rs

1use crate::StrictEq;
2use derive_more::{Constructor, Display, Index, IndexMut, IntoIterator};
3use serde::{Deserialize, Serialize};
4use std::{borrow::Cow, iter::FromIterator};
5
6#[derive(
7    Constructor,
8    Clone,
9    Debug,
10    Display,
11    Eq,
12    PartialEq,
13    Hash,
14    Index,
15    IndexMut,
16    IntoIterator,
17    Serialize,
18    Deserialize,
19)]
20#[display(fmt = "{}", "lines.join(\"\n\")")]
21pub struct Blockquote<'a> {
22    /// Represents the lines of text contained within the blockquote include
23    /// potential blank lines
24    #[index]
25    #[index_mut]
26    #[into_iterator(owned, ref, ref_mut)]
27    pub lines: Vec<Cow<'a, str>>,
28}
29
30impl<'a> Blockquote<'a> {
31    /// Returns total line groups available
32    pub fn line_group_cnt(&self) -> usize {
33        self.line_groups().count()
34    }
35
36    /// Returns an iterator over slices of lines where each item is a slice
37    /// of lines representing a group of lines
38    pub fn line_groups(&self) -> impl Iterator<Item = &[Cow<'a, str>]> {
39        self.lines
40            .split(|line| line.is_empty())
41            .filter(|lines| !lines.is_empty())
42    }
43
44    /// Returns an iterator over mutable slices of lines where each item is a slice
45    /// of lines representing a group of lines
46    pub fn mut_line_groups(&self) -> impl Iterator<Item = &[Cow<'a, str>]> {
47        self.lines
48            .split(|line| line.is_empty())
49            .filter(|lines| !lines.is_empty())
50    }
51}
52
53impl Blockquote<'_> {
54    pub fn to_borrowed(&self) -> Blockquote {
55        use self::Cow::*;
56
57        self.lines
58            .iter()
59            .map(|x| {
60                Cow::Borrowed(match x {
61                    Borrowed(x) => *x,
62                    Owned(x) => x.as_str(),
63                })
64            })
65            .collect()
66    }
67
68    pub fn into_owned(self) -> Blockquote<'static> {
69        self.into_iter()
70            .map(|x| Cow::from(x.into_owned()))
71            .collect()
72    }
73}
74
75impl<'a> FromIterator<&'a str> for Blockquote<'a> {
76    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
77        Self {
78            lines: iter.into_iter().map(Cow::Borrowed).collect(),
79        }
80    }
81}
82
83impl FromIterator<String> for Blockquote<'static> {
84    fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
85        Self {
86            lines: iter.into_iter().map(Cow::Owned).collect(),
87        }
88    }
89}
90
91impl<'a> FromIterator<Cow<'a, str>> for Blockquote<'a> {
92    fn from_iter<I: IntoIterator<Item = Cow<'a, str>>>(iter: I) -> Self {
93        Self {
94            lines: iter.into_iter().collect(),
95        }
96    }
97}
98
99impl<'a> StrictEq for Blockquote<'a> {
100    /// Same as PartialEq
101    #[inline]
102    fn strict_eq(&self, other: &Self) -> bool {
103        self == other
104    }
105}