use serde::{Deserialize, Serialize};
use crate::metric::Metric;
use crate::size::{Size, SizeReport};
use crate::threshold::Threshold;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Limits<T> {
raw: Option<T>,
gzip: Option<T>,
brotli: Option<T>,
}
pub type Budget = Limits<Size>;
pub type MaxDelta = Limits<Threshold>;
impl<T> Limits<T> {
#[must_use]
pub const fn new() -> Self {
Self {
raw: None,
gzip: None,
brotli: None,
}
}
#[must_use]
pub const fn limit(&self, metric: Metric) -> Option<&T> {
match metric {
Metric::Raw => self.raw.as_ref(),
Metric::Gzip => self.gzip.as_ref(),
Metric::Brotli => self.brotli.as_ref(),
}
}
pub fn set_limit(&mut self, metric: Metric, limit: Option<T>) {
match metric {
Metric::Raw => self.raw = limit,
Metric::Gzip => self.gzip = limit,
Metric::Brotli => self.brotli = limit,
}
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.raw.is_none() && self.gzip.is_none() && self.brotli.is_none()
}
#[must_use]
pub fn raw_only(limit: T) -> Self {
let mut limits = Self::new();
limits.set_limit(Metric::Raw, Some(limit));
limits
}
}
impl<T> Default for Limits<T> {
fn default() -> Self {
Self::new()
}
}
impl Limits<Size> {
pub fn exceeded_metrics(&self, report: &SizeReport) -> Vec<Metric> {
Metric::ALL
.into_iter()
.filter(|metric| {
self.limit(*metric)
.is_some_and(|limit| metric.value(report) > limit.bytes())
})
.collect()
}
}
impl Limits<Threshold> {
#[must_use]
pub fn exceeded_delta(&self, report: &SizeReport, baseline: &SizeReport) -> Vec<Metric> {
Metric::ALL
.into_iter()
.filter(|metric| {
self.limit(*metric).is_some_and(|threshold| {
metric.value(report) > threshold.allowed(metric.value(baseline))
})
})
.collect()
}
#[must_use]
pub fn allowed(&self, metric: Metric, baseline: &SizeReport) -> Option<u64> {
self.limit(metric)
.map(|threshold| threshold.allowed(metric.value(baseline)))
}
}