smarty_rust_sdk/sdk/
batch.rs

1use crate::sdk::MAX_BATCH_SIZE;
2
3use thiserror::Error;
4
5#[derive(Clone)]
6/// A storage for lookups.
7/// Has a maximum limit of 100 lookups
8pub struct Batch<T> {
9    lookups: Vec<T>,
10}
11
12impl<T> Default for Batch<T> {
13    fn default() -> Self {
14        Self { lookups: vec![] }
15    }
16}
17
18#[derive(Error, Debug)]
19#[error("Batch is full")]
20pub struct BatchError;
21
22impl<T> Batch<T> {
23    /// Pushes a lookup into the batch, returns an SDKError if the batch is full.
24    pub fn push(&mut self, lookup: T) -> Result<(), BatchError> {
25        if self.is_full() {
26            return Err(BatchError);
27        }
28
29        self.lookups.push(lookup);
30
31        Ok(())
32    }
33
34    /// Returns whether or not the batch is full.
35    pub fn is_full(&self) -> bool {
36        self.lookups.len() >= MAX_BATCH_SIZE
37    }
38
39    /// Returns whether or not the batch is empty.
40    pub fn is_empty(&self) -> bool {
41        self.lookups.is_empty()
42    }
43
44    /// Returns the number of lookups in the batch.
45    pub fn len(&self) -> usize {
46        self.lookups.len()
47    }
48
49    /// Returns the lookups stored in the batch
50    ///
51    /// Mostly used to get the results from the lookups
52    pub fn records(&self) -> &Vec<T> {
53        &self.lookups
54    }
55
56    /// Returns the lookups stored in the batch as a mutable reference
57    ///
58    /// Mostly used to alter lookups all at once.
59    pub fn records_mut(&mut self) -> &mut Vec<T> {
60        &mut self.lookups
61    }
62
63    /// Clears all lookups from the batch.
64    pub fn clear(&mut self) {
65        self.lookups.clear();
66    }
67}