use thiserror::Error;
pub const MAX_BATCH: usize = 4096;
pub const DEFAULT_BATCH: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BatchSize(usize);
impl BatchSize {
pub const DEFAULT: Self = Self(DEFAULT_BATCH);
pub const fn new(n: usize) -> Result<Self, BatchSizeError> {
if n == 0 || n > MAX_BATCH {
return Err(BatchSizeError {
requested: n,
max: MAX_BATCH,
});
}
Ok(Self(n))
}
#[must_use]
pub const fn get(self) -> usize {
self.0
}
}
impl Default for BatchSize {
fn default() -> Self {
Self::DEFAULT
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error("batch size must be in 1..={max}, got {requested}")]
pub struct BatchSizeError {
pub requested: usize,
pub max: usize,
}
#[cfg(test)]
#[allow(clippy::unwrap_used, reason = "test code")]
#[allow(clippy::expect_used, reason = "test code")]
mod tests {
use super::{BatchSize, BatchSizeError, DEFAULT_BATCH, MAX_BATCH};
#[test]
fn rejects_zero() {
let err = BatchSize::new(0).unwrap_err();
assert_eq!(
err,
BatchSizeError {
requested: 0,
max: MAX_BATCH
}
);
}
#[test]
fn rejects_above_max() {
let err = BatchSize::new(MAX_BATCH + 1).unwrap_err();
assert_eq!(err.requested, MAX_BATCH + 1);
assert_eq!(err.max, MAX_BATCH);
}
#[test]
fn accepts_lower_and_upper_bound() {
assert_eq!(BatchSize::new(1).expect("1 is valid").get(), 1);
assert_eq!(
BatchSize::new(MAX_BATCH).expect("MAX is valid").get(),
MAX_BATCH
);
}
#[test]
fn default_is_default_batch() {
assert_eq!(BatchSize::DEFAULT.get(), DEFAULT_BATCH);
assert_eq!(BatchSize::default().get(), DEFAULT_BATCH);
}
}