1#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11pub enum CacheInvalidationReason {
12 #[default]
13 Theme,
14 Dpr,
15 Atlas,
16 Font,
17 Image,
18 Layout,
19 DeviceLost,
20 WindowRecreate,
21 Visibility,
22}
23
24impl CacheInvalidationReason {
25 pub const ALL: [Self; 9] = [
26 Self::Theme,
27 Self::Dpr,
28 Self::Atlas,
29 Self::Font,
30 Self::Image,
31 Self::Layout,
32 Self::DeviceLost,
33 Self::WindowRecreate,
34 Self::Visibility,
35 ];
36
37 pub fn name(self) -> &'static str {
38 match self {
39 Self::Theme => "theme",
40 Self::Dpr => "dpr",
41 Self::Atlas => "atlas",
42 Self::Font => "font",
43 Self::Image => "image",
44 Self::Layout => "layout",
45 Self::DeviceLost => "device_lost",
46 Self::WindowRecreate => "window_recreate",
47 Self::Visibility => "visibility",
48 }
49 }
50}
51
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
54pub struct CacheStats {
55 pub layer_hits: u32,
57 pub layer_misses: u32,
59 pub texture_recreates: u32,
61 pub invalidations: [u32; 9],
63 pub vram_bytes: u64,
65 pub vram_high_watermark_bytes: u64,
67 pub recovery_ns: u64,
69 pub key_ns: u64,
71 pub content_skips: u32,
73}
74
75impl CacheStats {
76 pub fn invalidation(&self, reason: CacheInvalidationReason) -> u32 {
77 self.invalidations[reason as usize]
78 }
79
80 pub fn invalidation_summary(&self) -> String {
82 let parts: Vec<&'static str> =
83 CacheInvalidationReason::ALL.into_iter().filter(|r| self.invalidation(*r) > 0).map(|r| r.name()).collect();
84 if parts.is_empty() {
85 "none".to_string()
86 } else {
87 parts.join(",")
88 }
89 }
90
91 pub fn note_invalidation(&mut self, reason: CacheInvalidationReason) {
93 self.invalidations[reason as usize] = self.invalidations[reason as usize].saturating_add(1);
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn invalidation_reasons_are_stable_and_named() {
103 let names: Vec<&str> = CacheInvalidationReason::ALL.iter().map(|r| r.name()).collect();
104 assert_eq!(
105 names,
106 vec!["theme", "dpr", "atlas", "font", "image", "layout", "device_lost", "window_recreate", "visibility"]
107 );
108 assert_eq!(CacheInvalidationReason::default(), CacheInvalidationReason::Theme);
109 }
110
111 #[test]
112 fn invalidation_summary_omits_zero_reasons() {
113 let mut stats = CacheStats::default();
114 assert_eq!(stats.invalidation_summary(), "none");
115 stats.note_invalidation(CacheInvalidationReason::Atlas);
116 stats.note_invalidation(CacheInvalidationReason::Layout);
117 assert_eq!(stats.invalidation(CacheInvalidationReason::Atlas), 1);
118 assert_eq!(stats.invalidation_summary(), "atlas,layout");
119 }
120}