girt 0.13.1

An incremental, idiomatic Rust implementation of Git
Documentation
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use crate::{
    ObjectId, ObjectKind, ObjectReadError, ReadLimits, TreeCompareError, TreeCompareLimits,
};

/// Source selection for inferred copies, in addition to deleted rename sources.
///
/// Use `Modified` when an added file may derive from a changed file's previous contents.
/// `ModifiedPostimage` serves consumers comparing against its new contents, but the result's
/// `source_id` still names the old content. Neither option searches unchanged source files.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::rewrites::{Copies, Kind, Options};
/// use girt::{EntryMode, InitKind, ObjectFormat, Repository, Tree, TreeEntry};
/// let directory = tempfile::tempdir()?;
/// let repo = Repository::init(
///     ObjectFormat::Sha1,
///     directory.path().join("r"),
///     InitKind::Bare,
/// )?;
/// let loose = repo.loose_objects();
/// let original = loose.write_blob(b"original content\n")?;
/// let edited = loose.write_blob(b"changed source\n")?;
/// let entry = |name: &[u8], id| TreeEntry {
///     name: name.to_vec(),
///     mode: EntryMode::Blob,
///     id,
/// };
/// let old = loose.write_tree(&Tree::new(
///     ObjectFormat::Sha1,
///     vec![entry(b"source", original)],
/// )?)?;
/// let new = loose.write_tree(&Tree::new(
///     ObjectFormat::Sha1,
///     vec![entry(b"source", edited), entry(b"copy", original)],
/// )?)?;
/// let copies = repo.objects_with(Default::default())?.detect_rewrites(
///     Some(old),
///     Some(new),
///     Options::default().with_copies(Copies::Modified),
///     Default::default(),
///     None,
///     &AtomicBool::new(false),
/// )?;
/// assert_eq!(copies.len(), 1);
/// assert_eq!(copies[0].kind, Kind::Copy);
/// assert_eq!(copies[0].source_id, original); // Scored against the source's preimage.
/// assert_eq!(copies[0].target, b"copy");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum Copies {
    /// Each deleted source can supply at most one destination.
    #[default]
    Disabled,
    /// Also use preimages of modified regular/executable files and reuse deleted sources.
    /// Unchanged files are not candidates; mode-only changes count as modifications.
    Modified,
    /// Score modified sources by their new blobs, while reporting their old blob identities.
    /// Deleted sources are still scored by their old blobs and can be reused.
    ModifiedPostimage,
}

/// Caller choices for inference, independent of repository configuration.
///
/// Empty files participate by default, matching both `git diff -M` and `git diff-tree -r -M`.
/// Use [`Self::with_track_empty(false)`](Self::with_track_empty) to leave them unpaired, as with
/// Git's `--no-rename-empty`.
///
/// ```
/// use girt::rewrites::{Copies, Options};
/// let exact_copies = Options::default()
///     .with_similarity(100)
///     .with_copies(Copies::Modified);
/// assert_eq!(exact_copies.similarity, 100); // Identity-only; no approximate scoring.
/// let bounded = Options::default().with_candidate_limit(0);
/// assert_eq!(bounded.candidate_limit, 0); // Skip edited matching if any counted pair remains.
/// ```
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Options {
    /// Minimum retained-byte percentage, inclusive, from 1 through 100 (default 50).
    /// 100 admits only identical object IDs, bypassing approximate scoring and the candidate
    /// limit; independent [`Limits`] still apply and no inexact skip is reported.
    pub similarity: u8,
    /// Whether modified files and already-used deleted files can supply copies.
    pub copies: Copies,
    /// Include empty blobs as exact-match sources (default true).
    ///
    /// Matches Git's porcelain and plumbing defaults with rename detection enabled. Empty
    /// content supplies no distinguishing evidence; set false to leave these files unpaired.
    pub track_empty: bool,
    /// Bound on edited-content detection, as in Git's `diff.renameLimit` (default 1000).
    ///
    /// Exact matches are attempted first. Without copies, unique unmatched basenames are then
    /// paired at a stricter similarity threshold: halfway from [`Self::similarity`] to 100%.
    /// Exhaustive edited-content detection is skipped when the remaining sources multiplied by
    /// the remaining destinations exceeds the square of this limit, as Git does.
    /// [`Objects::detect_rewrites_or_exact`](crate::Objects::detect_rewrites_or_exact) returns
    /// the pairs already found with an [`InexactSkipped`] report;
    /// [`Objects::detect_rewrites`](crate::Objects::detect_rewrites) returns
    /// [`Error::Candidates`]. Neither reports an incomplete inference as complete.
    ///
    /// Counts include available sources (including sources reused for copies) and unmatched
    /// destinations: binary files count even when [`Self::approximate_binary`] is false, and
    /// empty files count when [`Self::track_empty`] is true. Zero skips exhaustive detection
    /// whenever a counted pair remains; Git's configuration value 0 means unlimited, which is
    /// `usize::MAX`.
    pub candidate_limit: usize,
    /// Permit approximate matching when either blob contains NUL in its first 8000 bytes.
    /// Exact object-ID matches are still considered (default true).
    pub approximate_binary: bool,
}

impl Options {
    /// Sets [`Self::similarity`].
    #[must_use]
    pub fn with_similarity(mut self, similarity: u8) -> Self {
        self.similarity = similarity;
        self
    }

    /// Sets [`Self::copies`].
    #[must_use]
    pub fn with_copies(mut self, copies: Copies) -> Self {
        self.copies = copies;
        self
    }

    /// Sets [`Self::track_empty`].
    ///
    /// ```
    /// use std::sync::atomic::AtomicBool;
    ///
    /// use girt::rewrites::Options;
    /// use girt::{EntryMode, InitKind, ObjectFormat, Repository, Tree, TreeEntry};
    ///
    /// let directory = tempfile::tempdir()?;
    /// let path = directory.path().join("r");
    /// let repo = Repository::init(ObjectFormat::Sha1, path, InitKind::Bare)?;
    ///
    /// let loose = repo.loose_objects();
    /// let entry = |name: &[u8], id, mode| TreeEntry {
    ///     name: name.to_vec(),
    ///     id,
    ///     mode,
    /// };
    /// let tree = |entries| loose.write_tree(&Tree::new(ObjectFormat::Sha1, entries)?);
    /// let cancel = AtomicBool::new(false);
    ///
    /// let id = loose.write_blob(b"")?;
    /// let old = tree(vec![entry(b"old", id, EntryMode::Blob)])?;
    /// let new = tree(vec![entry(b"new", id, EntryMode::Blob)])?;
    /// let objects = repo.objects_with(Default::default())?;
    /// assert!(
    ///     objects
    ///         .detect_rewrites(
    ///             Some(old),
    ///             Some(new),
    ///             Options::default().with_track_empty(false),
    ///             Default::default(),
    ///             None,
    ///             &cancel
    ///         )?
    ///         .is_empty()
    /// );
    /// let matches = objects.detect_rewrites(
    ///     Some(old),
    ///     Some(new),
    ///     Options::default(),
    ///     Default::default(),
    ///     None,
    ///     &cancel,
    /// )?;
    /// assert_eq!(matches.len(), 1);
    /// assert_eq!(matches[0].similarity, 100);
    /// // Empty content has no distinguishing evidence; choose whether such inferred moves are useful.
    /// assert_eq!(matches[0].kind, girt::rewrites::Kind::Rename);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn with_track_empty(mut self, track_empty: bool) -> Self {
        self.track_empty = track_empty;
        self
    }

    /// Sets [`Self::candidate_limit`].
    #[must_use]
    pub fn with_candidate_limit(mut self, candidate_limit: usize) -> Self {
        self.candidate_limit = candidate_limit;
        self
    }

    /// Sets [`Self::approximate_binary`].
    ///
    /// Disabling binary similarity does not remove those files from the candidate-limit
    /// calculation. A UI can therefore see an inexact skip even when its policy would not score
    /// the remaining pair.
    ///
    /// ```
    /// use std::sync::atomic::AtomicBool;
    ///
    /// use girt::rewrites::Options;
    /// use girt::{EntryMode, InitKind, ObjectFormat, Repository, Tree, TreeEntry};
    ///
    /// let directory = tempfile::tempdir()?;
    /// let path = directory.path().join("r");
    /// let repo = Repository::init(ObjectFormat::Sha1, path, InitKind::Bare)?;
    ///
    /// let loose = repo.loose_objects();
    /// let entry = |name: &[u8], id, mode| TreeEntry {
    ///     name: name.to_vec(),
    ///     id,
    ///     mode,
    /// };
    /// let tree = |entries| loose.write_tree(&Tree::new(ObjectFormat::Sha1, entries)?);
    /// let cancel = AtomicBool::new(false);
    ///
    /// let before = loose.write_blob(b"before\0binary")?;
    /// let after = loose.write_blob(b"after\0binary")?;
    /// let old = tree(vec![entry(b"old", before, EntryMode::Blob)])?;
    /// let new = tree(vec![entry(b"new", after, EntryMode::Blob)])?;
    /// let objects = repo.objects_with(Default::default())?;
    /// let options = Options::default()
    ///     .with_approximate_binary(false)
    ///     .with_candidate_limit(0);
    /// let skipped = objects.detect_rewrites_or_exact(
    ///     Some(old),
    ///     Some(new),
    ///     options,
    ///     Default::default(),
    ///     None,
    ///     &cancel,
    /// )?;
    /// assert!(skipped.rewrites.is_empty());
    /// assert!(skipped.inexact_skipped.is_some());
    /// let complete = objects.detect_rewrites_or_exact(
    ///     Some(old),
    ///     Some(new),
    ///     options.with_candidate_limit(1),
    ///     Default::default(),
    ///     None,
    ///     &cancel,
    /// )?;
    /// assert!(complete.rewrites.is_empty());
    /// assert!(complete.inexact_skipped.is_none());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn with_approximate_binary(mut self, approximate_binary: bool) -> Self {
        self.approximate_binary = approximate_binary;
        self
    }
}

impl Default for Options {
    fn default() -> Self {
        Self {
            similarity: 50,
            copies: Copies::Disabled,
            track_empty: true,
            candidate_limit: 1000,
            approximate_binary: true,
        }
    }
}

/// Resource bounds for a complete inference call, including its structural comparison.
///
/// Memory includes bounded tree comparison storage, retained blob bytes, at most one span per
/// payload byte, candidate pairs and output paths. Span keys have at most 64 bytes, with map-node
/// overhead; these bounds are not exact heap/RSS limits. Allocation failure follows Rust's
/// allocator behavior. No files are written and no handles remain owned by the result.
///
/// Exact-only fallback relaxes the candidate policy, not the independent byte, span, pair or work
/// budgets. Exact selection also charges [`Self::max_pairs`]; exhausting it returns an error from
/// both APIs, as this example demonstrates.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::rewrites::{Error, Limits, Options};
/// use girt::{EntryMode, InitKind, ObjectFormat, Repository, Tree, TreeEntry};
///
/// let directory = tempfile::tempdir()?;
/// let path = directory.path().join("r");
/// let repo = Repository::init(ObjectFormat::Sha1, path, InitKind::Bare)?;
///
/// let loose = repo.loose_objects();
/// let entry = |name: &[u8], id, mode| TreeEntry {
///     name: name.to_vec(),
///     id,
///     mode,
/// };
/// let tree = |entries| loose.write_tree(&Tree::new(ObjectFormat::Sha1, entries)?);
/// let cancel = AtomicBool::new(false);
///
/// let id = loose.write_blob(b"same")?;
/// let old = tree(vec![entry(b"old", id, EntryMode::Blob)])?;
/// let new = tree(vec![entry(b"new", id, EntryMode::Blob)])?;
/// let result = repo
///     .objects_with(Default::default())?
///     .detect_rewrites_or_exact(
///         Some(old),
///         Some(new),
///         Options::default().with_candidate_limit(0),
///         Limits::default().with_max_pairs(0),
///         None,
///         &cancel,
///     );
/// assert!(matches!(result, Err(Error::Limit("pairs"))));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Limits {
    /// Structural comparison bounds, including path and change counts.
    pub trees: TreeCompareLimits,
    /// Independent reconstruction bounds for each blob read.
    pub read: ReadLimits,
    /// Aggregate distinct candidate blob bytes retained (default 64 MiB).
    pub max_blob_bytes: usize,
    /// Maximum total span occurrences across cached candidate blobs (default 1,000,000).
    pub max_spans: usize,
    /// Maximum candidate pairs scored or considered for exact selection (default 1,000,000).
    pub max_pairs: usize,
    /// Conservative byte/lookup/comparison work budget (default 100,000,000).
    pub max_work: usize,
}

impl Limits {
    /// Sets [`Self::trees`].
    #[must_use]
    pub fn with_trees(mut self, trees: TreeCompareLimits) -> Self {
        self.trees = trees;
        self
    }

    /// Sets [`Self::read`].
    #[must_use]
    pub fn with_read(mut self, read: ReadLimits) -> Self {
        self.read = read;
        self
    }

    /// Sets [`Self::max_blob_bytes`].
    #[must_use]
    pub fn with_max_blob_bytes(mut self, max_blob_bytes: usize) -> Self {
        self.max_blob_bytes = max_blob_bytes;
        self
    }

    /// Sets [`Self::max_spans`].
    #[must_use]
    pub fn with_max_spans(mut self, max_spans: usize) -> Self {
        self.max_spans = max_spans;
        self
    }

    /// Sets [`Self::max_pairs`].
    #[must_use]
    pub fn with_max_pairs(mut self, max_pairs: usize) -> Self {
        self.max_pairs = max_pairs;
        self
    }

    /// Sets [`Self::max_work`].
    #[must_use]
    pub fn with_max_work(mut self, max_work: usize) -> Self {
        self.max_work = max_work;
        self
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            trees: TreeCompareLimits::default(),
            read: ReadLimits::default(),
            max_blob_bytes: 64 * 1024 * 1024,
            max_spans: 1_000_000,
            max_pairs: 1_000_000,
            max_work: 100_000_000,
        }
    }
}

/// How an inferred source is used in this result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Kind {
    /// The deleted source's first selected destination.
    Rename,
    /// A modified source or another destination reusing a deleted source.
    Copy,
}

impl Kind {
    /// Returns Git's `--name-status` letter: `R` for a rename and `C` for a copy.
    ///
    /// Git prints the letter followed by the three-digit [`Rewrite::similarity`], as in `R100`.
    #[must_use]
    pub fn letter(self) -> char {
        match self {
            Self::Rename => 'R',
            Self::Copy => 'C',
        }
    }
}

/// One inferred relationship, ordered by destination raw path bytes in returned results.
///
/// Exact object IDs score 100. Edited content is split at LF or after 64 significant bytes;
/// equal spans contribute the minimum occurrence count times span length, divided by the larger
/// raw payload length. Ordering of spans is immaterial. For text (no NUL in the first 8000 bytes),
/// CR immediately preceding LF is omitted. Binary spans preserve CR and all other bytes.
/// Percentages are rounded down; threshold comparison uses the unrounded fraction.
///
/// This independent byte-equality heuristic follows observed Git span behavior, but does not
/// reproduce every observed Git score or pairing shortcut. The repeated-byte discrepancy
/// remains under investigation; its cause has not been established. A score of 100 for edited
/// content can mean reordered spans, not identical bytes. `Options::similarity == 100` requires
/// identity instead. No finite compatibility corpus establishes universal heuristic parity.
///
/// # Postimage copies retain the original source identity
///
/// When a source is edited and its new content is copied, postimage policy can infer the copy. Its
/// score describes the postimage comparison; `source_id` still points at the old source snapshot.
/// Do not use that identity to reconstruct the scored input under postimage policy.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::rewrites::{Copies, Kind, Options};
/// use girt::{EntryMode, InitKind, ObjectFormat, Repository, Tree, TreeEntry};
///
/// let directory = tempfile::tempdir()?;
/// let path = directory.path().join("r");
/// let repo = Repository::init(ObjectFormat::Sha1, path, InitKind::Bare)?;
///
/// let loose = repo.loose_objects();
/// let entry = |name: &[u8], id, mode| TreeEntry {
///     name: name.to_vec(),
///     id,
///     mode,
/// };
/// let tree = |entries| loose.write_tree(&Tree::new(ObjectFormat::Sha1, entries)?);
/// let cancel = AtomicBool::new(false);
///
/// let before = loose.write_blob(b"before")?;
/// let after = loose.write_blob(b"after")?;
/// let old = tree(vec![entry(b"source", before, EntryMode::Blob)])?;
/// let new = tree(vec![
///     entry(b"source", after, EntryMode::Blob),
///     entry(b"copy", after, EntryMode::Blob),
/// ])?;
/// let records = repo.objects_with(Default::default())?.detect_rewrites(
///     Some(old),
///     Some(new),
///     Options::default()
///         .with_copies(Copies::ModifiedPostimage)
///         .with_similarity(100),
///     Default::default(),
///     None,
///     &cancel,
/// )?;
/// assert_eq!(records[0].kind, Kind::Copy);
/// assert_eq!(records[0].similarity, 100);
/// assert_eq!(records[0].source_id, before);
/// assert_eq!(records[0].target_id, after);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Rewrite {
    /// Original relative Git path bytes.
    pub source: Vec<u8>,
    /// Added relative Git path bytes.
    pub target: Vec<u8>,
    /// Original blob identity, including for a modified-source copy.
    pub source_id: ObjectId,
    /// Added blob identity.
    pub target_id: ObjectId,
    /// Rounded-down retained-byte percentage.
    pub similarity: u8,
    /// Rename or copy classification before target filtering.
    pub kind: Kind,
}

/// Inferred rewrites, with an explicit report when edited-content detection was skipped.
///
/// Returned by [`Objects::detect_rewrites_or_exact`](crate::Objects::detect_rewrites_or_exact).
///
/// Always inspect `inexact_skipped` before presenting the result as complete. A UI can retain
/// discovered pairs, leave all other additions/deletions unpaired, and offer a retry using
/// [`InexactSkipped::suggested_limit`]. The [fallback
/// example](crate::Objects::detect_rewrites_or_exact) shows the full lifecycle.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Detection {
    /// Inferred relationships, ordered by destination raw path bytes.
    ///
    /// When [`Self::inexact_skipped`] is set, these include exact and unique-basename matches.
    pub rewrites: Vec<Rewrite>,
    /// Set when [`Options::candidate_limit`] prevented exhaustive edited-content detection.
    ///
    /// `None` means detection ran to completion under the requested options.
    pub inexact_skipped: Option<InexactSkipped>,
}

/// Edited-content detection was skipped because too many candidates remained after exact and
/// unique-basename matching.
///
/// Remaining destinations stay unpaired, even where an edited source would match.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct InexactSkipped {
    /// Sources still available after exact and unique-basename matching, counted as
    /// [`Options::candidate_limit`] describes.
    pub sources: usize,
    /// Destinations remaining after exact and unique-basename matching, counted the same way.
    pub targets: usize,
    /// Caller-specified [`Options::candidate_limit`].
    pub limit: usize,
}

impl InexactSkipped {
    /// A [`Options::candidate_limit`] that permits edited detection for these candidates.
    ///
    /// This is the larger of the two counts, the value Git suggests for `diff.renameLimit`. It is
    /// sufficient but not always minimal: one source against three destinations needs only 2.
    ///
    /// The suggestion addresses candidate selection only. Independent byte, pair and work budgets
    /// in [`Limits`] can still refuse the retry.
    #[must_use]
    pub fn suggested_limit(&self) -> usize {
        self.sources.max(self.targets)
    }
}

/// Inference failed without returning partial records or modifying the repository.
///
/// Callers may raise an exhausted bound or retry cancellation with a cleared flag. Missing/corrupt
/// storage needs repair or a refreshed object view; retrying unchanged inputs does not repair it.
///
/// [`Error::Candidates`] is a policy refusal from the strict API; retry with a chosen larger
/// candidate limit or use [`crate::Objects::detect_rewrites_or_exact`] and report the skip.
/// [`Error::Limit`] instead means a resource budget failed, including during exact matching, and
/// neither API returns partial records. Invalid similarity is a caller error, not corrupt storage.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::rewrites::{Error, Limits, Options};
/// use girt::{InitKind, ObjectFormat, Repository};
/// let directory = tempfile::tempdir()?;
/// let repo = Repository::init(
///     ObjectFormat::Sha1,
///     directory.path().join("r"),
///     InitKind::Bare,
/// )?;
/// let result = repo.objects_with(Default::default())?.detect_rewrites(
///     None,
///     None,
///     Options::default().with_similarity(0),
///     Limits::default(),
///     None,
///     &AtomicBool::new(false),
/// );
/// assert!(matches!(result, Err(Error::Similarity(0))));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Similarity must be between 1 and 100 inclusive.
    #[error("rewrite similarity must be in 1..=100, got {0}")]
    Similarity(u8),
    /// Structural tree comparison failed.
    #[error("comparing rewrite trees")]
    Trees(#[from] TreeCompareError),
    /// A candidate blob could not be read or verified.
    #[error("reading rewrite blob {id}")]
    Read {
        /// Candidate identity.
        id: ObjectId,
        /// Storage failure, preserving its recovery classification.
        #[source]
        source: ObjectReadError,
    },
    /// Candidate object is missing.
    #[error("missing rewrite blob {0}")]
    Missing(ObjectId),
    /// Candidate object has a non-blob kind.
    #[error("rewrite object {id} is {actual:?}, not a blob")]
    NotBlob {
        /// Candidate identity.
        id: ObjectId,
        /// Verified object kind.
        actual: ObjectKind,
    },
    /// Edited detection would exceed the requested candidate limit after exact and unique-basename
    /// matching.
    ///
    /// Only [`Objects::detect_rewrites`](crate::Objects::detect_rewrites) returns this; see
    /// [`InexactSkipped`] for the fields.
    #[error("rewrite candidates ({sources} sources, {targets} targets) exceed limit {limit}")]
    Candidates {
        /// Eligible sources.
        sources: usize,
        /// Unpaired destinations.
        targets: usize,
        /// Caller-specified limit.
        limit: usize,
    },
    /// A named resource budget was exhausted; no partial result is returned.
    #[error("rewrite resource limit exhausted: {0}")]
    Limit(&'static str),
    /// Caller cancellation was observed.
    #[error("rewrite detection cancelled")]
    Cancelled,
}