use super::*;
pub struct Children {
model: Model,
index: usize,
}
impl Children {
pub fn new(model: Model) -> Self {
Self { model, index: 0 }
}
}
impl Iterator for Children {
type Item = Model;
fn next(&mut self) -> Option<Self::Item> {
let model = self.model.borrow();
let child = model.children.get(self.index);
self.index += 1;
child.cloned()
}
}
pub struct Descendants {
stack: Models,
}
impl Descendants {
pub fn new(root: Model) -> Self {
Self {
stack: root
.borrow()
.children
.iter()
.rev()
.cloned()
.collect::<Vec<_>>()
.into(),
}
}
}
impl Iterator for Descendants {
type Item = Model;
fn next(&mut self) -> Option<Self::Item> {
if let Some(model) = self.stack.pop() {
let children = model.borrow().children.clone();
for child in children.iter().rev() {
self.stack.push(child.clone());
}
Some(model)
} else {
None
}
}
}
pub struct MultiplicityDescendants {
stack: Models,
}
impl MultiplicityDescendants {
pub fn new(root: Model) -> Self {
Self {
stack: root
.borrow()
.children
.iter()
.rev()
.cloned()
.collect::<Vec<_>>()
.into(),
}
}
}
impl Iterator for MultiplicityDescendants {
type Item = Model;
fn next(&mut self) -> Option<Self::Item> {
while let Some(ref model) = self.stack.pop() {
let model_ = model.borrow();
if matches!(model_.element(), Element::Multiplicity) {
self.stack.extend(model_.children.iter().rev().cloned());
continue;
}
return Some(model.clone());
}
None
}
}
pub struct Parents {
model: Option<Model>,
}
impl Parents {
pub fn new(model: Model) -> Self {
Self { model: Some(model) }
}
}
impl Iterator for Parents {
type Item = Model;
fn next(&mut self) -> Option<Self::Item> {
match &self.model {
Some(model) => {
let parent = model.borrow().parent.clone();
self.model = parent;
self.model.clone()
}
None => None,
}
}
}
pub struct Ancestors {
model: Option<Model>,
}
impl Ancestors {
pub fn new(model: Model) -> Self {
Self { model: Some(model) }
}
}
impl Iterator for Ancestors {
type Item = Model;
fn next(&mut self) -> Option<Self::Item> {
let model = match &self.model {
Some(model) => model.clone(),
None => return None,
};
self.model = model.borrow().parent.clone();
Some(model.clone())
}
}
pub struct SourceFileDescendants {
stack: Models,
source_hash: u64,
}
impl SourceFileDescendants {
pub fn new(root: Model) -> Self {
let source_hash = root.source_hash();
Self {
stack: root
.borrow()
.children
.filter_by_source_hash(source_hash)
.iter()
.rev()
.cloned()
.collect(),
source_hash,
}
}
}
impl Iterator for SourceFileDescendants {
type Item = Model;
fn next(&mut self) -> Option<Self::Item> {
if let Some(model) = self.stack.pop() {
let children = model
.borrow()
.children
.filter_by_source_hash(self.source_hash);
for child in children.iter().rev() {
self.stack.push(child.clone());
}
Some(model)
} else {
None
}
}
}