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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
//! Byte-preserving line edits and explicit binary classification.
//!
//! Start with [`diff`] when both payloads are already in memory. [`BlobContent::read`] loads the
//! blob sides of a [`crate::TreeChange`] from object storage first. [`ContentDiff`] distinguishes
//! unchanged, binary-changed, and text results; [`DiffLimits`] bounds the comparison. Returned
//! text edits borrow the supplied payloads and do not include patch context; render them with
//! [`crate::patch::write_hunks`], or write whole `git diff` patches with
//! [`crate::Objects::write_patch`].
//!
//! The comparison does not apply attributes, textconv, whitespace normalization, rename
//! detection, or patch encoding. It performs no merge, index, or worktree operation.
//!
//! # Choose a comparison layer
//!
//! A file-list viewer starts with [`crate::Objects::compare_trees`]. A patch viewer loads a
//! change with [`BlobContent::read`], then calls [`diff`] and renders the returned byte ranges,
//! or uses [`crate::patch`] for Git's unified form.
//! Keep the original structural change alongside the content result: a mode-only change or an
//! added empty file can have unchanged content. Gitlinks need a submodule view instead of blob
//! loading. Use [`crate::rewrites`] separately to infer relationships between different paths.
//!
//! Text is split only at LF. CRLF, invalid UTF-8 and a missing final LF remain exact bytes, so
//! rendering and escaping are caller decisions. [`TextDiff`] demonstrates reconstruction from
//! the original coordinates. Similarity scoring in `rewrites` has different line/CR rules and
//! must not be used as a content equality test. Rewrite scoring checks for NUL only in the first
//! 8000 bytes; content diff's automatic binary policy checks the entire payload.
//!
//! # Example
//!
//! Load both sides of a changed tree entry, then diff their lines:
//!
//! ```
//! use std::sync::atomic::AtomicBool;
//!
//! use girt::content_diff::{BinaryMode, BlobContent, ContentDiff, DiffLimits, diff};
//! use girt::{
//! EntryMode, InitKind, ObjectFormat, PackLimits, ReadLimits, Repository, Tree,
//! TreeCompareLimits, TreeEntry,
//! };
//!
//! let directory = tempfile::tempdir()?;
//! let repo = Repository::init(
//! ObjectFormat::Sha1,
//! directory.path().join("r"),
//! InitKind::Bare,
//! )?;
//! let loose = repo.loose_objects();
//! let tree = |content: &[u8]| -> Result<_, Box<dyn std::error::Error>> {
//! let id = loose.write_blob(content)?;
//! let entry = TreeEntry {
//! mode: EntryMode::Blob,
//! name: b"list.txt".to_vec(),
//! id,
//! };
//! Ok(loose.write_tree(&Tree::new(ObjectFormat::Sha1, vec![entry])?)?)
//! };
//! let (old, new) = (tree(b"apples\npears\n")?, tree(b"apples\nplums\n")?);
//!
//! let objects = repo.objects_with(PackLimits::default())?;
//! let cancel = AtomicBool::new(false);
//! let changes =
//! objects.compare_trees_with(Some(old), Some(new), TreeCompareLimits::default(), &cancel)?;
//! let limits = DiffLimits::default();
//! let content = BlobContent::read(
//! &objects,
//! &changes[0],
//! ReadLimits::default(),
//! limits.max_input_bytes,
//! &cancel,
//! )?;
//! let ContentDiff::Text(text) = diff(
//! &content.old,
//! &content.new,
//! BinaryMode::Auto,
//! limits,
//! &cancel,
//! )?
//! else {
//! panic!("both sides are text");
//! };
//! let edit = &text.edits()[0];
//! assert_eq!(&text.old_bytes()[edit.old_bytes.clone()], b"pears\n");
//! assert_eq!(&text.new_bytes()[edit.new_bytes.clone()], b"plums\n");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
use ;
pub use ;
pub use ;
/// Compares exact bytes, returning unchanged, binary-changed, or a shortest line edit sequence.
///
/// Lines include their terminating LF. A final nonempty unterminated fragment is a line; empty
/// input has no lines. CR, NUL (in forced text), non-UTF-8 and missing final LF remain significant.
/// Results borrow both inputs; no payload bytes are copied. Edits use zero-based half-open ranges
/// into the original inputs, coalesce adjacent insertions/deletions, and contain no context.
/// Unlisted gaps are byte-identical. They are not unified patch hunks: context expansion and
/// rendering belong to [`crate::patch::write_hunks`].
///
/// Equal bytes return [`ContentDiff::Unchanged`] in every mode, including binary. Auto mode scans
/// the **entire** payloads for NUL; it does not implement Git attributes or Git's sampling policy.
///
/// The independent Myers implementation minimizes inserted plus deleted lines. It greedily matches
/// equal lines, visits diagonals from insertion-heavy to deletion-heavy, and chooses deletion when
/// predecessor frontiers reach the same old position. This fixes repeated-line alignment; it does
/// not promise Git's exact search alignment. A post-processing pass rotates byte-identical
/// boundary lines to coalesce change groups and prefers boundaries aligned with changes on the
/// opposite side. Otherwise, the default indent-aware scoring prefers structural boundaries;
/// [`diff_with_options`] can disable scoring while retaining compaction. Rotations preserve the
/// unchanged subsequence and shortest-edit count. The scoring is calibrated against Git CLI
/// experiments, but some blank-run and file-edge ties still differ from Git.
///
/// With N total lines and edit distance D, search uses O(ND) line comparisons and O(D²) stored
/// frontier positions, subject to [`DiffLimits`]. Byte comparisons also consume work budget.
/// Compaction uses O(N) additional markers and charges scans and rotations to the same work budget.
/// Empty sides bypass search and compaction. No approximate fallback or partial edits are returned
/// on exhaustion.
///
/// This synchronous, pure operation checks cancellation before work, during scans (at most 4 KiB
/// per chunk), at every frontier/line comparison, during traceback and boundary selection, and
/// before return. Set `cancel` from another thread and leave it set until return. Allocation and
/// destruction cannot be interrupted; this is cooperative cancellation without a wall-clock
/// guarantee. Async callers should use a caller-bounded worker for substantial inputs.
///
/// # Errors
///
/// Returns [`DiffError`] on cancellation, checked-arithmetic overflow or exhaustion of any bound.
/// Input-byte limits apply even to equal/binary inputs; line/trace limits apply only to text
/// search. No external state changes on success or failure.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::content_diff::{BinaryMode, ContentDiff, DiffLimits, diff};
/// let result = diff(
/// b"one\ntwo\n",
/// b"one\nthree",
/// BinaryMode::Auto,
/// DiffLimits::default(),
/// &AtomicBool::new(false),
/// )?;
/// let ContentDiff::Text(text) = result else {
/// panic!("expected text edits")
/// };
/// let edit = &text.edits()[0];
/// assert_eq!(edit.old_lines, 1..2);
/// assert_eq!(&text.old_bytes()[edit.old_bytes.clone()], b"two\n");
/// assert_eq!(&text.new_bytes()[edit.new_bytes.clone()], b"three");
/// # Ok::<(), girt::content_diff::DiffError>(())
/// ```
/// Compares payloads with explicit classification and boundary-placement options.
///
/// See [`diff`] for byte, borrowing, shortest-edit, resource and cancellation contracts. Set
/// [`Options::indent_heuristic`] to false for compaction without indentation scoring.
///
/// # Errors
///
/// Returns the same errors as [`diff`], without returning partial edits.
/// End offsets avoid copying lines and give both byte ranges and constant-time line access.