1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use crate::{MarkdownExt, Share, FrontMatter};
use std::cell::{Ref, RefCell};
enum WithinState {
External,
Internal,
}
#[derive(new)]
pub struct Within<I, P, Q, F, T>
where
I: Iterator<Item = T>,
P: FnMut(&T) -> bool,
Q: FnMut(&T) -> bool,
F: FnMut(Ref<Option<FrontMatter>>, T) -> Option<T>,
{
frontmatter: Share<RefCell<Option<FrontMatter>>>,
iter: I,
start: P,
end: Q,
f: F,
#[new(value = "WithinState::External")]
state: WithinState,
}
impl<I, P, Q, F, T> Iterator for Within<I, P, Q, F, T>
where
I: Iterator<Item = T>,
P: FnMut(&T) -> bool,
Q: FnMut(&T) -> bool,
F: FnMut(Ref<Option<FrontMatter>>, T) -> Option<T>,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
match self.state {
WithinState::External => match self.iter.next() {
Some(e) if (self.start)(&e) => {
self.state = WithinState::Internal;
Some(e)
}
node => node,
},
WithinState::Internal => match self.iter.next() {
Some(e) if (self.end)(&e) => {
self.state = WithinState::External;
Some(e)
}
Some(e) => match (self.f)(self.frontmatter.upgrade().unwrap().borrow(), e) {
node @ Some(_) => node,
None => self.next(),
},
node => node,
},
}
}
}
impl<I, P, Q, F, T> MarkdownExt<T> for Within<I, P, Q, F, T>
where
I: Iterator<Item = T>,
P: FnMut(&T) -> bool,
Q: FnMut(&T) -> bool,
F: FnMut(Ref<Option<FrontMatter>>, T) -> Option<T>,
{
fn frontmatter(&mut self) -> &mut Share<RefCell<Option<FrontMatter>>> {
&mut self.frontmatter
}
}
#[cfg(test)]
mod test {
use super::*;
use std::rc::Rc;
#[test]
fn normal() {
assert_eq!(
Within::new(
Rc::new(RefCell::new(None)).into(),
1..9,
|&n| n == 3,
|&n| n == 6,
|_, n| Some(n + 1)
).collect::<Vec<_>>(),
vec![1, 2, 3, 5, 6, 6, 7, 8]
);
}
}