2018-07-09 05:29:01 -07:00
|
|
|
use std::cmp;
|
|
|
|
use std::collections::{HashSet, VecDeque};
|
|
|
|
|
|
|
|
use rand;
|
|
|
|
|
2018-10-10 07:11:27 -07:00
|
|
|
use Contribution;
|
2018-08-02 14:27:55 -07:00
|
|
|
|
2018-07-09 05:29:01 -07:00
|
|
|
/// A wrapper providing a few convenience methods for a queue of pending transactions.
|
|
|
|
#[derive(Debug)]
|
2018-08-02 14:27:55 -07:00
|
|
|
pub struct TransactionQueue<T>(pub VecDeque<T>);
|
2018-07-09 05:29:01 -07:00
|
|
|
|
2018-08-02 14:27:55 -07:00
|
|
|
impl<T: Clone> TransactionQueue<T> {
|
2018-07-09 05:29:01 -07:00
|
|
|
/// Removes the given transactions from the queue.
|
|
|
|
pub fn remove_all<'a, I>(&mut self, txs: I)
|
|
|
|
where
|
2018-08-02 14:27:55 -07:00
|
|
|
I: IntoIterator<Item = &'a T>,
|
|
|
|
T: 'a + Contribution,
|
2018-07-09 05:29:01 -07:00
|
|
|
{
|
|
|
|
let tx_set: HashSet<_> = txs.into_iter().collect();
|
|
|
|
self.0.retain(|tx| !tx_set.contains(tx));
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a new set of `amount` transactions, randomly chosen from the first `batch_size`.
|
|
|
|
/// No transactions are removed from the queue.
|
|
|
|
// TODO: Return references, once the `HoneyBadger` API accepts them. Remove `Clone` bound.
|
2018-08-02 14:27:55 -07:00
|
|
|
pub fn choose(&self, amount: usize, batch_size: usize) -> Vec<T> {
|
2018-07-09 05:29:01 -07:00
|
|
|
let mut rng = rand::thread_rng();
|
|
|
|
let limit = cmp::min(batch_size, self.0.len());
|
|
|
|
let sample = match rand::seq::sample_iter(&mut rng, self.0.iter().take(limit), amount) {
|
|
|
|
Ok(choice) => choice,
|
|
|
|
Err(choice) => choice, // Fewer than `amount` were available, which is fine.
|
|
|
|
};
|
|
|
|
sample.into_iter().cloned().collect()
|
|
|
|
}
|
|
|
|
}
|