use core::ops::Range;
use crate::{Document, Entry, Item, ItemKind};
#[derive(Debug, Clone, Copy)]
pub struct Group<'doc> {
document: &'doc Document<'doc>,
start: usize,
end: usize,
}
impl<'doc> Group<'doc> {
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub fn items(self) -> impl DoubleEndedIterator<Item = Item<'doc>> + ExactSizeIterator + 'doc {
(self.start..self.end).map(move |index| {
self.document
.item(index)
.expect("group item belongs to document")
})
}
pub fn entries(self) -> impl Iterator<Item = Entry<'doc>> + 'doc {
self.items().filter_map(Item::entry)
}
pub fn comments(self) -> impl Iterator<Item = Item<'doc>> + 'doc {
self.items().filter(|item| item.kind() == ItemKind::Comment)
}
pub fn leading_comments(self) -> impl Iterator<Item = Item<'doc>> + 'doc {
self.items()
.take_while(|item| item.kind() == ItemKind::Comment)
}
#[must_use]
pub fn span(self) -> Range<usize> {
let start = self
.document
.item(self.start)
.expect("nonempty group")
.span()
.start;
let end = self
.document
.item(self.end - 1)
.expect("nonempty group")
.span()
.end;
start..end
}
}
#[derive(Debug, Clone)]
pub struct Groups<'doc> {
document: &'doc Document<'doc>,
next: usize,
}
impl<'doc> Iterator for Groups<'doc> {
type Item = Group<'doc>;
fn next(&mut self) -> Option<Self::Item> {
while self.next < self.document.items().len()
&& self
.document
.item(self.next)
.expect("group cursor belongs to document")
.kind()
== ItemKind::Blank
{
self.next += 1;
}
if self.next >= self.document.items().len() {
return None;
}
let start = self.next;
while self.next < self.document.items().len()
&& self
.document
.item(self.next)
.expect("group cursor belongs to document")
.kind()
!= ItemKind::Blank
{
self.next += 1;
}
Some(Group {
document: self.document,
start,
end: self.next,
})
}
}
impl Document<'_> {
#[must_use]
pub fn groups(&self) -> Groups<'_> {
Groups {
document: self,
next: 0,
}
}
#[must_use]
pub fn header(&self) -> Option<Group<'_>> {
let end = self
.items()
.position(|item| item.kind() == ItemKind::Entry)
.unwrap_or(self.items().len());
(end != 0).then_some(Group {
document: self,
start: 0,
end,
})
}
}
impl<'doc> Entry<'doc> {
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub fn leading_comments(
self,
) -> impl DoubleEndedIterator<Item = Item<'doc>> + ExactSizeIterator + 'doc {
let end = self.item_id();
let mut start = end;
while start != 0 {
let Some(previous) = self.document.item(start - 1) else {
break;
};
if previous.kind() != ItemKind::Comment {
break;
}
start -= 1;
}
(start..end).map(move |index| {
self.document
.item(index)
.expect("leading comment belongs to document")
})
}
}