2018-11-26 06:35:24 -08:00
|
|
|
//! An interface for a transaction queue
|
|
|
|
|
2018-10-11 06:33:03 -07:00
|
|
|
use std::collections::HashSet;
|
|
|
|
use std::{cmp, fmt};
|
2018-07-09 05:29:01 -07:00
|
|
|
|
2018-10-11 06:33:03 -07:00
|
|
|
use rand::{self, Rng};
|
2018-07-09 05:29:01 -07:00
|
|
|
|
2018-10-10 07:11:27 -07:00
|
|
|
use Contribution;
|
2018-08-02 14:27:55 -07:00
|
|
|
|
2018-10-11 06:33:03 -07:00
|
|
|
/// An interface to the transaction queue. A transaction queue is a structural part of
|
|
|
|
/// `QueueingHoneyBadger` that manages enqueueing of transactions for a future batch and dequeueing
|
|
|
|
/// of transactions to become part of a current batch.
|
|
|
|
pub trait TransactionQueue<T>: fmt::Debug + Default + Extend<T> + Sync + Send {
|
|
|
|
/// Checks whether the queue is empty.
|
|
|
|
fn is_empty(&self) -> bool;
|
|
|
|
/// 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.
|
|
|
|
fn choose<R: Rng>(&mut self, rng: &mut R, amount: usize, batch_size: usize) -> Vec<T>;
|
2018-07-09 05:29:01 -07:00
|
|
|
/// Removes the given transactions from the queue.
|
2018-10-11 06:33:03 -07:00
|
|
|
fn remove_multiple<'a, I>(&mut self, txs: I)
|
|
|
|
where
|
|
|
|
I: IntoIterator<Item = &'a T>,
|
|
|
|
T: 'a + Contribution;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> TransactionQueue<T> for Vec<T>
|
|
|
|
where
|
|
|
|
T: Clone + fmt::Debug + Sync + Send,
|
|
|
|
{
|
|
|
|
#[inline]
|
|
|
|
fn is_empty(&self) -> bool {
|
|
|
|
self.is_empty()
|
|
|
|
}
|
|
|
|
|
2018-10-11 06:44:44 -07:00
|
|
|
#[inline]
|
2018-10-11 06:33:03 -07:00
|
|
|
fn remove_multiple<'a, I>(&mut self, txs: I)
|
2018-07-09 05:29:01 -07:00
|
|
|
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();
|
2018-10-11 06:33:03 -07:00
|
|
|
self.retain(|tx| !tx_set.contains(tx));
|
2018-07-09 05:29:01 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Return references, once the `HoneyBadger` API accepts them. Remove `Clone` bound.
|
2018-10-11 06:44:44 -07:00
|
|
|
#[inline]
|
2018-10-11 06:33:03 -07:00
|
|
|
fn choose<R: Rng>(&mut self, rng: &mut R, amount: usize, batch_size: usize) -> Vec<T> {
|
|
|
|
let limit = cmp::min(batch_size, self.len());
|
|
|
|
let sample = match rand::seq::sample_iter(rng, self.iter().take(limit), amount) {
|
2018-07-09 05:29:01 -07:00
|
|
|
Ok(choice) => choice,
|
|
|
|
Err(choice) => choice, // Fewer than `amount` were available, which is fine.
|
|
|
|
};
|
|
|
|
sample.into_iter().cloned().collect()
|
|
|
|
}
|
|
|
|
}
|