use serde::{Deserialize, Serialize};
const MOBILE_MAX_STARTUP_MS: u64 = 200;
const DEFAULT_MAX_STARTUP_MS: u64 = 500;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WasmBudget {
pub max_binary_size: u64,
pub max_startup_ms: u64,
pub max_memory_bytes: u64,
}
impl WasmBudget {
pub fn new(max_binary_size: u64, max_startup_ms: u64, max_memory_bytes: u64) -> Self {
Self { max_binary_size, max_startup_ms, max_memory_bytes }
}
pub fn mobile() -> Self {
Self {
max_binary_size: 2 * 1024 * 1024, max_startup_ms: MOBILE_MAX_STARTUP_MS,
max_memory_bytes: 128 * 1024 * 1024, }
}
pub fn desktop() -> Self {
Self {
max_binary_size: 10 * 1024 * 1024, max_startup_ms: 1000, max_memory_bytes: 512 * 1024 * 1024, }
}
pub fn embedded() -> Self {
Self {
max_binary_size: 1024 * 1024, max_startup_ms: 100, max_memory_bytes: 64 * 1024 * 1024, }
}
pub fn sizes_mb(&self) -> (f64, f64) {
(
self.max_binary_size as f64 / (1024.0 * 1024.0),
self.max_memory_bytes as f64 / (1024.0 * 1024.0),
)
}
}
impl Default for WasmBudget {
fn default() -> Self {
Self {
max_binary_size: 5 * 1024 * 1024, max_startup_ms: DEFAULT_MAX_STARTUP_MS,
max_memory_bytes: 256 * 1024 * 1024, }
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum BudgetViolation {
BinarySize { actual: u64, limit: u64 },
StartupLatency { actual: u64, limit: u64 },
MemoryFootprint { actual: u64, limit: u64 },
}
impl std::fmt::Display for BudgetViolation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BinarySize { actual, limit } => {
write!(
f,
"Binary size {} MB exceeds {} MB limit",
*actual as f64 / (1024.0 * 1024.0),
*limit as f64 / (1024.0 * 1024.0)
)
}
Self::StartupLatency { actual, limit } => {
write!(f, "Startup latency {actual} ms exceeds {limit} ms limit")
}
Self::MemoryFootprint { actual, limit } => {
write!(
f,
"Memory footprint {} MB exceeds {} MB limit",
*actual as f64 / (1024.0 * 1024.0),
*limit as f64 / (1024.0 * 1024.0)
)
}
}
}
}