1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
/// A strategy to batch items.
pub trait BatchStrategy<I>: Send + Sync {
/// Adds an item to the strategy.
///
/// # Arguments
///
/// * `item` - The item to add.
fn add(&mut self, item: I);
/// Batches the items.
///
/// # Arguments
///
/// * `force` - Whether to force batching.
///
/// # Returns
///
/// The batched items.
fn batch(&mut self, force: bool) -> Option<Vec<I>>;
/// Creates a new strategy of the same type.
///
/// # Returns
///
/// The new strategy.
fn new_like(&self) -> Box<dyn BatchStrategy<I>>;
}
/// A strategy to batch items with a fixed batch size.
pub struct FixBatchStrategy<I> {
items: Vec<I>,
batch_size: usize,
}
impl<I> FixBatchStrategy<I> {
/// Creates a new strategy to batch items with a fixed batch size.
///
/// # Arguments
///
/// * `batch_size` - The batch size.
///
/// # Returns
///
/// The strategy.
pub fn new(batch_size: usize) -> Self {
FixBatchStrategy {
items: Vec::with_capacity(batch_size),
batch_size,
}
}
}
impl<I: Send + Sync + 'static> BatchStrategy<I> for FixBatchStrategy<I> {
fn add(&mut self, item: I) {
self.items.push(item);
}
fn batch(&mut self, force: bool) -> Option<Vec<I>> {
if self.items.len() < self.batch_size && !force {
return None;
}
let mut items = Vec::with_capacity(self.batch_size);
std::mem::swap(&mut items, &mut self.items);
if items.is_empty() {
return None;
}
Some(items)
}
fn new_like(&self) -> Box<dyn BatchStrategy<I>> {
Box::new(Self::new(self.batch_size))
}
}