1use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::Mutex;
9use std::sync::atomic::{AtomicBool, Ordering};
10
11pub const MAX_TEXT_BYTES: usize = 256 * 1024;
13pub const MAX_FILES: usize = 32;
15
16#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct CellWrite {
19 pub path: PathBuf,
20 pub created: bool,
22 pub texts: Option<(String, String)>,
24}
25
26#[derive(Default)]
28pub struct CellWrites {
29 enabled: AtomicBool,
30 lanes: Mutex<HashMap<String, Vec<CellWrite>>>,
31}
32
33fn small_text(path: &Path) -> Result<Option<String>, ()> {
34 match std::fs::metadata(path) {
35 Err(_) => Ok(None),
36 Ok(meta) if !meta.is_file() || meta.len() as usize > MAX_TEXT_BYTES => Err(()),
37 Ok(_) => std::fs::read(path)
38 .ok()
39 .and_then(|bytes| String::from_utf8(bytes).ok())
40 .map(Some)
41 .ok_or(()),
42 }
43}
44
45impl CellWrites {
46 fn lanes(&self) -> std::sync::MutexGuard<'_, HashMap<String, Vec<CellWrite>>> {
47 self.lanes.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
48 }
49
50 pub fn set_enabled(&self, enabled: bool) {
51 self.enabled.store(enabled, Ordering::SeqCst);
52 }
53
54 pub fn begin(&self, lane: &str) {
56 self.lanes().remove(lane);
57 }
58
59 pub fn record(&self, lane: &str, path: &Path, content: &str) {
62 if !self.enabled.load(Ordering::SeqCst) {
63 return;
64 }
65 let mut lanes = self.lanes();
66 let writes = lanes.entry(lane.to_string()).or_default();
67 if let Some(write) = writes.iter_mut().find(|w| w.path == path) {
68 write.texts = match write.texts.take() {
69 Some((before, _)) if content.len() <= MAX_TEXT_BYTES => Some((before, content.to_string())),
70 _ => None,
71 };
72 return;
73 }
74 if writes.len() >= MAX_FILES {
75 return;
76 }
77 let before = small_text(path);
78 let created = matches!(before, Ok(None));
79 let texts = match before {
80 Ok(before) if content.len() <= MAX_TEXT_BYTES => Some((before.unwrap_or_default(), content.to_string())),
81 _ => None,
82 };
83 writes.push(CellWrite {
84 path: path.to_path_buf(),
85 created,
86 texts,
87 });
88 }
89
90 pub fn take(&self, lane: &str) -> Vec<CellWrite> {
93 let writes = self.lanes().remove(lane).unwrap_or_default();
94 writes
95 .into_iter()
96 .filter(|write| match &write.texts {
97 Some((before, after)) => {
98 (write.created || before != after)
99 && std::fs::read(&write.path).is_ok_and(|now| now == after.as_bytes())
100 }
101 None => write.path.exists(),
102 })
103 .collect()
104 }
105}