Allow draining AddressBook entries oldest-first.

This commit is contained in:
Henry de Valence 2019-10-18 09:27:28 -07:00 committed by Deirdre Connolly
parent 39d38a8647
commit fe9cef261d
2 changed files with 24 additions and 7 deletions

View File

@ -113,8 +113,20 @@ impl AddressBook {
/// Returns an iterator that drains entries from the address book, removing /// Returns an iterator that drains entries from the address book, removing
/// them in order from most recent to least recent. /// them in order from most recent to least recent.
pub fn drain_recent<'a>(&'a mut self) -> impl Iterator<Item = MetaAddr> + 'a { pub fn drain_newest<'a>(&'a mut self) -> impl Iterator<Item = MetaAddr> + 'a {
Drain { book: self } Drain {
book: self,
newest_first: true,
}
}
/// Returns an iterator that drains entries from the address book, removing
/// them in order from most recent to least recent.
pub fn drain_oldest<'a>(&'a mut self) -> impl Iterator<Item = MetaAddr> + 'a {
Drain {
book: self,
newest_first: false,
}
} }
} }
@ -131,18 +143,23 @@ impl Extend<MetaAddr> for AddressBook {
struct Drain<'a> { struct Drain<'a> {
book: &'a mut AddressBook, book: &'a mut AddressBook,
newest_first: bool,
} }
impl<'a> Iterator for Drain<'a> { impl<'a> Iterator for Drain<'a> {
type Item = MetaAddr; type Item = MetaAddr;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
let most_recent = self.book.by_time.iter().next()?.clone(); let next_item = if self.newest_first {
self.book.by_time.remove(&most_recent); self.book.by_time.iter().next()?.clone()
} else {
self.book.by_time.iter().rev().next()?.clone()
};
self.book.by_time.remove(&next_item);
self.book self.book
.by_addr .by_addr
.remove(&most_recent.addr) .remove(&next_item.addr)
.expect("cannot have by_time entry without by_addr entry"); .expect("cannot have by_time entry without by_addr entry");
Some(most_recent) Some(next_item)
} }
} }

View File

@ -139,7 +139,7 @@ impl ConnectCmd {
); );
} }
let addrs = all_addrs.drain_recent().collect::<Vec<_>>(); let addrs = all_addrs.drain_newest().collect::<Vec<_>>();
info!(addrs.len = addrs.len(), ab.len = all_addrs.peers().count()); info!(addrs.len = addrs.len(), ab.len = all_addrs.peers().count());
let mut head = Vec::new(); let mut head = Vec::new();