Skip to main content

paircomp_core/
lib.rs

1//! Raw-byte file inspection, prefix fingerprinting, and difference localization.
2//!
3//! Each instance reads only its local file. The caller exchanges counts and
4//! compares fingerprints with the other instance; this crate handles file
5//! access and search state without terminal or network I/O.
6//!
7//! # Comparison workflow
8//!
9//! 1. Call [`inspect_file`] and compare the whole-file fingerprints. If they
10//!    match, the comparison is complete.
11//! 2. On a mismatch, exchange line counts and construct a [`LineSearch`]. Use
12//!    [`fingerprint_through_line`] for each requested comparison and pass the
13//!    answer as a [`Comparison`] to [`LineSearch::record_result`] until the
14//!    differing line is known.
15//! 3. To continue within that line, call [`inspect_line`], exchange byte lengths
16//!    (zero for an absent line), and construct a [`ByteSearch`]. Compare
17//!    [`fingerprint_line_prefix`] results and call [`ByteSearch::record_result`].
18//! 4. Optionally annotate the differing byte with [`utf8_character_position`].
19//!
20//! Both instances must use accurate counts and the same comparison answers.
21//! Localization also assumes that distinct prefixes have distinct fingerprints.
22//!
23//! ## Example
24//!
25//! This runnable example uses two fixture files to simulate the counts and
26//! fingerprints supplied by the other instance. In a real frontend, each
27//! instance opens only its own file; the caller obtains the other instance's
28//! counts and a match/no-match answer for each fingerprint comparison.
29//! Keep both files [unchanged](#file-stability) throughout the comparison.
30//! The example chooses to continue into the optional within-line search.
31//!
32//! ```
33//! use paircomp_core::{
34//!     fingerprint_line_prefix, fingerprint_through_line, inspect_file, inspect_line,
35//!     utf8_character_position, ByteSearch, ByteSearchStep, Comparison, LineSearch, LineSearchStep,
36//! };
37//! use std::fs;
38//!
39//! let directory = std::env::temp_dir()
40//!     .join(format!("paircomp-workflow-example-{}", std::process::id()));
41//! fs::create_dir(&directory)?;
42//! let local_path = directory.join("local.txt");
43//! let other_path = directory.join("other.txt");
44//! fs::write(&local_path, "header\ncafé\nfooter\n")?;
45//! fs::write(&other_path, "header\ncafè\nfooter\n")?;
46//!
47//! let local = inspect_file(&local_path)?;
48//! let other = inspect_file(&other_path)?; // Simulates metadata from the other instance.
49//! if local.fingerprint == other.fingerprint {
50//!     println!("The files match.");
51//! } else {
52//!     // Start searching only after establishing the whole-file mismatch.
53//!     let mut search = LineSearch::new(local.line_count, other.line_count)?;
54//!     let line = loop {
55//!         match search.current_step() {
56//!             LineSearchStep::CompareThroughLine { line } => {
57//!                 let fingerprint = fingerprint_through_line(&local_path, line)?;
58//!                 let other_fingerprint = fingerprint_through_line(&other_path, line)?;
59//!                 // The frontend would ask whether the displayed fingerprints match.
60//!                 let comparison = if fingerprint == other_fingerprint {
61//!                     Comparison::Match
62//!                 } else {
63//!                     Comparison::Differ
64//!                 };
65//!                 search.record_result(comparison)?;
66//!             }
67//!             LineSearchStep::DifferenceAtLine { line } => break line,
68//!         }
69//!     };
70//!     assert_eq!(line, 2);
71//!
72//!     // Both instances choose to continue. Counts include LF; absence means zero.
73//!     let local_byte_len = inspect_line(&local_path, line)?.map_or(0, |info| info.byte_len);
74//!     let other_byte_len = inspect_line(&other_path, line)?.map_or(0, |info| info.byte_len);
75//!     let mut search = ByteSearch::new(local_byte_len, other_byte_len)?;
76//!     let byte = loop {
77//!         match search.current_step() {
78//!             ByteSearchStep::CompareThroughByte { byte } => {
79//!                 // These raw-byte prefixes can end inside a UTF-8 code point.
80//!                 let fingerprint = fingerprint_line_prefix(&local_path, line, byte)?;
81//!                 let other_fingerprint = fingerprint_line_prefix(&other_path, line, byte)?;
82//!                 let comparison = if fingerprint == other_fingerprint {
83//!                     Comparison::Match
84//!                 } else {
85//!                     Comparison::Differ
86//!                 };
87//!                 search.record_result(comparison)?;
88//!             }
89//!             ByteSearchStep::DifferenceAtByte { byte } => break byte,
90//!         }
91//!     };
92//!     assert_eq!(byte, 5);
93//!     println!("First difference: line {line}, byte {byte}");
94//!     if line > local.line_count {
95//!         println!("The local file has no such line.");
96//!     } else if byte > local_byte_len {
97//!         println!("The local line has no such byte.");
98//!     }
99//!
100//!     // Character positions are supplementary and require valid UTF-8 for the whole line.
101//!     let character = utf8_character_position(&local_path, line, byte)?;
102//!     assert_eq!(character, Some(4));
103//!     if let Some(position) = character {
104//!         println!("UTF-8 code-point position: {position}");
105//!     }
106//! }
107//! fs::remove_dir_all(&directory)?;
108//! # Ok::<(), Box<dyn std::error::Error>>(())
109//! ```
110//!
111//! # Bytes and positions
112//!
113//! Hashing uses raw bytes without normalization or UTF-8 decoding. LF terminates
114//! a line and belongs to it; CR is ordinary content. A nonempty suffix after the
115//! last LF counts as a line, and a trailing LF creates no extra line.
116//!
117//! Line, byte, and Unicode code-point positions start at 1. Only
118//! [`fingerprint_through_line`] accepts line zero, denoting an empty file prefix.
119//! Byte positions are relative to the selected line. Character annotations
120//! require that entire line to be valid UTF-8 and count code points, not grapheme
121//! clusters or visual columns.
122//!
123//! # File stability
124//!
125//! Each file operation opens the supplied path afresh. The library does
126//! not snapshot files, lock them, or detect changes.
127//!
128//! Both files must remain unchanged from the start of the initial inspection
129//! until the comparison ends, including during reads and between calls. If
130//! either file is edited or replaced, discard the collected metadata,
131//! fingerprints, and [`LineSearch`]/[`ByteSearch`] state, and restart both
132//! instances from the initial inspection.
133
134use std::error::Error as StdError;
135use std::fmt;
136use std::io;
137
138mod file;
139mod search;
140mod within_line;
141pub use file::{fingerprint_file, fingerprint_through_line, inspect_file};
142pub use search::{ByteSearch, ByteSearchStep, Comparison, LineSearch, LineSearchStep};
143pub use within_line::{fingerprint_line_prefix, inspect_line, utf8_character_position};
144
145/// Metadata calculated from the bytes read from a regular file.
146#[derive(Clone, Copy, Debug, Eq, PartialEq)]
147pub struct FileInfo {
148    /// Number of raw bytes in the file.
149    pub byte_len: u64,
150    /// Number of LF bytes, plus one for a nonempty unterminated suffix.
151    ///
152    /// A trailing LF creates no extra line; an empty file has zero lines.
153    pub line_count: u64,
154    /// BLAKE3 digest of all raw file bytes, without normalization.
155    pub fingerprint: Fingerprint,
156}
157
158/// Metadata for an existing line, including its terminating LF if present.
159#[derive(Clone, Copy, Debug, Eq, PartialEq)]
160pub struct LineInfo {
161    /// Number of raw bytes in the line, including its LF if present.
162    ///
163    /// An existing line always contains at least one byte.
164    pub byte_len: u64,
165}
166
167/// A full 256-bit BLAKE3 digest of raw bytes.
168///
169/// Equality and [`std::hash::Hash`] use all 32 digest bytes. Matching fingerprints
170/// provide strong evidence of equal input, subject to the possibility of a hash
171/// collision. Use [`Self::as_bytes`] to format the digest for display in a frontend,
172/// or [`AsRef<[u8]>`] to borrow the complete digest as a byte slice.
173#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
174pub struct Fingerprint([u8; 32]);
175
176impl Fingerprint {
177    /// Borrows the complete 32-byte BLAKE3 digest in its original byte order.
178    ///
179    /// No bytes are truncated or converted to a display string.
180    pub fn as_bytes(&self) -> &[u8; 32] {
181        &self.0
182    }
183}
184
185impl AsRef<[u8]> for Fingerprint {
186    /// Borrows all 32 digest bytes in their original byte order, without copying.
187    fn as_ref(&self) -> &[u8] {
188        self.as_bytes()
189    }
190}
191
192/// An error returned by a core operation.
193///
194/// This enum is non-exhaustive so new variants can be added in future releases.
195/// Callers outside this crate must include a wildcard arm when matching:
196///
197/// ```
198/// use paircomp_core::Error;
199///
200/// fn report(error: &Error) {
201///     match error {
202///         Error::Io(source) => eprintln!("I/O error: {source}"),
203///         _ => eprintln!("{error}"),
204///     }
205/// }
206/// ```
207///
208/// Matching only the currently known variants does not compile:
209///
210/// ```compile_fail,E0004
211/// use paircomp_core::Error;
212///
213/// fn report(error: &Error) {
214///     match error {
215///         Error::Io(_) => {},
216///         Error::NotRegularFile
217///         | Error::FileTooLarge
218///         | Error::EmptyFilesCannotDiffer
219///         | Error::EmptyLinesCannotDiffer
220///         | Error::InvalidLineNumber
221///         | Error::InvalidBytePosition
222///         | Error::SearchAlreadyComplete => {},
223///     }
224/// }
225/// ```
226#[derive(Debug)]
227#[non_exhaustive]
228pub enum Error {
229    /// Metadata lookup, opening, or reading the file failed.
230    Io(io::Error),
231    /// The path does not identify a regular file.
232    NotRegularFile,
233    /// A byte count, line count, or character position cannot fit in `u64`.
234    FileTooLarge,
235    /// Both supplied line counts are zero despite a reported mismatch.
236    EmptyFilesCannotDiffer,
237    /// Both supplied line byte lengths are zero despite a reported mismatch.
238    EmptyLinesCannotDiffer,
239    /// A line-local operation was given line zero; its lines start at 1.
240    InvalidLineNumber,
241    /// The byte position is zero or more than one past the selected line.
242    ///
243    /// An absent line permits only byte position 1.
244    InvalidBytePosition,
245    /// An answer was submitted after the search had reached its result.
246    SearchAlreadyComplete,
247}
248
249impl fmt::Display for Error {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        match self {
252            Self::Io(error) => write!(f, "file I/O failed: {error}"),
253            Self::NotRegularFile => f.write_str("input is not a regular file"),
254            Self::FileTooLarge => f.write_str("file size or line count exceeds u64"),
255            Self::EmptyFilesCannotDiffer => f.write_str("two empty files cannot differ"),
256            Self::EmptyLinesCannotDiffer => f.write_str("two zero-length lines cannot differ"),
257            Self::InvalidLineNumber => f.write_str("line numbers must start at 1"),
258            Self::InvalidBytePosition => {
259                f.write_str("byte position must be within the line or immediately after it")
260            }
261            Self::SearchAlreadyComplete => f.write_str("search is already complete"),
262        }
263    }
264}
265
266impl StdError for Error {
267    fn source(&self) -> Option<&(dyn StdError + 'static)> {
268        match self {
269            Self::Io(error) => Some(error),
270            Self::NotRegularFile
271            | Self::FileTooLarge
272            | Self::EmptyFilesCannotDiffer
273            | Self::EmptyLinesCannotDiffer
274            | Self::InvalidLineNumber
275            | Self::InvalidBytePosition
276            | Self::SearchAlreadyComplete => None,
277        }
278    }
279}
280
281impl From<io::Error> for Error {
282    fn from(error: io::Error) -> Self {
283        Self::Io(error)
284    }
285}