use std::fmt;
use std::str::FromStr;
use crate::deserialize;
use crate::error::WasmCheckError;
use crate::size::Size;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Percent(u32);
impl Percent {
#[must_use]
pub const fn from_hundredths(hundredths: u32) -> Self {
Self(hundredths)
}
#[must_use]
pub const fn hundredths(self) -> u32 {
self.0
}
#[must_use]
pub const fn of(self, baseline: u64) -> u64 {
let scaled = baseline as u128 * self.0 as u128;
let bytes = scaled / 10_000;
if bytes > u64::MAX as u128 {
u64::MAX
} else {
bytes as u64
}
}
}
impl fmt::Display for Percent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let hundredths = self.0;
let whole = hundredths / 100;
let fraction = hundredths % 100;
if fraction == 0 {
write!(f, "{whole}%")
} else if fraction.is_multiple_of(10) {
write!(f, "{whole}.{}%", fraction / 10)
} else {
write!(f, "{whole}.{fraction:02}%")
}
}
}
impl FromStr for Percent {
type Err = WasmCheckError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let invalid = || WasmCheckError::InvalidPercent(s.trim().to_string());
let number = s.trim().strip_suffix('%').unwrap_or(s.trim()).trim();
let value: f64 = number.parse().map_err(|_| invalid())?;
if !value.is_finite() || value < 0.0 {
return Err(invalid());
}
let hundredths = value * 100.0;
if hundredths > u32::MAX as f64 {
return Err(invalid());
}
Ok(Self(hundredths.round() as u32))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Threshold {
Bytes(Size),
Percent(Percent),
}
impl Threshold {
#[must_use]
pub const fn allowed(self, baseline: u64) -> u64 {
match self {
Threshold::Bytes(bytes) => baseline.saturating_add(bytes.bytes()),
Threshold::Percent(percent) => baseline.saturating_add(percent.of(baseline)),
}
}
}
impl fmt::Display for Threshold {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Threshold::Bytes(bytes) => bytes.fmt(f),
Threshold::Percent(percent) => percent.fmt(f),
}
}
}
impl FromStr for Threshold {
type Err = WasmCheckError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.trim().ends_with('%') {
s.parse().map(Threshold::Percent)
} else {
s.parse().map(Threshold::Bytes)
}
}
}
impl serde::Serialize for Threshold {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(self)
}
}
impl<'de> serde::Deserialize<'de> for Threshold {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserialize::string_or_number(
deserializer,
"a byte count or a threshold string such as \"50 KB\" or \"5%\"",
)
}
}