entrenar/efficiency/platform/
budget.rs1use serde::{Deserialize, Serialize};
4
5const MOBILE_MAX_STARTUP_MS: u64 = 200;
7const DEFAULT_MAX_STARTUP_MS: u64 = 500;
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub struct WasmBudget {
13 pub max_binary_size: u64,
15 pub max_startup_ms: u64,
17 pub max_memory_bytes: u64,
19}
20
21impl WasmBudget {
22 pub fn new(max_binary_size: u64, max_startup_ms: u64, max_memory_bytes: u64) -> Self {
24 Self { max_binary_size, max_startup_ms, max_memory_bytes }
25 }
26
27 pub fn mobile() -> Self {
29 Self {
30 max_binary_size: 2 * 1024 * 1024, max_startup_ms: MOBILE_MAX_STARTUP_MS,
32 max_memory_bytes: 128 * 1024 * 1024, }
34 }
35
36 pub fn desktop() -> Self {
38 Self {
39 max_binary_size: 10 * 1024 * 1024, max_startup_ms: 1000, max_memory_bytes: 512 * 1024 * 1024, }
43 }
44
45 pub fn embedded() -> Self {
47 Self {
48 max_binary_size: 1024 * 1024, max_startup_ms: 100, max_memory_bytes: 64 * 1024 * 1024, }
52 }
53
54 pub fn sizes_mb(&self) -> (f64, f64) {
56 (
57 self.max_binary_size as f64 / (1024.0 * 1024.0),
58 self.max_memory_bytes as f64 / (1024.0 * 1024.0),
59 )
60 }
61}
62
63impl Default for WasmBudget {
64 fn default() -> Self {
65 Self {
66 max_binary_size: 5 * 1024 * 1024, max_startup_ms: DEFAULT_MAX_STARTUP_MS,
68 max_memory_bytes: 256 * 1024 * 1024, }
70 }
71}
72
73#[derive(Debug, Clone, PartialEq)]
75pub enum BudgetViolation {
76 BinarySize { actual: u64, limit: u64 },
78 StartupLatency { actual: u64, limit: u64 },
80 MemoryFootprint { actual: u64, limit: u64 },
82}
83
84impl std::fmt::Display for BudgetViolation {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 match self {
87 Self::BinarySize { actual, limit } => {
88 write!(
89 f,
90 "Binary size {} MB exceeds {} MB limit",
91 *actual as f64 / (1024.0 * 1024.0),
92 *limit as f64 / (1024.0 * 1024.0)
93 )
94 }
95 Self::StartupLatency { actual, limit } => {
96 write!(f, "Startup latency {actual} ms exceeds {limit} ms limit")
97 }
98 Self::MemoryFootprint { actual, limit } => {
99 write!(
100 f,
101 "Memory footprint {} MB exceeds {} MB limit",
102 *actual as f64 / (1024.0 * 1024.0),
103 *limit as f64 / (1024.0 * 1024.0)
104 )
105 }
106 }
107 }
108}