Skip to main content

rustik_diff/
document.rs

1//! Unified diff document model.
2//!
3//! Defines the data tree (`DiffDocument` → `FileDiff` → `Hunk` → `DiffLine`)
4//! that callers consume. The decoder that produces these values lives in
5//! [`crate::decode`]; `document` is intentionally model-only.
6
7use std::fmt;
8use std::io;
9use std::num::ParseIntError;
10use std::path::PathBuf;
11use std::str::FromStr;
12
13/// Stable identifier for a file section in one diff document.
14#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
15pub struct FileId(usize);
16
17/// Stable identifier for a hunk in one diff document.
18#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
19pub struct HunkId(usize);
20
21/// Stable identifier for a rendered hunk row in one diff document.
22#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
23pub struct RowId(usize);
24
25/// Object identifier as it appears in a Git diff header.
26#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
27pub struct Oid(String);
28
29impl FileId {
30    /// Wraps a raw index as a [`FileId`].
31    pub const fn new(index: usize) -> Self {
32        Self(index)
33    }
34}
35
36impl HunkId {
37    /// Wraps a raw index as a [`HunkId`].
38    pub const fn new(index: usize) -> Self {
39        Self(index)
40    }
41}
42
43impl RowId {
44    /// Wraps a raw index as a [`RowId`].
45    pub const fn new(index: usize) -> Self {
46        Self(index)
47    }
48}
49
50impl Oid {
51    /// Returns the object identifier text.
52    pub fn as_str(&self) -> &str {
53        &self.0
54    }
55}
56
57impl FromStr for Oid {
58    type Err = OidError;
59
60    fn from_str(input: &str) -> Result<Self, Self::Err> {
61        if input.is_empty() {
62            return Err(OidError);
63        }
64        if !input.bytes().all(|byte| byte.is_ascii_hexdigit()) {
65            return Err(OidError);
66        }
67        Ok(Self(input.to_owned()))
68    }
69}
70
71impl fmt::Display for Oid {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(&self.0)
74    }
75}
76
77/// Error returned when a diff object identifier is malformed.
78#[derive(Clone, Copy, Debug, Eq, PartialEq)]
79pub struct OidError;
80
81impl fmt::Display for OidError {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        f.write_str("object id must be non-empty hexadecimal text")
84    }
85}
86
87impl std::error::Error for OidError {}
88
89impl std::ops::Deref for FileId {
90    type Target = usize;
91
92    fn deref(&self) -> &usize {
93        &self.0
94    }
95}
96
97impl std::ops::Deref for HunkId {
98    type Target = usize;
99
100    fn deref(&self) -> &usize {
101        &self.0
102    }
103}
104
105impl std::ops::Deref for RowId {
106    type Target = usize;
107
108    fn deref(&self) -> &usize {
109        &self.0
110    }
111}
112
113/// A complete unified diff document.
114#[derive(Clone, Debug, Default, Eq, PartialEq)]
115pub struct DiffDocument {
116    /// Commit preamble before the first `diff --git` section, if present.
117    pub commit: Option<crate::Commit>,
118    /// File diffs in input order.
119    pub files: Vec<FileDiff>,
120}
121
122/// A single file section in a unified diff.
123#[derive(Clone, Debug, Eq, PartialEq)]
124pub struct FileDiff {
125    /// Stable file identifier.
126    pub id: FileId,
127    /// Metadata and raw header lines for this file.
128    pub header: FileHeader,
129    /// Hunks in input order.
130    pub hunks: Vec<Hunk>,
131}
132
133/// Metadata lines that introduce a file section in a Git patch.
134#[derive(Clone, Debug, Eq, PartialEq)]
135pub struct FileHeader {
136    /// Classified kind of file change.
137    pub kind: FileKind,
138    /// Path on the old side of the diff, when present.
139    pub old_path: Option<PathBuf>,
140    /// Path on the new side of the diff, when present.
141    pub new_path: Option<PathBuf>,
142    /// File mode on the old side of the diff, when present.
143    pub old_mode: Option<FileMode>,
144    /// File mode on the new side of the diff, when present.
145    pub new_mode: Option<FileMode>,
146    /// Object id on the old side of the diff, when present.
147    pub old_oid: Option<Oid>,
148    /// Object id on the new side of the diff, when present.
149    pub new_oid: Option<Oid>,
150    /// Raw header lines preserved for callers that need exact metadata.
151    pub raw: Vec<String>,
152}
153
154/// File mode in a Git diff, parsed from the octal value Git records.
155#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
156pub enum FileMode {
157    /// Regular file (`100644`).
158    Blob,
159    /// Executable regular file (`100755`).
160    BlobExecutable,
161    /// Symbolic link (`120000`).
162    Link,
163    /// Submodule reference, i.e. a Git commit (`160000`).
164    Commit,
165    /// Directory tree (`040000`).
166    Tree,
167    /// Any other mode, preserved as the original octal value.
168    Other(u32),
169}
170
171/// Kind of file-level change described by a patch file header.
172#[derive(Clone, Copy, Debug, Eq, PartialEq)]
173pub enum FileKind {
174    /// Existing file content changed.
175    Modified,
176    /// New file was added.
177    Added,
178    /// Existing file was deleted.
179    Deleted,
180    /// Existing file was renamed.
181    Renamed,
182    /// Existing file was copied.
183    Copied,
184    /// File mode changed without a more specific content kind.
185    ModeChanged,
186    /// File contains binary patch data or a binary comparison marker.
187    Binary,
188}
189
190impl FileKind {
191    /// Returns the compact marker used by diff chrome.
192    pub const fn marker(self) -> char {
193        match self {
194            Self::Added => '⊕',
195            Self::Deleted => '⊖',
196            Self::Renamed => '↦',
197            Self::Copied => '⇉',
198            Self::Modified | Self::ModeChanged | Self::Binary => '⊙',
199        }
200    }
201}
202
203/// Aggregate statistics for one [`FileDiff`].
204#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
205pub struct FileStats {
206    /// Total addition lines across all hunks in the file.
207    pub additions: usize,
208    /// Total deletion lines across all hunks in the file.
209    pub deletions: usize,
210}
211
212/// Aggregate statistics for one [`DiffDocument`].
213#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
214pub struct Stats {
215    /// Number of file sections in the document.
216    pub files_changed: usize,
217    /// Total addition lines across all files.
218    pub insertions: usize,
219    /// Total deletion lines across all files.
220    pub deletions: usize,
221}
222
223/// A unified diff hunk and its body lines.
224#[derive(Clone, Debug, Eq, PartialEq)]
225pub struct Hunk {
226    /// Stable hunk identifier.
227    pub id: HunkId,
228    /// Parsed hunk header.
229    pub header: HunkHeader,
230    /// Lines contained in the hunk body.
231    pub lines: Vec<DiffLine>,
232}
233
234/// Metadata from a unified diff hunk header.
235///
236/// Example: `@@ -24,8 +24,6 @@ fn main`.
237#[derive(Clone, Debug, Default, Eq, PartialEq)]
238pub struct HunkHeader {
239    /// Starting line number on the old side of the diff.
240    pub old_line_no: u32,
241    /// Number of old-side lines covered by the hunk.
242    pub old_size: u32,
243    /// Starting line number on the new side of the diff.
244    pub new_line_no: u32,
245    /// Number of new-side lines covered by the hunk.
246    pub new_size: u32,
247    /// Optional trailing hunk context text.
248    pub text: String,
249}
250
251/// A single line in a unified diff hunk.
252#[derive(Clone, Debug, Eq, PartialEq)]
253pub struct DiffLine {
254    /// Stable row identifier.
255    pub id: RowId,
256    /// Line role inside the hunk.
257    pub kind: DiffLineKind,
258    /// Line text without the leading diff marker.
259    pub text: String,
260}
261
262/// Role of a line inside a unified diff hunk.
263#[derive(Clone, Copy, Debug, Eq, PartialEq)]
264pub enum DiffLineKind {
265    /// Unchanged context line.
266    Context,
267    /// Added line.
268    Addition,
269    /// Deleted line.
270    Deletion,
271    /// Marker for a file without a trailing newline.
272    NoNewline,
273}
274
275/// Error produced while decoding a unified diff.
276#[derive(Clone, Debug, Eq, PartialEq)]
277pub struct DecodeError {
278    /// One-based input line number where decoding failed.
279    pub line: usize,
280    /// Human-readable failure message.
281    pub message: String,
282    /// Whether this error represents a clean end-of-input signal.
283    is_eof: bool,
284}
285
286impl DiffDocument {
287    /// Returns whether the document contains no changed files.
288    pub fn is_empty(&self) -> bool {
289        self.files.is_empty()
290    }
291
292    /// Returns the totals of files changed, insertions, and deletions.
293    pub fn stats(&self) -> Stats {
294        let mut stats = Stats {
295            files_changed: self.files.len(),
296            ..Stats::default()
297        };
298        for file in &self.files {
299            let file_stats = file.stats();
300            stats.insertions += file_stats.additions;
301            stats.deletions += file_stats.deletions;
302        }
303        stats
304    }
305}
306
307impl FileHeader {
308    /// Returns the path callers should usually show for this file.
309    pub fn display_path(&self) -> Option<&PathBuf> {
310        self.new_path.as_ref().or(self.old_path.as_ref())
311    }
312}
313
314impl FileMode {
315    /// Returns the octal mode value Git records on the wire.
316    pub const fn as_octal(self) -> u32 {
317        match self {
318            Self::Blob => 0o100644,
319            Self::BlobExecutable => 0o100755,
320            Self::Link => 0o120000,
321            Self::Commit => 0o160000,
322            Self::Tree => 0o040000,
323            Self::Other(value) => value,
324        }
325    }
326
327    /// Builds a [`FileMode`] from an octal value, mapping known modes.
328    pub const fn from_octal(value: u32) -> Self {
329        match value {
330            0o100644 => Self::Blob,
331            0o100755 => Self::BlobExecutable,
332            0o120000 => Self::Link,
333            0o160000 => Self::Commit,
334            0o040000 => Self::Tree,
335            other => Self::Other(other),
336        }
337    }
338
339    /// Parses an octal mode token from a Git diff header (e.g. `"100644"`).
340    pub fn parse(input: &str) -> Option<Self> {
341        u32::from_str_radix(input.trim(), 8)
342            .ok()
343            .map(Self::from_octal)
344    }
345}
346
347impl fmt::Display for FileMode {
348    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
349        write!(f, "{:o}", self.as_octal())
350    }
351}
352
353impl DecodeError {
354    /// Creates a decode error at a one-based line number.
355    pub fn new(line: usize, message: impl Into<String>) -> Self {
356        Self {
357            line,
358            message: message.into(),
359            is_eof: false,
360        }
361    }
362
363    /// Creates an end-of-input error used to signal a clean EOF to streaming
364    /// callers. [`crate::Decode::try_decode`] turns this into `Ok(None)`.
365    pub fn eof() -> Self {
366        Self {
367            line: 0,
368            message: "unexpected end of file".to_owned(),
369            is_eof: true,
370        }
371    }
372
373    /// Returns whether this error represents end of input rather than a
374    /// malformed patch.
375    pub fn is_eof(&self) -> bool {
376        self.is_eof
377    }
378
379    /// Returns a copy of this error with a line number when the error has none.
380    pub(crate) fn at_line(mut self, line: usize) -> Self {
381        if self.line == 0 {
382            self.line = line;
383        }
384        self
385    }
386}
387
388impl fmt::Display for DecodeError {
389    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390        if self.line == 0 {
391            f.write_str(&self.message)
392        } else {
393            write!(f, "line {}: {}", self.line, self.message)
394        }
395    }
396}
397
398impl std::error::Error for DecodeError {}
399
400impl From<ParseIntError> for DecodeError {
401    fn from(error: ParseIntError) -> Self {
402        Self::new(0, error.to_string())
403    }
404}
405
406impl From<io::Error> for DecodeError {
407    fn from(error: io::Error) -> Self {
408        Self {
409            line: 0,
410            message: error.to_string(),
411            is_eof: error.kind() == io::ErrorKind::UnexpectedEof,
412        }
413    }
414}
415
416impl fmt::Display for FileKind {
417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418        let name = match self {
419            Self::Modified => "modified",
420            Self::Added => "added",
421            Self::Deleted => "deleted",
422            Self::Renamed => "renamed",
423            Self::Copied => "copied",
424            Self::ModeChanged => "mode changed",
425            Self::Binary => "binary",
426        };
427        f.write_str(name)
428    }
429}
430
431impl DiffLineKind {
432    /// Returns how many old-side lines this kind contributes to a hunk.
433    pub const fn old_len(self) -> u32 {
434        match self {
435            Self::Context | Self::Deletion => 1,
436            Self::Addition | Self::NoNewline => 0,
437        }
438    }
439
440    /// Returns how many new-side lines this kind contributes to a hunk.
441    pub const fn new_len(self) -> u32 {
442        match self {
443            Self::Context | Self::Addition => 1,
444            Self::Deletion | Self::NoNewline => 0,
445        }
446    }
447}
448
449impl HunkHeader {
450    /// Returns a copy with old and new line numbers shifted by the deltas.
451    pub fn shifted(&self, old_delta: i32, new_delta: i32) -> Self {
452        Self {
453            old_line_no: Self::add_delta(self.old_line_no, old_delta),
454            new_line_no: Self::add_delta(self.new_line_no, new_delta),
455            ..self.clone()
456        }
457    }
458
459    /// Adds a signed delta to an unsigned line number with saturation.
460    fn add_delta(line: u32, delta: i32) -> u32 {
461        if delta.is_negative() {
462            line.saturating_sub(delta.unsigned_abs())
463        } else {
464            line.saturating_add(delta.unsigned_abs())
465        }
466    }
467}
468
469impl Hunk {
470    /// Returns the number of old-side lines covered by the hunk body.
471    pub fn old_size(&self) -> u32 {
472        self.sizes().old
473    }
474
475    /// Returns the number of new-side lines covered by the hunk body.
476    pub fn new_size(&self) -> u32 {
477        self.sizes().new
478    }
479
480    /// Counts addition and deletion lines in this hunk.
481    pub fn stats(&self) -> FileStats {
482        let mut stats = FileStats::default();
483        for line in &self.lines {
484            match line.kind {
485                DiffLineKind::Addition => stats.additions += 1,
486                DiffLineKind::Deletion => stats.deletions += 1,
487                DiffLineKind::Context | DiffLineKind::NoNewline => {}
488            }
489        }
490        stats
491    }
492
493    /// Returns the net line offset introduced by applying this hunk.
494    pub fn delta(&self) -> i32 {
495        let sizes = self.sizes();
496        let new_size = i32::try_from(sizes.new).unwrap_or(i32::MAX);
497        let old_size = i32::try_from(sizes.old).unwrap_or(i32::MAX);
498        new_size - old_size
499    }
500
501    /// Splits this hunk into context-separated change groups, each with its
502    /// own recomputed header. Returns `None` when the hunk has fewer than two
503    /// change groups (nothing to split).
504    pub fn split(&self) -> Option<impl Iterator<Item = Self> + '_> {
505        let groups = self.change_groups();
506        if groups.len() < 2 {
507            return None;
508        }
509        Some((0..groups.len()).map(move |index| {
510            let group = groups[index];
511            let start = if index == 0 {
512                0
513            } else {
514                groups[index - 1].split_context_before(group)
515            };
516            let end = groups
517                .get(index + 1)
518                .map_or(self.lines.len(), |next| group.split_context_before(*next));
519            self.segment(start, end)
520        }))
521    }
522
523    /// Returns half-open ranges of contiguous non-context lines.
524    fn change_groups(&self) -> Vec<ChangeGroup> {
525        let mut groups = Vec::new();
526        let mut current = None;
527
528        for (index, line) in self.lines.iter().enumerate() {
529            if matches!(line.kind, DiffLineKind::Context) {
530                if let Some(start) = current.take() {
531                    groups.push(ChangeGroup { start, end: index });
532                }
533            } else if current.is_none() {
534                current = Some(index);
535            }
536        }
537        if let Some(start) = current {
538            groups.push(ChangeGroup {
539                start,
540                end: self.lines.len(),
541            });
542        }
543        groups
544    }
545
546    /// Returns one hunk segment with line numbers and sizes recomputed.
547    fn segment(&self, start: usize, end: usize) -> Self {
548        let lines = self.lines[start..end].to_vec();
549        let old_delta = self.lines[..start]
550            .iter()
551            .map(|l| l.kind.old_len())
552            .sum::<u32>();
553        let new_delta = self.lines[..start]
554            .iter()
555            .map(|l| l.kind.new_len())
556            .sum::<u32>();
557        let sizes = HunkSizes::from_lines(&lines);
558
559        Self {
560            id: self.id,
561            header: HunkHeader {
562                old_line_no: self.header.old_line_no.saturating_add(old_delta),
563                old_size: sizes.old,
564                new_line_no: self.header.new_line_no.saturating_add(new_delta),
565                new_size: sizes.new,
566                text: self.header.text.clone(),
567            },
568            lines,
569        }
570    }
571
572    /// Returns old-side and new-side body sizes.
573    fn sizes(&self) -> HunkSizes {
574        HunkSizes::from_lines(&self.lines)
575    }
576}
577
578/// Old-side and new-side line counts for a hunk body.
579#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
580struct HunkSizes {
581    /// Old-side line count.
582    old: u32,
583    /// New-side line count.
584    new: u32,
585}
586
587impl HunkSizes {
588    /// Counts old-side and new-side contributions across diff lines.
589    fn from_lines(lines: &[DiffLine]) -> Self {
590        let mut sizes = Self::default();
591        for line in lines {
592            sizes.old += line.kind.old_len();
593            sizes.new += line.kind.new_len();
594        }
595        sizes
596    }
597}
598
599impl FileDiff {
600    /// Returns the sum of addition and deletion lines across all hunks.
601    pub fn stats(&self) -> FileStats {
602        let mut total = FileStats::default();
603        for hunk in &self.hunks {
604            let hunk_stats = hunk.stats();
605            total.additions += hunk_stats.additions;
606            total.deletions += hunk_stats.deletions;
607        }
608        total
609    }
610
611    /// Returns a copy containing only the hunks at the given indexes.
612    pub fn selected(&self, hunks: impl IntoIterator<Item = usize>) -> Self {
613        Self {
614            id: self.id,
615            header: self.header.clone(),
616            hunks: hunks
617                .into_iter()
618                .filter_map(|ix| self.hunks.get(ix).cloned())
619                .collect(),
620        }
621    }
622}
623
624impl DiffDocument {
625    /// Returns a single-file document with the given hunks, suitable for
626    /// `git apply`. The preamble is dropped.
627    pub fn for_hunks(file: &FileDiff, hunks: impl IntoIterator<Item = Hunk>) -> Self {
628        Self {
629            commit: None,
630            files: vec![FileDiff {
631                id: file.id,
632                header: file.header.clone(),
633                hunks: hunks.into_iter().collect(),
634            }],
635        }
636    }
637}
638
639/// Half-open range of non-context lines inside a hunk.
640#[derive(Clone, Copy, Debug)]
641struct ChangeGroup {
642    /// First changed line index.
643    start: usize,
644    /// One past the final changed line index.
645    end: usize,
646}
647
648impl ChangeGroup {
649    /// Returns the split point in the context before `next`.
650    const fn split_context_before(self, next: Self) -> usize {
651        self.end + (next.start - self.end) / 2
652    }
653}
654
655#[cfg(test)]
656#[allow(clippy::unwrap_used)]
657mod tests {
658    use super::*;
659    use crate::Decode;
660
661    fn parse_patch(input: &str) -> DiffDocument {
662        DiffDocument::decode_str(input).unwrap()
663    }
664
665    const PATCH: &str = "\
666diff --git a/a.txt b/a.txt
667index 7898192..6178079 100644
668--- a/a.txt
669+++ b/a.txt
670@@ -1,3 +1,4 @@
671 one
672+two
673 three
674-four
675+five
676";
677
678    #[test]
679    fn diff_line_kind_counts_old_and_new_contributions() {
680        assert_eq!(DiffLineKind::Context.old_len(), 1);
681        assert_eq!(DiffLineKind::Context.new_len(), 1);
682        assert_eq!(DiffLineKind::Addition.old_len(), 0);
683        assert_eq!(DiffLineKind::Addition.new_len(), 1);
684        assert_eq!(DiffLineKind::Deletion.old_len(), 1);
685        assert_eq!(DiffLineKind::Deletion.new_len(), 0);
686        assert_eq!(DiffLineKind::NoNewline.old_len(), 0);
687        assert_eq!(DiffLineKind::NoNewline.new_len(), 0);
688    }
689
690    #[test]
691    fn hunk_recomputes_sizes_from_lines() {
692        let doc = parse_patch(PATCH);
693        let hunk = &doc.files[0].hunks[0];
694
695        assert_eq!(hunk.old_size(), 3);
696        assert_eq!(hunk.new_size(), 4);
697        assert_eq!(hunk.delta(), 1);
698    }
699
700    #[test]
701    fn hunk_split_separates_change_groups() {
702        let doc = parse_patch(PATCH);
703        let hunk = &doc.files[0].hunks[0];
704        let split = hunk.split().unwrap().collect::<Vec<_>>();
705
706        assert_eq!(split.len(), 2);
707        assert_eq!(split[0].header.old_line_no, 1);
708        assert_eq!(split[0].header.old_size, 1);
709        assert_eq!(split[0].header.new_line_no, 1);
710        assert_eq!(split[0].header.new_size, 2);
711        assert_eq!(split[1].header.old_line_no, 2);
712        assert_eq!(split[1].header.old_size, 2);
713        assert_eq!(split[1].header.new_line_no, 3);
714        assert_eq!(split[1].header.new_size, 2);
715    }
716
717    #[test]
718    fn hunk_split_returns_none_for_single_change_group() {
719        let doc = parse_patch(
720            "\
721diff --git a/a b/a
722@@ -1 +1,2 @@
723 one
724+two
725",
726        );
727
728        assert!(doc.files[0].hunks[0].split().is_none());
729    }
730
731    #[test]
732    fn hunk_header_shifted_moves_line_numbers() {
733        let header = HunkHeader::decode_str("@@ -10,3 +20,3 @@").unwrap();
734        let shifted = header.shifted(2, -3);
735
736        assert_eq!(shifted.old_line_no, 12);
737        assert_eq!(shifted.new_line_no, 17);
738        assert_eq!(shifted.old_size, 3);
739        assert_eq!(shifted.new_size, 3);
740    }
741
742    #[test]
743    fn file_diff_selected_keeps_only_chosen_hunks() {
744        let doc = parse_patch(PATCH);
745        let only = doc.files[0].selected([0]);
746
747        assert_eq!(only.hunks.len(), 1);
748        assert_eq!(only.id, doc.files[0].id);
749    }
750
751    #[test]
752    fn document_for_hunks_drops_preamble() {
753        let with_preamble = format!("commit abc\n\n{PATCH}");
754        let doc = parse_patch(&with_preamble);
755        let single = DiffDocument::for_hunks(&doc.files[0], doc.files[0].hunks.clone());
756
757        assert!(single.commit.is_none());
758        assert_eq!(single.files.len(), 1);
759        assert_eq!(single.files[0].hunks.len(), doc.files[0].hunks.len());
760    }
761
762    #[test]
763    fn stats_aggregate_across_hunks_and_files() {
764        let doc = parse_patch(PATCH);
765        let hunk_stats = doc.files[0].hunks[0].stats();
766        let file_stats = doc.files[0].stats();
767        let doc_stats = doc.stats();
768
769        assert_eq!(
770            hunk_stats,
771            FileStats {
772                additions: 2,
773                deletions: 1
774            }
775        );
776        assert_eq!(
777            file_stats,
778            FileStats {
779                additions: 2,
780                deletions: 1
781            }
782        );
783        assert_eq!(
784            doc_stats,
785            Stats {
786                files_changed: 1,
787                insertions: 2,
788                deletions: 1,
789            }
790        );
791    }
792
793    #[test]
794    fn file_mode_round_trips_through_octal() {
795        for mode in [
796            FileMode::Blob,
797            FileMode::BlobExecutable,
798            FileMode::Link,
799            FileMode::Commit,
800            FileMode::Tree,
801            FileMode::Other(0o123456),
802        ] {
803            assert_eq!(FileMode::from_octal(mode.as_octal()), mode);
804            assert_eq!(FileMode::parse(&mode.to_string()), Some(mode));
805        }
806        assert_eq!(FileMode::parse("not-octal"), None);
807    }
808
809    #[test]
810    fn oid_parses_hexadecimal_text() {
811        let oid = Oid::from_str("ABC123").unwrap();
812
813        assert_eq!(oid.as_str(), "ABC123");
814        assert_eq!(oid.to_string(), "ABC123");
815        assert_eq!("".parse::<Oid>(), Err(OidError));
816        assert_eq!("not-hex".parse::<Oid>(), Err(OidError));
817    }
818
819    #[test]
820    fn add_delta_saturates_at_zero() {
821        assert_eq!(HunkHeader::add_delta(5, 3), 8);
822        assert_eq!(HunkHeader::add_delta(5, -3), 2);
823        assert_eq!(HunkHeader::add_delta(2, -10), 0);
824    }
825}