| 1 | use std::cell::RefCell; |
| 2 | use std::collections::{HashMap, VecDeque}; |
| 3 | use std::sync::Arc; |
| 4 | |
| 5 | use sha2::{Digest, Sha256}; |
| 6 | |
| 7 | use crate::tui::history::OutputProjection; |
| 8 | |
| 9 | const DEFAULT_CAPACITY: usize = 256; |
| 10 | const MAX_CACHE_BYTES: usize = 4 * 1024 * 1024; |
| 11 | const MAX_POLICY_VARIANTS: usize = 4; |
| 12 | |
| 13 | #[derive(Debug)] |
| 14 | struct CacheEntry { |
| 15 | rows: Arc<OutputProjection>, |
| 16 | bytes: usize, |
| 17 | } |
| 18 | |
| 19 | #[derive(Debug)] |
| 20 | struct OutputRowsCacheInner { |
| 21 | capacity: usize, |
| 22 | bytes: usize, |
| 23 | by_key: HashMap<RowsKey, CacheEntry>, |
| 24 | insertion_order: VecDeque<RowsKey>, |
| 25 | } |
| 26 | |
| 27 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 28 | struct RowsKey { |
| 29 | content_hash: [u8; 32], |
| 30 | width: u16, |
| 31 | line_limit: usize, |
| 32 | transcript: bool, |
| 33 | } |
| 34 | |
| 35 | impl OutputRowsCacheInner { |
| 36 | fn new() -> Self { |
| 37 | Self::with_capacity(DEFAULT_CAPACITY) |
| 38 | } |
| 39 | |
| 40 | fn with_capacity(capacity: usize) -> Self { |
| 41 | let capacity = capacity.clamp(1, DEFAULT_CAPACITY); |
| 42 | Self { |
| 43 | capacity, |
| 44 | bytes: 0, |
| 45 | by_key: HashMap::with_capacity(capacity), |
| 46 | insertion_order: VecDeque::with_capacity(capacity), |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | fn container_bytes(&self) -> usize { |
| 51 | std::mem::size_of::<Self>() |
| 52 | .saturating_add( |
| 53 | self.by_key |
| 54 | .capacity() |
| 55 | .saturating_add(1) |
| 56 | .next_power_of_two() |
| 57 | .saturating_mul(std::mem::size_of::<(RowsKey, CacheEntry)>() + 1), |
| 58 | ) |
| 59 | .saturating_add(16) |
| 60 | .saturating_add( |
| 61 | self.insertion_order |
| 62 | .capacity() |
| 63 | .saturating_mul(std::mem::size_of::<RowsKey>()), |
| 64 | ) |
| 65 | } |
| 66 | |
| 67 | fn remove(&mut self, key: &RowsKey) { |
| 68 | if let Some(entry) = self.by_key.remove(key) { |
| 69 | self.bytes = self.bytes.saturating_sub(entry.bytes); |
| 70 | } |
| 71 | if let Some(index) = self |
| 72 | .insertion_order |
| 73 | .iter() |
| 74 | .position(|candidate| candidate == key) |
| 75 | { |
| 76 | self.insertion_order.remove(index); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | fn get_or_compute_rows<F>( |
| 81 | &mut self, |
| 82 | content_hash: [u8; 32], |
| 83 | width: u16, |
| 84 | line_limit: usize, |
| 85 | transcript: bool, |
| 86 | compute: F, |
| 87 | ) -> Arc<OutputProjection> |
| 88 | where |
| 89 | F: FnOnce() -> OutputProjection, |
| 90 | { |
| 91 | let key = RowsKey { |
| 92 | content_hash, |
| 93 | width, |
| 94 | line_limit, |
| 95 | transcript, |
| 96 | }; |
| 97 | if let Some(entry) = self.by_key.get(&key) { |
| 98 | let rows = Arc::clone(&entry.rows); |
| 99 | if let Some(index) = self |
| 100 | .insertion_order |
| 101 | .iter() |
| 102 | .position(|candidate| *candidate == key) |
| 103 | { |
| 104 | self.insertion_order.remove(index); |
| 105 | } |
| 106 | self.insertion_order.push_back(key); |
| 107 | return rows; |
| 108 | } |
| 109 | let rows = Arc::new(compute()); |
| 110 | let bytes = rows |
| 111 | .allocated_bytes() |
| 112 | .saturating_add(2 * std::mem::size_of::<usize>()); |
| 113 | if bytes.saturating_add(self.container_bytes()) > MAX_CACHE_BYTES { |
| 114 | return rows; |
| 115 | } |
| 116 | while self |
| 117 | .by_key |
| 118 | .keys() |
| 119 | .filter(|candidate| candidate.content_hash == content_hash && candidate.width == width) |
| 120 | .count() |
| 121 | >= MAX_POLICY_VARIANTS |
| 122 | { |
| 123 | let oldest = self |
| 124 | .insertion_order |
| 125 | .iter() |
| 126 | .find(|candidate| { |
| 127 | candidate.content_hash == content_hash && candidate.width == width |
| 128 | }) |
| 129 | .copied(); |
| 130 | if let Some(oldest) = oldest { |
| 131 | self.remove(&oldest); |
| 132 | } else { |
| 133 | break; |
| 134 | } |
| 135 | } |
| 136 | while self.by_key.len() >= self.capacity |
| 137 | || self |
| 138 | .bytes |
| 139 | .saturating_add(bytes) |
| 140 | .saturating_add(self.container_bytes()) |
| 141 | > MAX_CACHE_BYTES |
| 142 | { |
| 143 | let Some(oldest) = self.insertion_order.front().copied() else { |
| 144 | break; |
| 145 | }; |
| 146 | self.remove(&oldest); |
| 147 | } |
| 148 | self.bytes = self.bytes.saturating_add(bytes); |
| 149 | self.by_key.insert( |
| 150 | key, |
| 151 | CacheEntry { |
| 152 | rows: Arc::clone(&rows), |
| 153 | bytes, |
| 154 | }, |
| 155 | ); |
| 156 | self.insertion_order.push_back(key); |
| 157 | rows |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | thread_local! { |
| 162 | static GLOBAL_CACHE: RefCell<OutputRowsCacheInner> = |
| 163 | RefCell::new(OutputRowsCacheInner::new()); |
| 164 | } |
| 165 | |
| 166 | #[cfg(test)] |
| 167 | pub fn reset_for_tests() { |
| 168 | GLOBAL_CACHE.with(|c| *c.borrow_mut() = OutputRowsCacheInner::new()); |
| 169 | } |
| 170 | |
| 171 | #[cfg(test)] |
| 172 | pub fn get_or_compute_rows<F>(output: &str, width: u16, compute: F) -> Arc<OutputProjection> |
| 173 | where |
| 174 | F: FnOnce() -> OutputProjection, |
| 175 | { |
| 176 | get_or_compute_rows_with_hash(hash_output(output), width, 20, false, compute) |
| 177 | } |
| 178 | |
| 179 | pub fn get_or_compute_rows_with_hash<F>( |
| 180 | content_hash: [u8; 32], |
| 181 | width: u16, |
| 182 | line_limit: usize, |
| 183 | transcript: bool, |
| 184 | compute: F, |
| 185 | ) -> Arc<OutputProjection> |
| 186 | where |
| 187 | F: FnOnce() -> OutputProjection, |
| 188 | { |
| 189 | GLOBAL_CACHE.with(|c| { |
| 190 | c.borrow_mut() |
| 191 | .get_or_compute_rows(content_hash, width, line_limit, transcript, compute) |
| 192 | }) |
| 193 | } |
| 194 | |
| 195 | pub fn hash_output(output: &str) -> [u8; 32] { |
| 196 | Sha256::digest(output.as_bytes()).into() |
| 197 | } |
| 198 | |
| 199 | pub fn hash_str(s: &str) -> u64 { |
| 200 | const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; |
| 201 | const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; |
| 202 | |
| 203 | let mut hash = FNV_OFFSET_BASIS; |
| 204 | for byte in s.as_bytes() { |
| 205 | hash ^= u64::from(*byte); |
| 206 | hash = hash.wrapping_mul(FNV_PRIME); |
| 207 | } |
| 208 | hash ^= s.len() as u64; |
| 209 | hash.wrapping_mul(FNV_PRIME) |
| 210 | } |
| 211 | #[cfg(test)] |
| 212 | mod tests { |
| 213 | use super::*; |
| 214 | use crate::tui::history::OutputRow; |
| 215 | |
| 216 | fn row(text: &str) -> OutputRow { |
| 217 | OutputRow { |
| 218 | text: text.to_string(), |
| 219 | intact: false, |
| 220 | styled: None, |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | #[test] |
| 225 | fn cache_hit_returns_cached_rows() { |
| 226 | reset_for_tests(); |
| 227 | |
| 228 | let calls = std::cell::Cell::new(0u32); |
| 229 | let compute = || { |
| 230 | calls.set(calls.get() + 1); |
| 231 | OutputProjection { |
| 232 | rows: vec![row("hello"), row("world")], |
| 233 | ..Default::default() |
| 234 | } |
| 235 | }; |
| 236 | |
| 237 | let a = get_or_compute_rows("payload", 80, compute); |
| 238 | let b = get_or_compute_rows("payload", 80, || { |
| 239 | calls.set(calls.get() + 1); |
| 240 | OutputProjection { |
| 241 | rows: vec![row("hello"), row("world")], |
| 242 | ..Default::default() |
| 243 | } |
| 244 | }); |
| 245 | assert_eq!(calls.get(), 1, "second call should hit the cache"); |
| 246 | assert_eq!(a, b); |
| 247 | } |
| 248 | |
| 249 | #[test] |
| 250 | fn different_width_invalidates_rows() { |
| 251 | reset_for_tests(); |
| 252 | |
| 253 | let calls = std::cell::Cell::new(0u32); |
| 254 | let make = || { |
| 255 | calls.set(calls.get() + 1); |
| 256 | OutputProjection { |
| 257 | rows: vec![row("hello")], |
| 258 | ..Default::default() |
| 259 | } |
| 260 | }; |
| 261 | |
| 262 | let _ = get_or_compute_rows("payload", 80, make); |
| 263 | let _ = get_or_compute_rows("payload", 120, make); |
| 264 | assert_eq!(calls.get(), 2, "different width must miss the cache"); |
| 265 | } |
| 266 | |
| 267 | #[test] |
| 268 | fn different_output_invalidates_rows() { |
| 269 | reset_for_tests(); |
| 270 | |
| 271 | let calls = std::cell::Cell::new(0u32); |
| 272 | let make = || { |
| 273 | calls.set(calls.get() + 1); |
| 274 | OutputProjection { |
| 275 | rows: vec![row("x")], |
| 276 | ..Default::default() |
| 277 | } |
| 278 | }; |
| 279 | |
| 280 | let _ = get_or_compute_rows("payload-a", 80, make); |
| 281 | let _ = get_or_compute_rows("payload-b", 80, make); |
| 282 | assert_eq!(calls.get(), 2); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn projections_cached_per_policy_and_line_limit() { |
| 287 | reset_for_tests(); |
| 288 | let content_hash = hash_output("payload"); |
| 289 | let mut calls = 0; |
| 290 | let first = get_or_compute_rows_with_hash(content_hash, 80, 2, false, || { |
| 291 | calls += 1; |
| 292 | OutputProjection { |
| 293 | rows: vec![row("a"), row("e")], |
| 294 | ..Default::default() |
| 295 | } |
| 296 | }); |
| 297 | let repeated = get_or_compute_rows_with_hash(content_hash, 80, 2, false, || { |
| 298 | calls += 1; |
| 299 | OutputProjection::default() |
| 300 | }); |
| 301 | assert_eq!(calls, 1); |
| 302 | assert!(Arc::ptr_eq(&first, &repeated)); |
| 303 | let _ = get_or_compute_rows_with_hash(content_hash, 80, 3, false, || { |
| 304 | calls += 1; |
| 305 | OutputProjection::default() |
| 306 | }); |
| 307 | let _ = get_or_compute_rows_with_hash(content_hash, 80, 3, true, || { |
| 308 | calls += 1; |
| 309 | OutputProjection::default() |
| 310 | }); |
| 311 | assert_eq!(calls, 3); |
| 312 | } |
| 313 | |
| 314 | #[test] |
| 315 | fn capacity_evicts_oldest() { |
| 316 | // Build a private cache so we can size it tightly. |
| 317 | let mut cache = OutputRowsCacheInner::with_capacity(2); |
| 318 | |
| 319 | let _ = cache.get_or_compute_rows([1; 32], 80, 20, false, || OutputProjection { |
| 320 | rows: vec![row("a")], |
| 321 | ..Default::default() |
| 322 | }); |
| 323 | let _ = cache.get_or_compute_rows([2; 32], 80, 20, false, || OutputProjection { |
| 324 | rows: vec![row("b")], |
| 325 | ..Default::default() |
| 326 | }); |
| 327 | let _ = cache.get_or_compute_rows([3; 32], 80, 20, false, || OutputProjection { |
| 328 | rows: vec![row("c")], |
| 329 | ..Default::default() |
| 330 | }); |
| 331 | // The first entry (hash 1) should have been evicted. |
| 332 | let mut compute_calls = 0; |
| 333 | let _ = cache.get_or_compute_rows([1; 32], 80, 20, false, || { |
| 334 | compute_calls += 1; |
| 335 | OutputProjection { |
| 336 | rows: vec![row("a")], |
| 337 | ..Default::default() |
| 338 | } |
| 339 | }); |
| 340 | assert_eq!(compute_calls, 1, "evicted entry must miss"); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn hash_str_stable_for_identical_input() { |
| 345 | assert_eq!(hash_str("hello"), hash_str("hello")); |
| 346 | assert_ne!(hash_str("hello"), hash_str("world")); |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn hash_str_differs_on_length_suffix() { |
| 351 | // A trailing newline is a different content; the hash must differ. |
| 352 | assert_ne!(hash_str("hello"), hash_str("hello\n")); |
| 353 | } |
| 354 | |
| 355 | #[test] |
| 356 | fn hash_str_handles_empty() { |
| 357 | // Empty string hashes to the FNV offset basis; the result just |
| 358 | // needs to be stable. |
| 359 | assert_eq!(hash_str(""), hash_str("")); |
| 360 | } |
| 361 | } |
| 362 |