Skip to main content

paircomp_core/
search.rs

1use crate::Error;
2
3/// The caller's answer to a fingerprint comparison on the two copies.
4///
5/// Pass the same answer to [`LineSearch::record_result`] or
6/// [`ByteSearch::record_result`] on both instances. This describes the requested
7/// prefix comparison, rather than the final location of a difference.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum Comparison {
10    /// The two fingerprints match.
11    Match,
12    /// The two fingerprints differ.
13    Differ,
14}
15
16/// A prefix comparison requested by [`LineSearch`], or its completed result.
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum LineSearchStep {
19    /// Compare file prefixes through this line, including its LF if present.
20    ///
21    /// Use [`crate::fingerprint_through_line`] on each copy. A request beyond
22    /// the local EOF hashes the whole local file.
23    CompareThroughLine {
24        /// The 1-based line position.
25        line: u64,
26    },
27    /// The first differing line; it may be beyond the local EOF.
28    DifferenceAtLine {
29        /// The 1-based line position.
30        line: u64,
31    },
32}
33
34/// A deterministic search for the first differing line using file prefixes.
35///
36/// Construct this only after the whole-file fingerprints have been reported
37/// as different. Supply the local line count and the count reported by the
38/// other instance to [`Self::new`]. Drive the search with [`Self::current_step`]
39/// and [`Self::record_result`]; the search itself performs no file I/O.
40///
41/// Line counts and comparison results must describe the same unchanged pair of
42/// files throughout the search. See the [file stability requirements](crate#file-stability).
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub struct LineSearch {
45    bounds: SearchBounds,
46}
47
48impl LineSearch {
49    /// Creates a line search using both copies' counts.
50    ///
51    /// Construct only after comparing the whole-file fingerprints and establishing
52    /// a mismatch. Supply the local line count and the count reported by the other
53    /// copy; either count may be zero. Both files must stay unchanged, and both
54    /// instances must use accurate counts and the same comparison answers.
55    ///
56    /// Equal counts bound the search at that count. Unequal counts bound it at
57    /// one past the shorter file: the first difference is either in a shared
58    /// line or at the first absent line. Comparisons never exceed the shorter
59    /// count. The constructor does not read either file or verify the mismatch.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`Error::EmptyFilesCannotDiffer`] when both counts are zero.
64    ///
65    /// # Examples
66    ///
67    /// ```
68    /// use paircomp_core::{Comparison, LineSearch, LineSearchStep};
69    ///
70    /// // The whole-file fingerprints differ; the copies have 3 and 4 lines.
71    /// let mut search = LineSearch::new(3, 4)?;
72    /// assert_eq!(search.current_step(), LineSearchStep::CompareThroughLine { line: 2 });
73    /// search.record_result(Comparison::Match)?;
74    /// assert_eq!(search.current_step(), LineSearchStep::CompareThroughLine { line: 3 });
75    /// search.record_result(Comparison::Differ)?;
76    /// assert_eq!(search.current_step(), LineSearchStep::DifferenceAtLine { line: 3 });
77    /// # Ok::<(), paircomp_core::Error>(())
78    /// ```
79    pub fn new(local_line_count: u64, other_line_count: u64) -> Result<Self, Error> {
80        let bounds = SearchBounds::new(local_line_count, other_line_count)
81            .ok_or(Error::EmptyFilesCannotDiffer)?;
82        Ok(Self { bounds })
83    }
84
85    /// Returns the next prefix comparison or the completed line result.
86    ///
87    /// Repeated calls leave the state unchanged. Positions are 1-based; a final
88    /// result can refer to a line absent from the shorter copy. When only one
89    /// candidate remains, returns [`LineSearchStep::DifferenceAtLine`] without
90    /// requesting another comparison.
91    pub fn current_step(&self) -> LineSearchStep {
92        match self.bounds.midpoint() {
93            Some(line) => LineSearchStep::CompareThroughLine { line },
94            None => LineSearchStep::DifferenceAtLine {
95                line: self.bounds.low,
96            },
97        }
98    }
99
100    /// Applies the answer to the comparison returned by [`Self::current_step`].
101    ///
102    /// Pass [`Comparison::Match`] when the two fingerprints from
103    /// [`crate::fingerprint_through_line`] match, or [`Comparison::Differ`] when
104    /// they differ. A match excludes the prefix through the requested line; a
105    /// mismatch retains that position as a candidate. The caller must supply
106    /// the answer for the current comparison on both copies.
107    ///
108    /// # Errors
109    ///
110    /// Returns [`Error::SearchAlreadyComplete`] if the result is already known.
111    /// An error leaves the search unchanged.
112    pub fn record_result(&mut self, comparison: Comparison) -> Result<(), Error> {
113        self.bounds.record_result(comparison)
114    }
115}
116
117/// A requested line-local prefix comparison, or the first differing byte.
118///
119/// Byte positions are 1-based and can denote a byte absent from the shorter copy.
120#[derive(Clone, Copy, Debug, Eq, PartialEq)]
121pub enum ByteSearchStep {
122    /// Compare prefixes from the selected line's beginning through this byte.
123    ///
124    /// Use [`crate::fingerprint_line_prefix`] on each copy. Requests past the
125    /// local line's end hash the whole line; an absent line hashes no bytes.
126    CompareThroughByte {
127        /// The 1-based byte position.
128        byte: u64,
129    },
130    /// The first differing byte; it may be absent from the shorter line.
131    DifferenceAtByte {
132        /// The 1-based byte position.
133        byte: u64,
134    },
135}
136
137/// A deterministic search for the first differing byte within a differing line.
138///
139/// Supply both copies' byte lengths, including any LF, to [`Self::new`]. An
140/// absent line has length zero. Drive the search with [`Self::current_step`] and
141/// [`Self::record_result`]; the caller keeps track of the selected line, and the
142/// search itself performs no file I/O.
143///
144/// Counts and comparison results must describe the same unchanged pair of lines
145/// throughout the search. See the [file stability requirements](crate#file-stability).
146#[derive(Clone, Copy, Debug, Eq, PartialEq)]
147pub struct ByteSearch {
148    bounds: SearchBounds,
149}
150
151impl ByteSearch {
152    /// Creates a byte search using both copies' counts.
153    ///
154    /// Construct only after the line search has established that the selected
155    /// line differs and all preceding lines match. Supply each copy's byte length
156    /// for that line, including any CR/LF; use zero for an absent line. Both files
157    /// must stay unchanged, and both instances must use accurate lengths and the
158    /// same comparison answers.
159    ///
160    /// Equal lengths bound the search at that length. Unequal lengths bound it
161    /// at one past the shorter line: the first difference is either in a shared
162    /// byte or at the first absent byte. Comparisons never exceed the shorter
163    /// length. The constructor does not read either file or verify the mismatch.
164    ///
165    /// # Errors
166    ///
167    /// Returns [`Error::EmptyLinesCannotDiffer`] when both counts are zero.
168    ///
169    /// # Examples
170    ///
171    /// ```
172    /// use paircomp_core::{ByteSearch, ByteSearchStep, Comparison};
173    ///
174    /// // The differing lines are UTF-8 "café" and "cafè", each 5 bytes long.
175    /// let mut search = ByteSearch::new(5, 5)?;
176    /// assert_eq!(search.current_step(), ByteSearchStep::CompareThroughByte { byte: 3 });
177    /// search.record_result(Comparison::Match)?; // "caf" matches.
178    /// assert_eq!(search.current_step(), ByteSearchStep::CompareThroughByte { byte: 4 });
179    /// search.record_result(Comparison::Match)?; // The first byte of the final code point matches.
180    /// assert_eq!(search.current_step(), ByteSearchStep::DifferenceAtByte { byte: 5 });
181    /// # Ok::<(), paircomp_core::Error>(())
182    /// ```
183    pub fn new(local_byte_len: u64, other_byte_len: u64) -> Result<Self, Error> {
184        let bounds = SearchBounds::new(local_byte_len, other_byte_len)
185            .ok_or(Error::EmptyLinesCannotDiffer)?;
186        Ok(Self { bounds })
187    }
188
189    /// Returns the next prefix comparison or the completed byte result.
190    ///
191    /// Repeated calls leave the state unchanged. Positions are 1-based; a final
192    /// result can refer to a byte absent from the shorter copy. When only one
193    /// candidate remains, returns [`ByteSearchStep::DifferenceAtByte`] without
194    /// requesting another comparison.
195    pub fn current_step(&self) -> ByteSearchStep {
196        match self.bounds.midpoint() {
197            Some(byte) => ByteSearchStep::CompareThroughByte { byte },
198            None => ByteSearchStep::DifferenceAtByte {
199                byte: self.bounds.low,
200            },
201        }
202    }
203
204    /// Applies the answer to the comparison returned by [`Self::current_step`].
205    ///
206    /// Pass [`Comparison::Match`] when the two fingerprints from
207    /// [`crate::fingerprint_line_prefix`] match, or [`Comparison::Differ`] when
208    /// they differ. A match excludes the prefix through the requested byte; a
209    /// mismatch retains that position as a candidate. The caller must supply
210    /// the answer for the current comparison on both copies.
211    ///
212    /// # Errors
213    ///
214    /// Returns [`Error::SearchAlreadyComplete`] if the result is already known.
215    /// An error leaves the search unchanged.
216    pub fn record_result(&mut self, comparison: Comparison) -> Result<(), Error> {
217        self.bounds.record_result(comparison)
218    }
219}
220
221/// Inclusive candidate bounds for prefix bisection.
222///
223/// Maintains `1 <= low <= high`. Given an initial mismatch and consistent
224/// answers, prefixes before `low` match and the prefix through `high` differs.
225/// This lets the search finish at `low == high` without another comparison.
226#[derive(Clone, Copy, Debug, Eq, PartialEq)]
227struct SearchBounds {
228    low: u64,
229    high: u64,
230}
231
232impl SearchBounds {
233    fn new(local_count: u64, other_count: u64) -> Option<Self> {
234        let high = if local_count == other_count {
235            local_count
236        } else {
237            // Unequal counts guarantee the smaller one is below u64::MAX.
238            local_count.min(other_count) + 1
239        };
240        (high > 0).then_some(Self { low: 1, high })
241    }
242
243    /// A completed search has no midpoint; `low` is its result.
244    fn midpoint(&self) -> Option<u64> {
245        (self.low < self.high).then(|| self.low + (self.high - self.low) / 2)
246    }
247
248    fn record_result(&mut self, comparison: Comparison) -> Result<(), Error> {
249        let midpoint = self.midpoint().ok_or(Error::SearchAlreadyComplete)?;
250        match comparison {
251            Comparison::Match => self.low = midpoint + 1,
252            Comparison::Differ => self.high = midpoint,
253        }
254        Ok(())
255    }
256}