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