1use std::collections::BTreeMap;
4use std::io::BufReader;
5use std::path::Path;
6use tickwise::format::{Chunk, FormatError, RecReader, SnapshotPolicy, kind};
7
8pub struct Report {
10 pub text: String,
12 pub corrupt: bool,
14}
15
16pub fn render<P: AsRef<Path>>(path: P) -> Result<Report, FormatError> {
18 let path = path.as_ref();
19 let file_size = std::fs::metadata(path)?.len();
20 let file = std::fs::File::open(path)?;
21 let mut reader = RecReader::open(BufReader::new(file))?;
22
23 let header = reader.header().clone();
24 let version = reader.version();
25 let tick_count = reader.tick_count();
26
27 let mut input_frames: u64 = 0;
28 let mut light_batches: u64 = 0;
29 let mut light_hashes: u64 = 0;
30 let mut full_hashes: u64 = 0;
31 let mut snapshot_ticks: Vec<u64> = Vec::new();
32 let mut markers: u64 = 0;
33 let mut unknown_chunks: u64 = 0;
34 let mut stream_error: Option<FormatError> = None;
35
36 for item in reader.chunks()? {
37 match item {
38 Ok(Chunk::InputFrame { .. }) => input_frames += 1,
39 Ok(Chunk::LightHashBatch { hashes, .. }) => {
40 light_batches += 1;
41 light_hashes += hashes.len() as u64;
42 }
43 Ok(Chunk::FullHash { .. }) => full_hashes += 1,
44 Ok(Chunk::Snapshot { tick, .. }) => snapshot_ticks.push(tick),
45 Ok(Chunk::Marker { .. }) => markers += 1,
46 Ok(Chunk::Unknown { .. }) => unknown_chunks += 1,
47 Err(err) => {
48 stream_error = Some(err);
49 break;
50 }
51 }
52 }
53
54 let mut bytes_by_kind: BTreeMap<u16, u64> = BTreeMap::new();
57 let mut index_error: Option<FormatError> = None;
58 match reader.read_index() {
59 Ok(entries) => {
60 for entry in entries {
61 *bytes_by_kind.entry(entry.kind).or_insert(0) += u64::from(entry.len) + 6;
62 }
63 }
64 Err(err) => index_error = Some(err),
65 }
66
67 let checksum_line = match reader.verify_checksum() {
68 Ok(()) => "checksum ok".to_string(),
69 Err(FormatError::ChecksumMismatch { stored, computed }) => {
70 format!("CHECKSUM MISMATCH, stored {stored:016x}, computed {computed:016x}")
71 }
72 Err(err) => return Err(err),
73 };
74 let corrupt =
75 checksum_line.starts_with("CHECKSUM") || stream_error.is_some() || index_error.is_some();
76
77 let meta = &header.meta;
78 let config = &header.config;
79 let mut s = String::new();
80
81 s.push_str(&format!("{}\n", path.display()));
82 s.push_str(&format!(" format version {version}\n"));
83 s.push_str(&format!(" game {}\n", or_unset(&meta.game_id)));
84 s.push_str(&format!(
85 " build {}\n",
86 or_unset(&meta.build_hash)
87 ));
88 s.push_str(&format!(" platform {}\n", or_unset(&meta.platform)));
89 s.push_str(&format!(
90 " tick rate {} ticks per second\n",
91 meta.tick_rate
92 ));
93 s.push_str(&format!(" rng seed {:#018x}\n", meta.rng_seed));
94 s.push_str(&format!(" created at unix {}\n", meta.created_at));
95 s.push_str(&match config.full_hash_interval {
96 0 => " full hashes disabled\n".to_string(),
97 n => format!(" full hashes every {n} ticks\n"),
98 });
99 s.push_str(&match config.snapshot_policy {
100 SnapshotPolicy::Off => " snapshots off\n".to_string(),
101 SnapshotPolicy::Every(n) => format!(" snapshots every {n} ticks\n"),
102 });
103 s.push_str(&format!(" hash algo id {}\n", config.hash_algo_id));
104 s.push_str(&format!(" input format id {}\n", config.input_format_id));
105 s.push('\n');
106 s.push_str(&format!(" ticks {tick_count}\n"));
107 s.push_str(&format!(" file size {}\n", human_bytes(file_size)));
108 s.push('\n');
109 s.push_str(" chunks\n");
110
111 let row = |label: &str, count: u64, bytes: Option<&u64>, note: &str| -> String {
112 let size = bytes.map_or("n/a".to_string(), |b| human_bytes(*b));
113 let mut line = format!(" {label:<22} {count:>8} {size:>10}");
114 if !note.is_empty() {
115 line.push_str(" ");
116 line.push_str(note);
117 }
118 line.push('\n');
119 line
120 };
121
122 s.push_str(&row(
123 "input frames",
124 input_frames,
125 bytes_by_kind.get(&kind::INPUT_FRAME),
126 "repeat suppressed",
127 ));
128 s.push_str(&row(
129 "light hash batches",
130 light_batches,
131 bytes_by_kind.get(&kind::LIGHT_HASH_BATCH),
132 &format!("holding {light_hashes} hashes"),
133 ));
134 s.push_str(&row(
135 "full hashes",
136 full_hashes,
137 bytes_by_kind.get(&kind::FULL_HASH),
138 "",
139 ));
140 s.push_str(&row(
141 "snapshots",
142 snapshot_ticks.len() as u64,
143 bytes_by_kind.get(&kind::SNAPSHOT),
144 &snapshot_note(&snapshot_ticks),
145 ));
146 s.push_str(&row(
147 "markers",
148 markers,
149 bytes_by_kind.get(&kind::MARKER),
150 "",
151 ));
152 if unknown_chunks > 0 {
153 let unknown_bytes: u64 = bytes_by_kind
154 .iter()
155 .filter(|(k, _)| !is_known_kind(**k))
156 .map(|(_, b)| *b)
157 .sum();
158 s.push_str(&row(
159 "unknown kinds",
160 unknown_chunks,
161 Some(&unknown_bytes),
162 "skipped safely",
163 ));
164 }
165 s.push('\n');
166
167 if let Some(err) = &stream_error {
168 s.push_str(&format!(" warning chunk stream error: {err}\n"));
169 }
170 if let Some(err) = &index_error {
171 s.push_str(&format!(" warning index unreadable: {err}\n"));
172 }
173 s.push_str(&format!(" integrity {checksum_line}\n"));
174 s.push_str(
175 " next record a second session, then find the first divergent tick\n\
176 \x20 with tickwise compare, which arrives with M2\n",
177 );
178
179 Ok(Report { text: s, corrupt })
180}
181
182fn is_known_kind(id: u16) -> bool {
183 matches!(
184 id,
185 kind::INPUT_FRAME
186 | kind::LIGHT_HASH_BATCH
187 | kind::FULL_HASH
188 | kind::SNAPSHOT
189 | kind::MARKER
190 )
191}
192
193fn or_unset(value: &str) -> &str {
194 if value.is_empty() { "unset" } else { value }
195}
196
197fn snapshot_note(ticks: &[u64]) -> String {
198 match ticks {
199 [] => String::new(),
200 few if few.len() <= 8 => {
201 let list: Vec<String> = few.iter().map(u64::to_string).collect();
202 format!("at ticks {}", list.join(", "))
203 }
204 many => format!(
205 "first at tick {}, last at tick {}",
206 many[0],
207 many[many.len() - 1]
208 ),
209 }
210}
211
212fn human_bytes(bytes: u64) -> String {
213 const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
214 let mut value = bytes as f64;
215 let mut unit = 0;
216 while value >= 1024.0 && unit < UNITS.len() - 1 {
217 value /= 1024.0;
218 unit += 1;
219 }
220 if unit == 0 {
221 format!("{bytes} B")
222 } else {
223 format!("{value:.1} {}", UNITS[unit])
224 }
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230
231 #[test]
232 fn human_bytes_picks_sane_units() {
233 assert_eq!(human_bytes(0), "0 B");
234 assert_eq!(human_bytes(512), "512 B");
235 assert_eq!(human_bytes(2048), "2.0 KiB");
236 assert_eq!(human_bytes(5 * 1024 * 1024), "5.0 MiB");
237 }
238
239 #[test]
240 fn snapshot_notes_stay_short() {
241 assert_eq!(snapshot_note(&[]), "");
242 assert_eq!(snapshot_note(&[0, 100]), "at ticks 0, 100");
243 let many: Vec<u64> = (0..20).map(|i| i * 100).collect();
244 assert_eq!(snapshot_note(&many), "first at tick 0, last at tick 1900");
245 }
246}