1use std::ops::Range;
4
5use serde::{Deserialize, Serialize};
6
7fn stable_hash(bytes: &[u8]) -> String {
10 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
11 for byte in bytes {
12 hash ^= u64::from(*byte);
13 hash = hash.wrapping_mul(0x0100_0000_01b3);
14 }
15 format!("{hash:016x}")
16}
17
18#[derive(Debug, Clone, Default, PartialEq, Eq)]
19pub struct DiffModel {
20 pub files: Vec<FileDiff>,
21}
22
23impl DiffModel {
24 pub fn fingerprint(&self) -> String {
28 let mut buf = Vec::new();
29 for file in &self.files {
30 buf.extend_from_slice(file.path.as_bytes());
31 buf.push(0);
32 buf.extend_from_slice(file.sides_hash().as_bytes());
33 buf.push(b'\n');
34 }
35 stable_hash(&buf)
36 }
37
38 pub fn find_line(&self, file: &str, line: u32, on_old_side: bool) -> Option<&DiffLine> {
41 let file = self.files.iter().find(|f| f.path == file)?;
42 file.hunks.iter().flat_map(|h| &h.lines).find(|l| {
43 let no = if on_old_side { l.old_no } else { l.new_no };
44 no == Some(line)
45 })
46 }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct FileDiff {
51 pub path: String,
52 pub old_path: Option<String>,
53 pub status: FileStatus,
54 pub binary: bool,
55 pub old_text: Option<String>,
58 pub new_text: Option<String>,
59 pub hunks: Vec<Hunk>,
60 pub hashes: HashCache,
62}
63
64#[derive(Debug, Clone, Default)]
68pub struct HashCache {
69 content: std::sync::OnceLock<String>,
70 sides: std::sync::OnceLock<String>,
71}
72
73impl PartialEq for HashCache {
74 fn eq(&self, _: &Self) -> bool {
75 true
76 }
77}
78
79impl Eq for HashCache {}
80
81impl FileDiff {
82 pub fn content_hash(&self) -> String {
84 self.hashes
85 .content
86 .get_or_init(|| stable_hash(self.new_text.as_deref().unwrap_or("").as_bytes()))
87 .clone()
88 }
89
90 pub fn diffstat(&self) -> (usize, usize) {
92 let mut added = 0;
93 let mut deleted = 0;
94 for line in self.hunks.iter().flat_map(|h| &h.lines) {
95 match line.kind {
96 LineKind::Added => added += 1,
97 LineKind::Deleted => deleted += 1,
98 LineKind::Context => {}
99 }
100 }
101 (added, deleted)
102 }
103
104 pub fn sides_hash(&self) -> String {
108 self.hashes
109 .sides
110 .get_or_init(|| {
111 let mut bytes = Vec::from(self.old_text.as_deref().unwrap_or("").as_bytes());
112 bytes.push(0);
113 bytes.extend_from_slice(self.new_text.as_deref().unwrap_or("").as_bytes());
114 stable_hash(&bytes)
115 })
116 .clone()
117 }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(rename_all = "snake_case")]
122pub enum FileStatus {
123 Added,
124 Modified,
125 Deleted,
126 Renamed,
127 Untracked,
128}
129
130impl FileStatus {
131 pub const fn glyph(self) -> char {
133 match self {
134 Self::Added => 'A',
135 Self::Modified => 'M',
136 Self::Deleted => 'D',
137 Self::Renamed => 'R',
138 Self::Untracked => '?',
139 }
140 }
141
142 pub const fn label(self) -> &'static str {
144 match self {
145 Self::Added => "new file",
146 Self::Modified => "modified",
147 Self::Deleted => "deleted",
148 Self::Renamed => "renamed",
149 Self::Untracked => "untracked",
150 }
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
157pub struct HunkId(pub String);
158
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct Hunk {
161 pub id: HunkId,
162 pub old_start: u32,
163 pub old_lines: u32,
164 pub new_start: u32,
165 pub new_lines: u32,
166 pub context: String,
170 pub lines: Vec<DiffLine>,
171}
172
173impl Hunk {
174 pub fn header(&self) -> String {
175 format!(
176 "@@ -{},{} +{},{} @@",
177 self.old_start, self.old_lines, self.new_start, self.new_lines
178 )
179 }
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184pub enum LineKind {
185 Context,
186 Deleted,
187 Added,
188}
189
190impl LineKind {
191 pub const fn origin(self) -> char {
193 match self {
194 Self::Context => ' ',
195 Self::Deleted => '-',
196 Self::Added => '+',
197 }
198 }
199}
200
201#[derive(Debug, Clone, PartialEq, Eq)]
202pub struct DiffLine {
203 pub kind: LineKind,
204 pub old_no: Option<u32>,
205 pub new_no: Option<u32>,
206 pub text: String,
208 pub emphasis: Vec<Range<usize>>,
210}
211
212impl DiffLine {
213 pub fn new(kind: LineKind, old_no: Option<u32>, new_no: Option<u32>, text: String) -> Self {
214 Self {
215 kind,
216 old_no,
217 new_no,
218 text,
219 emphasis: Vec::new(),
220 }
221 }
222}
223
224pub fn hunk_id(file_path: &str, lines: &[DiffLine]) -> HunkId {
226 let mut buf = String::new();
227 buf.push_str(file_path);
228 buf.push('\n');
229 for line in lines {
230 let tag = match line.kind {
231 LineKind::Context => ' ',
232 LineKind::Deleted => '-',
233 LineKind::Added => '+',
234 };
235 buf.push(tag);
236 buf.push_str(&line.text);
237 buf.push('\n');
238 }
239 HunkId(stable_hash(buf.as_bytes()))
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 #[test]
249 fn stable_hash_is_fnv1a64_and_never_changes() {
250 assert_eq!(stable_hash(b""), "cbf29ce484222325");
251 assert_eq!(stable_hash(b"hello"), "a430d84680aabd0b");
252 }
253
254 #[test]
255 fn file_status_glyph_and_label_cover_all_variants() {
256 assert_eq!(FileStatus::Added.glyph(), 'A');
257 assert_eq!(FileStatus::Modified.glyph(), 'M');
258 assert_eq!(FileStatus::Deleted.glyph(), 'D');
259 assert_eq!(FileStatus::Renamed.glyph(), 'R');
260 assert_eq!(FileStatus::Untracked.glyph(), '?');
261
262 assert_eq!(FileStatus::Added.label(), "new file");
263 assert_eq!(FileStatus::Modified.label(), "modified");
264 assert_eq!(FileStatus::Deleted.label(), "deleted");
265 assert_eq!(FileStatus::Renamed.label(), "renamed");
266 assert_eq!(FileStatus::Untracked.label(), "untracked");
267 }
268
269 fn line(kind: LineKind, text: &str) -> DiffLine {
270 DiffLine::new(kind, None, None, text.to_owned())
271 }
272
273 #[test]
274 fn hunk_id_is_stable() {
275 let lines = vec![line(LineKind::Deleted, "a"), line(LineKind::Added, "b")];
276 let id1 = hunk_id("src/x.rs", &lines);
277 let id2 = hunk_id("src/x.rs", &lines);
278 assert_eq!(id1, id2);
279 }
280
281 #[test]
282 fn hunk_id_changes_with_content() {
283 let a = vec![line(LineKind::Added, "x")];
284 let b = vec![line(LineKind::Added, "y")];
285 assert_ne!(hunk_id("f", &a), hunk_id("f", &b));
286 }
287
288 #[test]
289 fn hunk_id_changes_with_kind() {
290 let a = vec![line(LineKind::Added, "x")];
291 let b = vec![line(LineKind::Deleted, "x")];
292 assert_ne!(hunk_id("f", &a), hunk_id("f", &b));
293 }
294
295 #[test]
296 fn hunk_id_changes_with_file() {
297 let lines = vec![line(LineKind::Added, "x")];
298 assert_ne!(hunk_id("a", &lines), hunk_id("b", &lines));
299 }
300
301 #[test]
302 fn header_formats() {
303 let hunk = Hunk {
304 id: HunkId("h".into()),
305 old_start: 10,
306 old_lines: 7,
307 new_start: 10,
308 new_lines: 9,
309 context: String::new(),
310 lines: vec![],
311 };
312 assert_eq!(hunk.header(), "@@ -10,7 +10,9 @@");
313 }
314
315 #[test]
316 fn content_hash_changes_when_new_text_changes() {
317 let base = FileDiff {
318 path: "f.rs".into(),
319 old_path: None,
320 status: FileStatus::Modified,
321 binary: false,
322 old_text: None,
323 new_text: Some("fn main() {}".into()),
324 hunks: vec![],
325 hashes: HashCache::default(),
326 };
327 let mut changed = base.clone();
328 changed.new_text = Some("fn main() { let x = 1; }".into());
329 assert_ne!(base.content_hash(), changed.content_hash());
330 }
331
332 #[test]
333 fn content_hash_is_stable() {
334 let file = FileDiff {
335 path: "f.rs".into(),
336 old_path: None,
337 status: FileStatus::Modified,
338 binary: false,
339 old_text: None,
340 new_text: Some("same content".into()),
341 hunks: vec![],
342 hashes: HashCache::default(),
343 };
344 assert_eq!(file.content_hash(), file.content_hash());
345 }
346
347 #[test]
348 fn sides_hash_changes_when_old_text_changes() {
349 let base = FileDiff {
350 path: "f.rs".into(),
351 old_path: None,
352 status: FileStatus::Modified,
353 binary: false,
354 old_text: Some("fn main() {}".into()),
355 new_text: Some("fn main() { let x = 1; }".into()),
356 hunks: vec![],
357 hashes: HashCache::default(),
358 };
359 let mut changed = base.clone();
360 changed.old_text = Some("fn main() { unreachable!() }".into());
361 assert_eq!(
362 base.content_hash(),
363 changed.content_hash(),
364 "same new side, same content hash"
365 );
366 assert_ne!(base.sides_hash(), changed.sides_hash());
367 }
368
369 fn one_file_model(path: &str, old_text: &str, new_text: &str) -> DiffModel {
370 DiffModel {
371 files: vec![FileDiff {
372 path: path.to_owned(),
373 old_path: None,
374 status: FileStatus::Modified,
375 binary: false,
376 old_text: Some(old_text.to_owned()),
377 new_text: Some(new_text.to_owned()),
378 hunks: vec![],
379 hashes: HashCache::default(),
380 }],
381 }
382 }
383
384 #[test]
385 fn fingerprint_is_stable_for_identical_models() {
386 let a = one_file_model("f.rs", "old", "new");
387 let b = one_file_model("f.rs", "old", "new");
388 assert_eq!(a.fingerprint(), b.fingerprint());
389 }
390
391 #[test]
392 fn fingerprint_changes_with_content_path_and_file_set() {
393 let base = one_file_model("f.rs", "old", "new");
394 assert_ne!(
395 base.fingerprint(),
396 one_file_model("f.rs", "old", "newer").fingerprint(),
397 "changed side changes the fingerprint"
398 );
399 assert_ne!(
400 base.fingerprint(),
401 one_file_model("g.rs", "old", "new").fingerprint(),
402 "renamed file changes the fingerprint"
403 );
404 let mut grown = base.clone();
405 grown.files.extend(one_file_model("g.rs", "", "x").files);
406 assert_ne!(
407 base.fingerprint(),
408 grown.fingerprint(),
409 "added file changes the fingerprint"
410 );
411 }
412
413 fn model_with_lines() -> DiffModel {
414 DiffModel {
415 files: vec![FileDiff {
416 path: "f.rs".into(),
417 old_path: None,
418 status: FileStatus::Modified,
419 binary: false,
420 old_text: None,
421 new_text: None,
422 hunks: vec![Hunk {
423 id: HunkId("h".into()),
424 old_start: 1,
425 old_lines: 2,
426 new_start: 1,
427 new_lines: 2,
428 context: String::new(),
429 lines: vec![
430 DiffLine::new(LineKind::Context, Some(1), Some(1), "one".into()),
431 DiffLine::new(LineKind::Deleted, Some(2), None, "two".into()),
432 DiffLine::new(LineKind::Added, None, Some(2), "TWO".into()),
433 ],
434 }],
435 hashes: HashCache::default(),
436 }],
437 }
438 }
439
440 #[test]
441 fn diffstat_counts_added_and_deleted_over_hunks() {
442 let model = model_with_lines();
444 assert_eq!(model.files[0].diffstat(), (1, 1));
445
446 let file = FileDiff {
448 path: "f.rs".into(),
449 old_path: None,
450 status: FileStatus::Modified,
451 binary: false,
452 old_text: None,
453 new_text: None,
454 hunks: vec![
455 Hunk {
456 id: HunkId("a".into()),
457 old_start: 1,
458 old_lines: 1,
459 new_start: 1,
460 new_lines: 2,
461 context: String::new(),
462 lines: vec![
463 DiffLine::new(LineKind::Context, Some(1), Some(1), "ctx".into()),
464 DiffLine::new(LineKind::Added, None, Some(2), "add one".into()),
465 ],
466 },
467 Hunk {
468 id: HunkId("b".into()),
469 old_start: 5,
470 old_lines: 1,
471 new_start: 6,
472 new_lines: 1,
473 context: String::new(),
474 lines: vec![
475 DiffLine::new(LineKind::Deleted, Some(5), None, "gone".into()),
476 DiffLine::new(LineKind::Added, None, Some(6), "add two".into()),
477 ],
478 },
479 ],
480 hashes: HashCache::default(),
481 };
482 assert_eq!(file.diffstat(), (2, 1));
483 }
484
485 #[test]
486 fn find_line_matches_the_requested_side() {
487 let model = model_with_lines();
488 let new_side = model.find_line("f.rs", 2, false).expect("new side");
489 assert_eq!(new_side.text, "TWO");
490 let old_side = model.find_line("f.rs", 2, true).expect("old side");
491 assert_eq!(old_side.text, "two");
492 }
493
494 #[test]
495 fn find_line_misses_unknown_files_and_lines() {
496 let model = model_with_lines();
497 assert!(model.find_line("nope.rs", 1, false).is_none());
498 assert!(model.find_line("f.rs", 99, false).is_none());
499 }
500
501 #[test]
502 fn content_hash_falls_back_for_none() {
503 let file = FileDiff {
504 path: "f.rs".into(),
505 old_path: None,
506 status: FileStatus::Deleted,
507 binary: false,
508 old_text: None,
509 new_text: None,
510 hunks: vec![],
511 hashes: HashCache::default(),
512 };
513 let hash = file.content_hash();
515 assert!(!hash.is_empty());
516 }
517}