Skip to content

Commit

Permalink
Allow Nodes returned from selection::Iter to outlive their Selection …
Browse files Browse the repository at this point in the history
…object

The Nodes should be able to live as long as their Document object, but
are having their lifetimes limited such that they can only live as long
as ther Selection object.
  • Loading branch information
mystor committed Jul 15, 2016
1 parent a58437e commit 413e17c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl<'a> Selection<'a> {
}
}

pub fn iter(&'a self) -> Iter<'a> {
pub fn iter<'sel>(&'sel self) -> Iter<'sel, 'a> {
Iter {
selection: self,
inner: self.bit_set.iter(),
Expand Down Expand Up @@ -138,22 +138,22 @@ impl<'a> Selection<'a> {
}

#[derive(Clone)]
pub struct Iter<'a> {
selection: &'a Selection<'a>,
inner: bit_set::Iter<'a, u32>,
pub struct Iter<'sel, 'doc: 'sel> {
selection: &'sel Selection<'doc>,
inner: bit_set::Iter<'sel, u32>,
}

impl<'a> Iterator for Iter<'a> {
type Item = Node<'a>;
impl<'sel, 'doc> Iterator for Iter<'sel, 'doc> {
type Item = Node<'doc>;

fn next(&mut self) -> Option<Node<'a>> {
fn next(&mut self) -> Option<Node<'doc>> {
self.inner.next().map(|index| self.selection.document.nth(index).unwrap())
}
}

impl<'a> IntoIterator for &'a Selection<'a> {
type Item = Node<'a>;
type IntoIter = Iter<'a>;
impl<'sel, 'doc> IntoIterator for &'sel Selection<'doc> {
type Item = Node<'doc>;
type IntoIter = Iter<'sel, 'doc>;

fn into_iter(self) -> Self::IntoIter {
self.iter()
Expand Down
12 changes: 12 additions & 0 deletions tests/selection_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,5 +143,17 @@ speculate! {
Name("span")
}
}

test "Iter (lifetimes)" {
let document = Document::from("<html><head></head><body>\
<article id='post-0' class='post category-foo tag-bar'></article>\
</body></html>");
let html = {
let selection = Selection::new(&document,
[0, 2, 3].iter().cloned().collect());
selection.iter().next().unwrap()
};
assert_eq!(html.name(), Some("html"));
}
}
}

0 comments on commit 413e17c

Please sign in to comment.