lgwks_std 0.9.0

Everyday Rust primitives with no async runtime required: codecs, timestamps, ids, hashing, regex, JSON/RON/wire, HTTP, and default structured-debugging install. One audited stack per feature.
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
//! Pure similarity primitives with replaceable scoring seams.
//!
//! This module keeps deterministic lexical, structural, and geometric scores
//! behind [`Similarity`]. Each concrete scorer owns only its policy; callers
//! can replace one scorer without changing the code that combines or consumes
//! scores. The algorithms use `core` and `alloc` only, and all returned scores
//! are clamped to the contract's closed interval `[0.0, 1.0]`.
//!
//! [`Similarity`]: crate::similarity::Similarity

extern crate alloc;

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use core::marker::PhantomData;

/// A score-producing seam for one kind of comparable value.
pub trait Similarity {
    /// The value type accepted by this scorer.
    type Value: ?Sized;

    /// Scores how similar `left` and `right` are.
    ///
    /// Implementations return `1.0` for identical values and `0.0` for values
    /// with no similarity. Every result is finite and lies in `[0.0, 1.0]`.
    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64;
}

/// Why a bounded edit-distance calculation was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum EditDistanceError {
    /// At least one input exceeded the scorer's declared character bound.
    InputTooLong {
        /// The largest permitted input length.
        maximum: usize,
        /// The first observed length known to exceed `maximum`.
        observed: usize,
    },
}

impl fmt::Display for EditDistanceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::InputTooLong { maximum, observed } => write!(
                formatter,
                "similarity input length {observed} exceeds maximum {maximum}"
            ),
        }
    }
}

impl core::error::Error for EditDistanceError {}

/// Bounded Levenshtein similarity over normalized text.
///
/// Inputs are trimmed, internal whitespace is collapsed, and Unicode
/// lower-case expansion is applied before the edit distance is calculated.
/// The score is `1 - distance / max(input lengths)`, with two empty inputs
/// scoring `1.0`. The dynamic-programming row is bounded by
/// `maximum_length`, so hostile input is refused before the row is allocated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct EditDistance {
    /// The maximum raw character count accepted per input.
    maximum_length: usize,
}

impl EditDistance {
    /// Creates a scorer that accepts at most `maximum_length` input characters.
    #[must_use]
    pub const fn new(maximum_length: usize) -> Self {
        Self { maximum_length }
    }

    /// Returns the maximum number of raw input characters accepted per side.
    #[must_use]
    pub const fn maximum_length(&self) -> usize {
        self.maximum_length
    }

    /// Calculates the normalized score or reports an over-limit input.
    pub fn try_score(&self, left: &str, right: &str) -> Result<f64, EditDistanceError> {
        let left = normalize_text(left, self.maximum_length)?;
        let right = normalize_text(right, self.maximum_length)?;
        Ok(sequence_similarity(&left, &right))
    }
}

impl Similarity for EditDistance {
    type Value = str;

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        self.try_score(left, right).unwrap_or(0.0)
    }
}

/// A set-based Jaccard similarity scorer.
///
/// `T` is intentionally constrained only by equality. The implementation
/// treats duplicate entries as one set member and uses bounded pairwise scans,
/// so it needs no hashing policy or third-party dependency.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Jaccard<T = String> {
    /// Keeps the collection element type in the scorer's type identity.
    marker: PhantomData<fn() -> T>,
}

impl<T> Jaccard<T> {
    /// Creates a Jaccard scorer for collections of `T`.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            marker: PhantomData,
        }
    }
}

impl<T> Default for Jaccard<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: PartialEq> Similarity for Jaccard<T> {
    type Value = [T];

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        if left.is_empty() && right.is_empty() {
            return 1.0;
        }
        if left.is_empty() || right.is_empty() {
            return 0.0;
        }

        let left_unique = unique_count(left);
        let right_unique = unique_count(right);
        let intersection = left
            .iter()
            .enumerate()
            .filter(|item| {
                let index = item.0;
                let value = item.1;
                !left[..index].iter().any(|previous| previous == value)
                    && right.iter().any(|candidate| candidate == value)
            })
            .fold(0.0, |count, _| count + 1.0);
        let union = left_unique + right_unique - intersection;
        unit_score(intersection / union)
    }
}

/// Structural path similarity that ignores volatile identifiers and hashes.
///
/// Paths may use `/`, `>`, or whitespace as separators. Numeric segments and
/// generated-looking class/hash suffixes are discarded before a normalized
/// Levenshtein comparison of the remaining structural segments.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PathSimilarity;

impl PathSimilarity {
    /// Creates a structural path scorer.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl Similarity for PathSimilarity {
    type Value = str;

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        let left = normalized_path(left);
        let right = normalized_path(right);
        sequence_similarity(&left, &right)
    }
}

/// A normalized four-coordinate bounding box.
///
/// Coordinates are caller-defined normalized values, commonly fractions of a
/// viewport. No coordinate is silently clipped; [`Geometry`] handles
/// non-finite values by returning the safe lower score.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct BoundingBox {
    /// The normalized horizontal origin.
    x: f64,
    /// The normalized vertical origin.
    y: f64,
    /// The normalized width.
    width: f64,
    /// The normalized height.
    height: f64,
}

impl BoundingBox {
    /// Creates a bounding box from its normalized origin and dimensions.
    #[must_use]
    pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// Returns the normalized horizontal origin.
    #[must_use]
    pub const fn x(&self) -> f64 {
        self.x
    }

    /// Returns the normalized vertical origin.
    #[must_use]
    pub const fn y(&self) -> f64 {
        self.y
    }

    /// Returns the normalized width.
    #[must_use]
    pub const fn width(&self) -> f64 {
        self.width
    }

    /// Returns the normalized height.
    #[must_use]
    pub const fn height(&self) -> f64 {
        self.height
    }

    /// Returns coordinates in `(x, y, width, height)` order.
    ///
    /// Named `to_` rather than `as_` because it returns an owned array by value:
    /// the four coordinates are separate fields, so there is no contiguous
    /// array behind `&self` to borrow from, and the conversion therefore costs
    /// a copy rather than a reborrow.
    #[must_use]
    pub const fn to_array(&self) -> [f64; 4] {
        [self.x, self.y, self.width, self.height]
    }
}

impl From<[f64; 4]> for BoundingBox {
    fn from(values: [f64; 4]) -> Self {
        Self::new(values[0], values[1], values[2], values[3])
    }
}

impl From<BoundingBox> for [f64; 4] {
    fn from(value: BoundingBox) -> Self {
        value.to_array()
    }
}

/// Geometric similarity over normalized bounding boxes.
///
/// The Euclidean distance between the four coordinates is mapped with
/// `1 - distance / maximum_distance` and clamped to `[0.0, 1.0]`. A
/// non-positive or non-finite maximum is treated as an exact-match-only
/// policy, which keeps construction infallible and every score bounded.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct Geometry {
    /// The caller-supplied distance that maps to zero similarity.
    maximum_distance: f64,
}

impl Geometry {
    /// Creates a geometry scorer with the caller-supplied maximum distance.
    #[must_use]
    pub const fn new(maximum_distance: f64) -> Self {
        Self { maximum_distance }
    }

    /// Returns the maximum distance used for normalization.
    #[must_use]
    pub const fn maximum_distance(&self) -> f64 {
        self.maximum_distance
    }

    /// Scores two equal-shaped bounding-box values.
    ///
    /// The inherent method accepts either a `[f64; 4]` or a [`BoundingBox`].
    /// The [`Similarity`] implementation below uses `[f64; 4]` as the stable
    /// trait value, so the scorer can also be placed in [`Weighted`].
    #[must_use]
    pub fn score<Value>(&self, left: &Value, right: &Value) -> f64
    where
        Value: Copy + Into<[f64; 4]>,
    {
        let left = (*left).into();
        let right = (*right).into();
        geometry_score(self.maximum_distance, &left, &right)
    }
}

impl Similarity for Geometry {
    type Value = [f64; 4];

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        geometry_score(self.maximum_distance, left, right)
    }
}

/// Why a cosine similarity was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CosineError {
    /// The two vectors had different lengths.
    ///
    /// A dimension mismatch is a defect in whatever produced the vectors, not a
    /// pair of values that merely differ, so it is reported rather than scored
    /// as zero. Reporting `0.0` would make an inconsistent provider
    /// indistinguishable from two genuinely unrelated vectors.
    DimensionMismatch {
        /// Length of the left-hand vector.
        left: usize,
        /// Length of the right-hand vector.
        right: usize,
    },
    /// A vector had zero magnitude, so its angle is undefined.
    ///
    /// An all-zero vector is a direction that does not exist. It is reported
    /// apart from [`Self::NonFinite`] because the two have different causes and
    /// different repairs: a zero vector is usually an empty or padded input at
    /// the caller, where a non-finite one is a numeric fault inside whatever
    /// produced it.
    ZeroMagnitude,
    /// A vector carried a value that is not finite, so no angle can be computed.
    ///
    /// This is a *fourth* state behind a metric that most callers read as one
    /// number, and it needs to be its own variant rather than folded into
    /// [`Self::ZeroMagnitude`]. `NaN` compares `false` against everything,
    /// including itself, so a caller that lets one through a comparison reads
    /// "no measurement was possible" as "the measurement came out negative" —
    /// which is exactly the inference that must not be available. The
    /// accumulated sums are checked as well as the inputs, because a vector of
    /// finite values can still overflow to infinity.
    NonFinite,
}

impl fmt::Display for CosineError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::DimensionMismatch { left, right } => write!(
                formatter,
                "cosine vectors differ in length: {left} and {right}"
            ),
            Self::ZeroMagnitude => formatter.write_str("cosine vector has zero magnitude"),
            Self::NonFinite => formatter.write_str("cosine vector is not finite"),
        }
    }
}

impl core::error::Error for CosineError {}

/// Cosine similarity over dense `f32` vectors, as a model's embedding produces.
///
/// The dot product and both magnitudes accumulate in `f64` even though the
/// inputs are `f32`. Summing a few hundred `f32` products in `f32` loses
/// precision exactly where it matters — near the decision threshold, where two
/// candidates are close and the ordering is the answer. `f64::from` is exact,
/// so the wider accumulator costs nothing in fidelity and no cast.
///
/// The result is clamped to `[-1.0, 1.0]`: the arithmetic cannot leave that
/// interval, so a value outside it means the inputs were not finite, and
/// clamping keeps the metric inside the range every [`Similarity`] promises.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Cosine;

impl Cosine {
    /// Creates a cosine scorer.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }

    /// Calculates the cosine similarity, or reports why it is undefined.
    pub fn try_score(&self, left: &[f32], right: &[f32]) -> Result<f64, CosineError> {
        if left.len() != right.len() {
            return Err(CosineError::DimensionMismatch {
                left: left.len(),
                right: right.len(),
            });
        }
        let mut dot = 0.0_f64;
        let mut left_squared = 0.0_f64;
        let mut right_squared = 0.0_f64;
        for (left_value, right_value) in left.iter().zip(right) {
            let left_value = f64::from(*left_value);
            let right_value = f64::from(*right_value);
            // Checked before it is accumulated, so a `NaN` component is named
            // as what it is rather than surfacing later as a `NaN` magnitude
            // that a caller could mistake for an all-zero vector.
            if !left_value.is_finite() || !right_value.is_finite() {
                return Err(CosineError::NonFinite);
            }
            dot += left_value * right_value;
            left_squared += left_value * left_value;
            right_squared += right_value * right_value;
        }
        // Every `f32` is far below the smallest `f64` value whose square
        // overflows, so the per-component check above already implies these
        // sums are finite. The guard stays because it is the one that becomes
        // load-bearing if the element type ever widens, and because a `NaN`
        // accumulator would otherwise fall through `magnitudes <= 0.0` — `NaN`
        // compares false against everything — and return as a score.
        if !dot.is_finite() || !left_squared.is_finite() || !right_squared.is_finite() {
            return Err(CosineError::NonFinite);
        }
        let magnitudes = left_squared.sqrt() * right_squared.sqrt();
        if magnitudes <= 0.0 {
            return Err(CosineError::ZeroMagnitude);
        }
        Ok((dot / magnitudes).clamp(-1.0, 1.0))
    }
}

impl Similarity for Cosine {
    type Value = [f32];

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        self.try_score(left, right).unwrap_or(0.0)
    }
}

/// Why a weighted scorer could not be constructed.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum WeightedError {
    /// No component scorer was supplied.
    Empty,
    /// A component weight was negative or non-finite.
    InvalidWeight {
        /// Index of the invalid component.
        index: usize,
    },
    /// The component weights would produce a score above `1.0`.
    WeightSumExceedsOne,
    /// The acceptance threshold was outside the finite unit interval.
    InvalidThreshold,
}

impl fmt::Display for WeightedError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Empty => formatter.write_str("weighted similarity needs a component"),
            Self::InvalidWeight { index } => {
                write!(
                    formatter,
                    "weighted similarity has invalid weight at {index}"
                )
            }
            Self::WeightSumExceedsOne => {
                formatter.write_str("weighted similarity weights must sum to at most 1.0")
            }
            Self::InvalidThreshold => {
                formatter.write_str("weighted similarity threshold must be in [0.0, 1.0]")
            }
        }
    }
}

impl core::error::Error for WeightedError {}

/// A weighted composition of replaceable similarity scorers.
///
/// Components are evaluated as `sum(weight * score)`. Construction rejects an
/// empty component set, invalid weights, and totals above `1.0`, preserving the
/// range promised by [`Similarity`].
pub struct Weighted<Value: ?Sized> {
    /// Non-empty scorers and their bounded non-negative weights.
    components: Vec<(f64, Box<dyn Similarity<Value = Value>>)>,
    /// The score at or above which [`Self::is_accepted`] returns `true`.
    threshold: f64,
}

impl<Value: ?Sized> Weighted<Value> {
    /// Creates a weighted scorer and its acceptance threshold.
    pub fn new(
        components: Vec<(f64, Box<dyn Similarity<Value = Value>>)>,
        threshold: f64,
    ) -> Result<Self, WeightedError> {
        if components.is_empty() {
            return Err(WeightedError::Empty);
        }
        if !threshold.is_finite() || !(0.0..=1.0).contains(&threshold) {
            return Err(WeightedError::InvalidThreshold);
        }

        let mut total = 0.0;
        for (index, component) in components.iter().enumerate() {
            let weight = component.0;
            if !weight.is_finite() || weight < 0.0 {
                return Err(WeightedError::InvalidWeight { index });
            }
            total += weight;
        }
        if total > 1.0 {
            return Err(WeightedError::WeightSumExceedsOne);
        }

        Ok(Self {
            components,
            threshold,
        })
    }

    /// Returns the acceptance threshold.
    #[must_use]
    pub const fn threshold(&self) -> f64 {
        self.threshold
    }

    /// Scores the pair and reports whether it reaches the configured threshold.
    #[must_use]
    pub fn is_accepted(&self, left: &Value, right: &Value) -> bool {
        self.score(left, right) >= self.threshold
    }
}

impl<Value: ?Sized> core::fmt::Debug for Weighted<Value> {
    /// Reports the composition rather than the components.
    ///
    /// The component list is a set of `dyn Similarity` trait objects, so a
    /// derived `Debug` would print pointers instead of policy: the useful
    /// facts are how many scorers there are and where the acceptance line
    /// sits.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Weighted")
            .field("components", &self.components.len())
            .field("weights", &WeightList(self))
            .field("threshold", &self.threshold)
            .finish_non_exhaustive()
    }
}

/// The component weights, formatted in composition order.
struct WeightList<'a, Value: ?Sized>(&'a Weighted<Value>);

impl<Value: ?Sized> core::fmt::Debug for WeightList<'_, Value> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_list()
            .entries(self.0.components.iter().map(|component| component.0))
            .finish()
    }
}

impl<Value: ?Sized> Similarity for Weighted<Value> {
    type Value = Value;

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        let total = self.components.iter().fold(0.0, |sum, component| {
            sum + (component.0 * unit_score(component.1.score(left, right)))
        });
        unit_score(total)
    }
}

/// Converts a finite candidate into the similarity contract's unit interval.
fn unit_score(candidate: f64) -> f64 {
    if candidate.is_finite() {
        candidate.clamp(0.0, 1.0)
    } else {
        0.0
    }
}

/// Normalizes text without allocating until the raw bound has been checked.
fn normalize_text(input: &str, maximum: usize) -> Result<Vec<char>, EditDistanceError> {
    let mut observed = 0usize;
    for _ in input.chars() {
        observed = observed.saturating_add(1);
        if observed > maximum {
            return Err(EditDistanceError::InputTooLong { maximum, observed });
        }
    }

    let mut normalized = Vec::with_capacity(observed);
    let mut pending_space = false;
    for character in input.chars() {
        if character.is_whitespace() {
            if !normalized.is_empty() {
                pending_space = true;
            }
            continue;
        }
        if pending_space {
            normalized.push(' ');
            pending_space = false;
        }
        for lower in character.to_lowercase() {
            normalized.push(lower);
        }
    }

    if normalized.len() > maximum {
        return Err(EditDistanceError::InputTooLong {
            maximum,
            observed: normalized.len(),
        });
    }
    Ok(normalized)
}

/// Computes normalized Levenshtein similarity with one rolling row.
fn sequence_similarity<T: PartialEq>(left: &[T], right: &[T]) -> f64 {
    if left.is_empty() && right.is_empty() {
        return 1.0;
    }
    if left.is_empty() || right.is_empty() {
        return 0.0;
    }

    let (rows, columns) = if left.len() < right.len() {
        (left, right)
    } else {
        (right, left)
    };

    let mut previous: Vec<f64> = Vec::with_capacity(columns.len().saturating_add(1));
    let mut denominator = 0.0f64;
    previous.push(0.0);
    for _ in columns {
        denominator += 1.0;
        previous.push(denominator);
    }
    let mut current: Vec<f64> = vec![0.0; columns.len().saturating_add(1)];
    let mut row_distance = 1.0;
    for row_value in rows {
        current[0] = row_distance;
        for (column_index, column_value) in columns.iter().enumerate() {
            let cost = if row_value == column_value { 0.0 } else { 1.0 };
            let index = column_index.saturating_add(1);
            let deletion = previous[index] + 1.0;
            let insertion = current[column_index] + 1.0;
            let substitution = previous[column_index] + cost;
            current[index] = deletion.min(insertion).min(substitution);
        }
        core::mem::swap(&mut previous, &mut current);
        row_distance += 1.0;
    }

    unit_score(1.0 - (previous[columns.len()] / denominator))
}

/// Counts distinct values without requiring a hashing policy.
fn unique_count<T: PartialEq>(values: &[T]) -> f64 {
    values
        .iter()
        .enumerate()
        .filter(|item| {
            let index = item.0;
            let value = item.1;
            !values[..index].iter().any(|previous| previous == value)
        })
        .fold(0.0, |count, _| count + 1.0)
}

/// Removes path syntax and volatile segments while borrowing the input.
fn normalized_path(path: &str) -> Vec<&str> {
    let mut segments = Vec::new();
    for part in path.split(|character: char| {
        character == '/' || character == '\\' || character == '>' || character.is_whitespace()
    }) {
        for component in part.split(['#', '.']) {
            let component = component.trim();
            if !component.is_empty() && !is_volatile_segment(component) {
                segments.push(component);
            }
        }
    }
    segments
}

/// Recognizes numeric ids and common generated class/hash suffixes.
fn is_volatile_segment(segment: &str) -> bool {
    let bytes = segment.as_bytes();
    if bytes.is_empty() || bytes.iter().all(|byte| byte.is_ascii_digit()) {
        return true;
    }
    if bytes.len() >= 6 && bytes.iter().all(|byte| byte.is_ascii_hexdigit()) {
        return true;
    }

    let suffix_is_numeric =
        |suffix: &str| !suffix.is_empty() && suffix.bytes().all(|byte| byte.is_ascii_digit());
    let suffix_is_hash = |suffix: &str| {
        suffix.len() >= 6
            && suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())
            && suffix.bytes().any(|byte| byte.is_ascii_digit())
    };
    if let Some((_, suffix)) = segment.rsplit_once(['-', '_'])
        && (suffix_is_numeric(suffix) || suffix_is_hash(suffix))
    {
        return true;
    }
    ["css-", "sc-", "jsx-", "emotion-", "hash-"]
        .iter()
        .any(|prefix| {
            segment.strip_prefix(prefix).is_some_and(|suffix| {
                suffix.len() >= 4 && suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())
            })
        })
}

/// Computes normalized Euclidean similarity for four coordinates.
fn geometry_score(maximum_distance: f64, left: &[f64; 4], right: &[f64; 4]) -> f64 {
    let mut squared_distance = 0.0;
    for (left_value, right_value) in left.iter().zip(right.iter()) {
        let difference = *left_value - *right_value;
        if !difference.is_finite() {
            return 0.0;
        }
        squared_distance = difference.mul_add(difference, squared_distance);
        if !squared_distance.is_finite() {
            return 0.0;
        }
    }
    let distance = squared_distance.sqrt();
    if !distance.is_finite() {
        return 0.0;
    }
    if maximum_distance.is_finite() && maximum_distance > 0.0 {
        unit_score(1.0 - (distance / maximum_distance))
    } else if distance <= f64::EPSILON {
        1.0
    } else {
        0.0
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_unit(value: f64) {
        assert!(value.is_finite(), "similarity must be finite: {value}");
        assert!(
            (0.0..=1.0).contains(&value),
            "similarity outside [0, 1]: {value}"
        );
    }

    /// Compares floating-point outputs without relying on exact arithmetic.
    fn assert_close(actual: f64, expected: f64) {
        assert!(
            (actual - expected).abs() < 1e-12,
            "expected {expected}, got {actual}"
        );
    }

    /// Erases one edit scorer for a weighted composition without a cast.
    fn boxed_edit_distance(maximum_length: usize) -> Box<dyn Similarity<Value = str>> {
        Box::new(EditDistance::new(maximum_length))
    }

    #[test]
    fn edit_distance_handles_empty_and_identical_inputs() -> Result<(), EditDistanceError> {
        let scorer = EditDistance::new(16);
        assert_close(scorer.try_score("", "")?, 1.0);
        assert_close(scorer.try_score("same", "same")?, 1.0);
        assert_close(scorer.try_score("", "text")?, 0.0);
        assert_close(scorer.try_score("text", "")?, 0.0);
        assert_close(scorer.try_score("  SAME ", "same")?, 1.0);
        Ok(())
    }

    #[test]
    fn edit_distance_normalizes_known_distance() -> Result<(), EditDistanceError> {
        let scorer = EditDistance::new(16);
        let score = scorer.try_score("kitten", "sitting")?;
        assert!((score - (4.0 / 7.0)).abs() < 1e-12, "score was {score}");
        Ok(())
    }

    #[test]
    fn edit_distance_refuses_over_limit_inputs() -> Result<(), EditDistanceError> {
        let scorer = EditDistance::new(3);
        assert_close(scorer.try_score("abc", "abc")?, 1.0);
        assert!(matches!(
            scorer.try_score("four", "four"),
            Err(EditDistanceError::InputTooLong {
                maximum: 3,
                observed: 4
            })
        ));
        assert_close(scorer.score("four", "four"), 0.0);
        assert!(
            scorer.score("four", "four") <= 0.0,
            "the infallible trait method must map refusal to no similarity"
        );
        Ok(())
    }

    #[test]
    fn jaccard_handles_boundary_sets() {
        let scorer = Jaccard::<&str>::new();
        assert_close(scorer.score(&[], &[]), 1.0);
        assert_close(scorer.score(&["a", "b"], &["a", "b"]), 1.0);
        assert_close(scorer.score(&["a"], &["b"]), 0.0);
        assert_close(scorer.score(&["a", "a"], &["a"]), 1.0);
    }

    #[test]
    fn cosine_scores_known_angles() -> Result<(), CosineError> {
        let scorer = Cosine::new();
        // Identical direction, different magnitude: the magnitude cancels, and
        // that is the property that makes cosine the right metric for an
        // embedding, where a longer vector is not a closer one.
        assert_close(scorer.try_score(&[1.0, 2.0, 3.0], &[2.0, 4.0, 6.0])?, 1.0);
        assert_close(scorer.try_score(&[1.0, 0.0], &[0.0, 1.0])?, 0.0);
        assert_close(scorer.try_score(&[1.0, 0.0], &[-1.0, 0.0])?, -1.0);
        // 45 degrees: cos(pi/4).
        let diagonal = scorer.try_score(&[1.0, 0.0], &[1.0, 1.0])?;
        assert!((diagonal - core::f64::consts::FRAC_1_SQRT_2).abs() < 1e-12);
        Ok(())
    }

    #[test]
    fn cosine_refuses_a_dimension_mismatch_rather_than_scoring_zero() {
        let scorer = Cosine::new();
        assert!(matches!(
            scorer.try_score(&[1.0, 0.0], &[1.0, 0.0, 0.0]),
            Err(CosineError::DimensionMismatch { left: 2, right: 3 })
        ));
        // The infallible trait method still maps refusal to no similarity, so a
        // caller that ignores the typed error cannot read refusal as a match.
        assert_close(scorer.score(&[1.0, 0.0], &[1.0, 0.0, 0.0]), 0.0);
    }

    #[test]
    fn cosine_refuses_a_zero_magnitude_vector() {
        let scorer = Cosine::new();
        assert!(matches!(
            scorer.try_score(&[0.0, 0.0], &[1.0, 0.0]),
            Err(CosineError::ZeroMagnitude)
        ));
        assert!(matches!(
            scorer.try_score(&[], &[]),
            Err(CosineError::ZeroMagnitude)
        ));
    }

    #[test]
    fn cosine_names_a_non_finite_vector_apart_from_a_zero_magnitude_one() {
        let scorer = Cosine::new();
        // A `NaN` component on either side, and an infinity on either side. All
        // four are refused as `NonFinite`, not as `ZeroMagnitude`: the two have
        // different repairs, and reporting the wrong one sends the operator to
        // the wrong end of the pipeline.
        for (left, right) in [
            (&[f32::NAN, 1.0][..], &[1.0, 1.0][..]),
            (&[1.0, 1.0][..], &[f32::NAN, 1.0][..]),
            (&[f32::INFINITY, 1.0][..], &[1.0, 1.0][..]),
            (&[1.0, 1.0][..], &[1.0, f32::NEG_INFINITY][..]),
        ] {
            assert!(
                matches!(scorer.try_score(left, right), Err(CosineError::NonFinite)),
                "a non-finite vector must be refused as NonFinite: {left:?} {right:?}"
            );
        }
        // The distinction has to reach the operator, so it is carried by the
        // rendered message and not only by the variant name.
        assert_ne!(
            CosineError::NonFinite.to_string(),
            CosineError::ZeroMagnitude.to_string(),
            "the two refusals must not render identically"
        );
    }

    #[test]
    fn cosine_never_returns_a_non_finite_score_from_the_infallible_method() {
        let scorer = Cosine::new();
        // This is the property the typed error protects. A caller that reads
        // only the trait method gets `0.0` — "no similarity" — and never `NaN`,
        // which would compare false against every threshold and turn "we could
        // not measure this" into "this did not match".
        let score = scorer.score(&[f32::NAN, 1.0], &[1.0, 1.0]);
        assert!(score.is_finite(), "the infallible method returned {score}");
        assert_close(score, 0.0);
        assert_close(scorer.score(&[f32::INFINITY, 1.0], &[1.0, 1.0]), 0.0);
    }

    #[test]
    fn cosine_stays_inside_the_contract_interval() -> Result<(), CosineError> {
        let scorer = Cosine::new();
        // `f32::from(u16)` is lossless and needs no cast; the second vector is
        // the first scaled, so the two are the same direction by construction.
        let wide: Vec<f32> = (0_u16..64).map(f32::from).collect();
        let narrow: Vec<f32> = wide.iter().map(|value| value * 0.5).collect();
        for (left, right) in [(&wide, &narrow), (&narrow, &wide)] {
            let score = scorer.try_score(left, right)?;
            assert!(
                (-1.0..=1.0).contains(&score),
                "score {score} left the contract interval"
            );
        }
        assert_close(scorer.try_score(&wide, &narrow)?, 1.0);
        Ok(())
    }

    #[test]
    fn path_similarity_discards_volatile_segments() {
        let scorer = PathSimilarity::new();
        assert_close(
            scorer.score(
                "html/body/div/123/button.css-a1b2c3",
                "html/body/div/987/button.css-z9y8x7",
            ),
            1.0,
        );
        assert_close(scorer.score("root/left", "root/right"), 0.5);
        assert_close(scorer.score("", ""), 1.0);
        assert_close(scorer.score("left", "right"), 0.0);
    }

    #[test]
    fn geometry_maps_zero_and_maximum_distance() {
        let scorer = Geometry::new(2.0);
        let origin = [0.0, 0.0, 0.0, 0.0];
        let far = [2.0, 0.0, 0.0, 0.0];
        assert_close(scorer.score(&origin, &origin), 1.0);
        assert_close(scorer.score(&origin, &far), 0.0);
        assert_close(scorer.score(&origin, &[1.0, 0.0, 0.0, 0.0]), 0.5);
    }

    #[test]
    fn bounding_box_accessors_preserve_coordinates() {
        let box_value = BoundingBox::new(0.1, 0.2, 0.3, 0.4);
        assert_close(box_value.x(), 0.1);
        assert_close(box_value.y(), 0.2);
        assert_close(box_value.width(), 0.3);
        assert_close(box_value.height(), 0.4);
        for (actual, expected) in box_value.to_array().iter().zip([0.1, 0.2, 0.3, 0.4]) {
            assert_close(*actual, expected);
        }
    }

    #[test]
    fn weighted_rejects_empty_components() {
        let result = Weighted::<str>::new(Vec::new(), 0.5);
        assert!(matches!(result, Err(WeightedError::Empty)));
    }

    #[test]
    fn weighted_single_vector_returns_that_vectors_score() -> Result<(), WeightedError> {
        let direct = EditDistance::new(16);
        let weighted = Weighted::<str>::new(vec![(1.0, boxed_edit_distance(16))], 0.8)?;
        assert_close(
            weighted.score("kitten", "sitting"),
            direct.score("kitten", "sitting"),
        );
        assert!(!weighted.is_accepted("kitten", "sitting"));
        Ok(())
    }

    #[test]
    fn every_metric_stays_in_unit_interval_for_fixed_inputs() -> Result<(), WeightedError> {
        let edit = EditDistance::new(32);
        for (left, right) in [("", ""), ("a", "b"), ("short", "longer"), ("A B", "a b")] {
            assert_unit(edit.score(left, right));
        }

        let sets = Jaccard::<&str>::new();
        for (left, right) in [
            (&[][..], &[][..]),
            (&["a"][..], &["b"][..]),
            (&["a", "b"][..], &["b", "c"][..]),
        ] {
            assert_unit(sets.score(left, right));
        }

        let paths = PathSimilarity::new();
        for (left, right) in [("", ""), ("root/1", "root/2"), ("a", "b/c")] {
            assert_unit(paths.score(left, right));
        }

        let geometry = Geometry::new(1.0);
        for (left, right) in [
            ([0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]),
            ([0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0]),
            ([0.5, 0.5, 0.25, 0.25], [0.25, 0.25, 0.5, 0.5]),
        ] {
            assert_unit(geometry.score(&left, &right));
        }

        let weighted = Weighted::<str>::new(vec![(1.0, boxed_edit_distance(32))], 0.5)?;
        for (left, right) in [
            ("", ""),
            ("same", "same"),
            ("a", "b"),
            ("too long", "too long"),
        ] {
            assert_unit(weighted.score(left, right));
        }
        Ok(())
    }
}