hotspots 0.2.0

A lightweight Rust library for working with 2D rectangular hotspots with support for pixel and percentage-based coordinates
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
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
1010
1011
1012
1013
1014
1015
1016
1017
#![doc = include_str!("../README.md")]
#![no_std]

// ## TODO
// - Introduce utilites to make conversions between different origins easier.
// - Make the repr module almost fully internal and provide simple exported types - similar to the MPN crate.

pub mod repr;

#[cfg(feature = "serde")]
mod serde;

#[cfg(feature = "reflectapi")]
mod reflectapi;

use core::marker::PhantomData;

use repr::*;

/// Coordinate type definition.
///
/// Coordinates are stored as fractions of `CoordinateValue::MAX`. The u16 type
/// provides 65,536 discrete positions. For percentage-based hotspots, precision
/// loss occurs when image dimensions exceed this value (expect ~1-2 pixel
/// rounding on 100,000px images).
///
/// Enable the "high_precision" feature for images larger than ~65,000 pixels.
#[cfg(not(feature = "high_precision"))]
pub type CoordinateValue = u16;

/// Coordinate type definition.
///
/// Coordinates are stored as fractions of `CoordinateValue::MAX`. The u32 type
/// provides 4,294,967,296 discrete positions, sufficient for virtually all
/// image sizes without precision loss.
#[cfg(feature = "high_precision")]
pub type CoordinateValue = u32;

/// An internal type used for the result from multiplication between two
/// [`CoordinateValue`] to ensure no loss of precision.
#[cfg(not(feature = "high_precision"))]
#[doc(hidden)]
type InternalCalculationType = u32;

/// An internal type used for the result from multiplication between two
/// [`CoordinateValue`] to ensure no loss of precision.
#[cfg(feature = "high_precision")]
#[doc(hidden)]
type InternalCalculationType = u64;

/// A function which rounds two numbers to the closest value using integer divison.
#[inline]
const fn div_round_closest(
    dividend: InternalCalculationType,
    divider: InternalCalculationType,
) -> InternalCalculationType {
    (dividend + (divider / 2)) / divider
}

/// A const function which selects the smaller of two values.
///
/// Needed because Ord is not const-stable yet.
///
/// See: https://github.com/rust-lang/rust/issues/143874 for more information.
macro_rules! min {
    ($a:expr, $b:expr) => {{ if $a < $b { $a } else { $b } }};
}

/// A const function which selects the greater of two values.
///
/// Needed because Ord is not const-stable yet.
///
/// See: https://github.com/rust-lang/rust/issues/143874 for more information.
macro_rules! max {
    ($a:expr, $b:expr) => {{ if $a > $b { $a } else { $b } }};
}

/// A coordinate in 2 Dimensional space.
///
/// The coordinates contained in this struct are always non-negative and bounded
/// by the maximum allowed value based on the current precision settings. See
/// [`CoordinateValue`] for more details. The origin point should always be the
/// lower-left of the image.
///
/// Can store one of two internal representations:
/// - Pixel-based: Absolute pixel values relative to the image dimensions,
///   e.g., (150, 300).
/// - Percentage-based: Relative percentage values of the image dimensions,
///   e.g., (15.0%, 30.0%), stored as a percentage of the maximum value of
///   `CoordinateValue`.
///
/// x is the horizontal axis (left to right), y is the vertical axis (bottom to top).
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Coordinate {
    pub x: CoordinateValue,
    pub y: CoordinateValue,
}

/// The dimensions of an image.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ImageDimensions {
    pub width: CoordinateValue,
    pub height: CoordinateValue,
}

/// A rectangular hotspot represented as two `Coordinate`s: upper-right and lower-left.
///
/// The internal representation can be either pixel-based or percentage-based,
/// as indicated by the generic parameter `R`. By default, it uses pixel-based representation.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Hotspot<R = PixelRepr> {
    upper_right: Coordinate,
    lower_left: Coordinate,
    _repr: core::marker::PhantomData<R>,
}

impl Hotspot<PixelRepr> {
    #[inline]
    pub const fn upper_right(&self) -> Coordinate {
        self.upper_right
    }

    #[inline]
    pub const fn upper_left(&self) -> Coordinate {
        Coordinate {
            x: self.upper_right.x,
            y: self.lower_left.y,
        }
    }

    #[inline]
    pub const fn lower_left(&self) -> Coordinate {
        self.lower_left
    }

    #[inline]
    pub const fn lower_right(&self) -> Coordinate {
        Coordinate {
            x: self.lower_left.x,
            y: self.upper_right.y,
        }
    }

    #[inline]
    pub const fn as_percentage(
        this: Self,
        image_dimensions: ImageDimensions,
    ) -> Hotspot<PercentageRepr> {
        let Self {
            upper_right,
            lower_left,
            _repr: _,
        } = this;
        // TODO: technically not the most efficient because `from_percentage` performs a bunch of checks that we don't really need anymore.
        Hotspot::builder()
            .with_repr::<PercentageRepr>()
            .from_percentage((upper_right, lower_left), image_dimensions)
    }
}

impl Hotspot<PercentageRepr> {
    #[inline]
    pub const fn as_pixels(this: Self, image_dimensions: ImageDimensions) -> Hotspot<PixelRepr> {
        Hotspot {
            upper_right: this.upper_right(image_dimensions),
            lower_left: this.lower_left(image_dimensions),
            _repr: PhantomData,
        }
    }
}

impl Hotspot<PercentageRepr> {
    /// Get the upper-right coordinate in pixel values, given the image dimensions.
    ///
    /// This will take the internal percentage and multiply it against the
    /// height and width of the image to produce exact coordinates.
    ///
    /// Note that we will round to the closest pixel automatically.
    #[inline]
    pub const fn upper_right(
        &self,
        ImageDimensions { height, width }: ImageDimensions,
    ) -> Coordinate {
        let Coordinate { x, y } = self.upper_right;

        let x: CoordinateValue = div_round_closest(
            x as InternalCalculationType * width as InternalCalculationType,
            CoordinateValue::MAX as InternalCalculationType,
        ) as CoordinateValue;

        let y: CoordinateValue = div_round_closest(
            y as InternalCalculationType * height as InternalCalculationType,
            CoordinateValue::MAX as InternalCalculationType,
        ) as CoordinateValue;

        Coordinate { x, y }
    }

    /// Get the upper-left coordinate in pixel values, given the image dimensions.
    ///
    /// This will take the internal percentage and multiply it against the
    /// height and width of the image to produce exact coordinates.
    ///
    /// Note that we will round to the closest pixel automatically.
    #[inline]
    pub const fn upper_left(
        &self,
        ImageDimensions { height, width }: ImageDimensions,
    ) -> Coordinate {
        let Coordinate { x, y } = Coordinate {
            x: self.upper_right.x,
            y: self.lower_left.y,
        };

        let x: CoordinateValue = div_round_closest(
            x as InternalCalculationType * width as InternalCalculationType,
            CoordinateValue::MAX as InternalCalculationType,
        ) as CoordinateValue;

        let y: CoordinateValue = div_round_closest(
            y as InternalCalculationType * height as InternalCalculationType,
            CoordinateValue::MAX as InternalCalculationType,
        ) as CoordinateValue;

        Coordinate { x, y }
    }

    /// Get the lower-left coordinate in pixel values, given the image dimensions.
    ///
    /// This will take the internal percentage and multiply it against the
    /// height and width of the image to produce exact coordinates.
    ///
    /// Note that we will round to the closest pixel automatically.
    #[inline]
    pub const fn lower_left(
        &self,
        ImageDimensions { height, width }: ImageDimensions,
    ) -> Coordinate {
        let Coordinate { x, y } = self.lower_left;

        let x: CoordinateValue = div_round_closest(
            x as InternalCalculationType * width as InternalCalculationType,
            CoordinateValue::MAX as InternalCalculationType,
        ) as CoordinateValue;

        let y: CoordinateValue = div_round_closest(
            y as InternalCalculationType * height as InternalCalculationType,
            CoordinateValue::MAX as InternalCalculationType,
        ) as CoordinateValue;

        Coordinate { x, y }
    }

    /// Get the lower-right coordinate in pixel values, given the image dimensions.
    ///
    /// This will take the internal percentage and multiply it against the
    /// height and width of the image to produce exact coordinates.
    ///
    /// Note that we will round to the closest pixel automatically.
    #[inline]
    pub const fn lower_right(
        &self,
        ImageDimensions { height, width }: ImageDimensions,
    ) -> Coordinate {
        let Coordinate { x, y } = Coordinate {
            x: self.lower_left.x,
            y: self.upper_right.y,
        };

        let x: CoordinateValue = div_round_closest(
            x as InternalCalculationType * width as InternalCalculationType,
            CoordinateValue::MAX as InternalCalculationType,
        ) as CoordinateValue;

        let y: CoordinateValue = div_round_closest(
            y as InternalCalculationType * height as InternalCalculationType,
            CoordinateValue::MAX as InternalCalculationType,
        ) as CoordinateValue;

        Coordinate { x, y }
    }
}

impl<R> Hotspot<R> {
    /// Calculate the overlap between two hotspots as a value between 0 and 1
    /// where 0 is no overlap and 1 is complete overlap.
    ///
    /// Note that this implementation is not perfect for calculating e.g. if two
    /// hotspots should be merged becuase if the size of two hotspots are of
    /// very different sizes then this may not report much overlap at all.
    ///
    /// E.g.
    /// > h1: 0,0 to 20,20 (area 400) \
    /// > h2: 5,5 to 15,15 (area 100) \
    /// > intersection: 5,5 to 15,15 (area 100) \
    /// > union: 400 + 100 - 100 = 400 \
    /// > overlap: 100 / 400 = 0.25
    ///
    /// If you need to decide if one hotspot should be merged into another
    /// consider using the [`Hotspot::overlap_in`] function instead.
    pub const fn overlap(&self, other: &Self) -> f32 {
        // https://stackoverflow.com/questions/9324339/how-much-do-two-rectangles-overlap
        let Coordinate { x: xa2, y: ya2 } = self.upper_right;
        let Coordinate { x: xa1, y: ya1 } = self.lower_left;
        let Coordinate { x: xb2, y: yb2 } = other.upper_right;
        let Coordinate { x: xb1, y: yb1 } = other.lower_left;

        // Cast to InternalCalculationType to prevent overflow during area calculation
        let xa1 = xa1 as InternalCalculationType;
        let xa2 = xa2 as InternalCalculationType;
        let ya1 = ya1 as InternalCalculationType;
        let ya2 = ya2 as InternalCalculationType;
        let xb1 = xb1 as InternalCalculationType;
        let xb2 = xb2 as InternalCalculationType;
        let yb1 = yb1 as InternalCalculationType;
        let yb2 = yb2 as InternalCalculationType;

        // Calculate area of rectangle A
        let sa = (xa2 - xa1) * (ya2 - ya1);

        // Calculate area of rectangle B
        let sb = (xb2 - xb1) * (yb2 - yb1);

        // Calculate intersection dimensions
        // We use saturating_sub because if the rectangles are disjoint,
        // min(right) - max(left) would be negative (underflow in unsigned).
        let intersection_w = min!(xa2, xb2).saturating_sub(max!(xa1, xb1));
        let intersection_h = min!(ya2, yb2).saturating_sub(max!(ya1, yb1));

        // Calculate area of intersection
        let si = intersection_w * intersection_h;

        // Calculate area of union
        // We subtract the intersection from the sum of the two areas.
        // However, sa + sb can overflow InternalCalculationType if both are large (e.g. u32::MAX).
        // Since we are calculating a ratio (si / su), we can cast to f32 before summing to avoid overflow
        // and maintain precision for the division.
        let su = sa as f32 + sb as f32 - si as f32;

        // Handle zero area union to avoid NaN
        if su == 0.0 {
            return 0.0;
        }

        // Calculate overlap %
        si as f32 / su
    }

    /// Calculate the % of this Hotspot that is in the other hotspot, returns an
    /// f32 where 0 is no overlap and 1 is complete overlap.
    ///
    /// Differs from [`Hotspot::overlap`] in that instead of calculating the total area /
    /// by the overlap it will return the area of self that is overlapped by
    /// other - regardless of the remaining area of other.
    ///
    /// E.g.
    /// > h1: 0,0 to 20,20 (area 400) \
    /// > h2: 5,5 to 15,15 (area 100) \
    /// > intersection: 5,5 to 15,15 (area 100) \
    /// > union: 400 + 100 - 100 = 400 \
    /// > overlap: 100 / 400 = 1.0
    pub const fn overlap_in(&self, other: &Self) -> f32 {
        let Coordinate { x: xa2, y: ya2 } = self.upper_right;
        let Coordinate { x: xa1, y: ya1 } = self.lower_left;
        let Coordinate { x: xb2, y: yb2 } = other.upper_right;
        let Coordinate { x: xb1, y: yb1 } = other.lower_left;

        // Cast to InternalCalculationType to prevent overflow during area calculation
        let xa1 = xa1 as InternalCalculationType;
        let xa2 = xa2 as InternalCalculationType;
        let ya1 = ya1 as InternalCalculationType;
        let ya2 = ya2 as InternalCalculationType;
        let xb1 = xb1 as InternalCalculationType;
        let xb2 = xb2 as InternalCalculationType;
        let yb1 = yb1 as InternalCalculationType;
        let yb2 = yb2 as InternalCalculationType;

        // Calculate area of rectangle A (self)
        let sa = (xa2 - xa1) * (ya2 - ya1);

        // Calculate intersection dimensions
        // We use saturating_sub because if the rectangles are disjoint,
        // min(right) - max(left) would be negative (underflow in unsigned).
        let intersection_w = min!(xa2, xb2).saturating_sub(max!(xa1, xb1));
        let intersection_h = min!(ya2, yb2).saturating_sub(max!(ya1, yb1));

        // Calculate area of intersection
        let si = intersection_w * intersection_h;

        // Handle zero area self to avoid NaN
        if sa == 0 {
            return 0.0;
        }

        // Calculate overlap % relative to self
        si as f32 / sa as f32
    }

    /// Calculates the highest overlap between these two hotspots by taking the maximum value
    /// of calling [`Hotspot::overlap_in`] for each combination of self and other.
    #[inline]
    pub const fn max_overlap(&self, other: &Self) -> f32 {
        self.overlap_in(other).max(other.overlap_in(self))
    }

    /// Combines two hotspots and returns a new hotspot which will fully encompass the two provided hotspots.
    #[inline]
    pub const fn combine_hotspots(this: Self, other: Self) -> Self {
        Self {
            upper_right: Coordinate {
                x: max!(this.upper_right.x, other.upper_right.x),
                y: max!(this.upper_right.y, other.upper_right.y),
            },
            lower_left: Coordinate {
                x: min!(this.lower_left.x, other.lower_left.x),
                y: min!(this.lower_left.y, other.lower_left.y),
            },
            _repr: PhantomData,
        }
    }
}

/// A builder for creating hotspots.
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct HotspotBuilder<R> {
    _marker: PhantomData<R>,
}

impl core::fmt::Debug for HotspotBuilder<PixelRepr> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("HotspotBuilder")
            .field("kind", &"Pixel Representation")
            .finish()
    }
}

impl core::fmt::Debug for HotspotBuilder<PercentageRepr> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("HotspotBuilder")
            .field("kind", &"Percentage Representation")
            .finish()
    }
}

impl Hotspot {
    /// Create a builder for a hotspot.
    #[inline]
    pub const fn builder() -> HotspotBuilder<PixelRepr> {
        HotspotBuilder {
            _marker: core::marker::PhantomData,
        }
    }
}

impl<R: InternalRepr> HotspotBuilder<R> {
    /// Set the internal representation for the hotspot.
    #[inline]
    pub const fn with_repr<NewR: InternalRepr>(self) -> HotspotBuilder<NewR> {
        HotspotBuilder {
            _marker: core::marker::PhantomData,
        }
    }
}

impl HotspotBuilder<PixelRepr> {
    /// Create a pixel-based hotspot from top-left and bottom-right coordinates.
    ///
    /// NOTE: we assume that these are provided with the origin in the bottom left, e.g.
    ///
    /// X is expected to be up/down (i.e. vertical), Y is expected to be left/right (i.e. Horizontal).
    #[inline]
    pub const fn from_pixels(
        self,
        (Coordinate { x: x1, y: y1 }, Coordinate { x: x2, y: y2 }): (Coordinate, Coordinate),
    ) -> Hotspot<PixelRepr> {
        let upper_right = Coordinate {
            x: max!(x1, x2),
            y: max!(y1, y2),
        };

        let lower_left = Coordinate {
            x: min!(x1, x2),
            y: min!(y1, y2),
        };

        Hotspot {
            upper_right,
            lower_left,
            _repr: core::marker::PhantomData,
        }
    }
}

impl HotspotBuilder<PercentageRepr> {
    /// Create a percentage-based hotspot from top-left and bottom-right coordinates and image dimensions.
    #[inline]
    pub const fn from_percentage(
        self,
        input: (Coordinate, Coordinate),
        ImageDimensions { height, width }: ImageDimensions,
    ) -> Hotspot<PercentageRepr> {
        // Use the HotspotBuilder<PixelRepr>::from_pixel representation to handle
        // which point is which.
        let Hotspot {
            upper_right,
            lower_left,
            _repr: _,
        } = Hotspot::<PixelRepr>::builder().from_pixels(input);

        let height = height as InternalCalculationType;
        let width = width as InternalCalculationType;

        // Convert the pixel coordinates to internal percentages of the maximum possible value.
        let upper_right = Coordinate {
            x: div_round_closest(
                upper_right.x as InternalCalculationType
                    * CoordinateValue::MAX as InternalCalculationType,
                width,
            ) as CoordinateValue,
            y: div_round_closest(
                upper_right.y as InternalCalculationType
                    * CoordinateValue::MAX as InternalCalculationType,
                height,
            ) as CoordinateValue,
        };
        let lower_left = Coordinate {
            x: div_round_closest(
                lower_left.x as InternalCalculationType
                    * CoordinateValue::MAX as InternalCalculationType,
                width,
            ) as CoordinateValue,
            y: div_round_closest(
                lower_left.y as InternalCalculationType
                    * CoordinateValue::MAX as InternalCalculationType,
                height,
            ) as CoordinateValue,
        };

        Hotspot {
            upper_right,
            lower_left,
            _repr: core::marker::PhantomData,
        }
    }
}

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

    extern crate alloc;
    use alloc::format;

    #[cfg(not(feature = "high_precision"))]
    #[test]
    fn test_percentage_repr() {
        let hotspot = Hotspot::builder()
            .with_repr::<PercentageRepr>()
            .from_percentage(
                (Coordinate { x: 50, y: 50 }, Coordinate { x: 2622, y: 2622 }),
                crate::ImageDimensions {
                    height: 5000,
                    width: 5000,
                },
            );

        assert_eq!(hotspot.upper_right, Coordinate { x: 34367, y: 34367 });
        assert_eq!(hotspot.lower_left, Coordinate { x: 655, y: 655 });

        assert_eq!(
            hotspot.upper_right(crate::ImageDimensions {
                height: 5000,
                width: 5000,
            }),
            Coordinate { x: 2622, y: 2622 }
        );

        assert_eq!(
            hotspot.lower_right(crate::ImageDimensions {
                height: 10000,
                width: 5000,
            }),
            Coordinate { x: 50, y: 5244 }
        );

        assert_eq!(
            hotspot.upper_left(crate::ImageDimensions {
                height: 5000,
                width: 5000,
            }),
            Coordinate { x: 2622, y: 50 }
        );

        assert_eq!(
            hotspot.upper_right(crate::ImageDimensions {
                height: 10000,
                width: 5000,
            }),
            Coordinate { x: 2622, y: 5244 }
        );
    }

    #[cfg(feature = "high_precision")]
    #[test]
    fn test_percentage_repr() {
        let hotspot = Hotspot::builder()
            .with_repr::<PercentageRepr>()
            .from_percentage(
                (Coordinate { x: 50, y: 50 }, Coordinate { x: 2622, y: 2622 }),
                crate::ImageDimensions {
                    height: 5000,
                    width: 5000,
                },
            );

        assert_eq!(
            hotspot.upper_right,
            Coordinate {
                x: 2252280849,
                y: 2252280849
            }
        );
        assert_eq!(
            hotspot.lower_left,
            Coordinate {
                x: 42949673,
                y: 42949673
            }
        );

        assert_eq!(
            hotspot.upper_right(crate::ImageDimensions {
                height: 5000,
                width: 5000,
            }),
            Coordinate { x: 2622, y: 2622 }
        );

        assert_eq!(
            hotspot.lower_right(crate::ImageDimensions {
                height: 10000,
                width: 5000,
            }),
            Coordinate { x: 50, y: 5244 }
        );

        assert_eq!(
            hotspot.upper_left(crate::ImageDimensions {
                height: 5000,
                width: 5000,
            }),
            Coordinate { x: 2622, y: 50 }
        );

        assert_eq!(
            hotspot.upper_right(crate::ImageDimensions {
                height: 10000,
                width: 5000,
            }),
            Coordinate { x: 2622, y: 5244 }
        );
    }

    fn make_hotspot(x1: u16, y1: u16, x2: u16, y2: u16) -> Hotspot<PixelRepr> {
        Hotspot::builder().from_pixels((
            Coordinate {
                x: x1 as CoordinateValue,
                y: y1 as CoordinateValue,
            },
            Coordinate {
                x: x2 as CoordinateValue,
                y: y2 as CoordinateValue,
            },
        ))
    }

    #[test]
    fn test_no_overlap() {
        let h1 = make_hotspot(0, 0, 10, 10);
        let h2 = make_hotspot(20, 20, 30, 30);
        assert_eq!(h1.overlap(&h2), 0.0);
    }

    #[test]
    fn test_complete_overlap() {
        let h1 = make_hotspot(0, 0, 10, 10);
        let h2 = make_hotspot(0, 0, 10, 10);
        assert_eq!(h1.overlap(&h2), 1.0);
    }

    #[test]
    fn test_partial_overlap() {
        // h1: 0,0 to 10,10 (area 100)
        // h2: 5,0 to 15,10 (area 100)
        // intersection: 5,0 to 10,10 (width 5, height 10, area 50)
        // union: 100 + 100 - 50 = 150
        // overlap: 50 / 150 = 1/3
        let h1 = make_hotspot(0, 0, 10, 10);
        let h2 = make_hotspot(5, 0, 15, 10);
        assert!((h1.overlap(&h2) - (1.0 / 3.0)).abs() < f32::EPSILON);
    }

    #[test]
    fn test_contained_overlap() {
        // h1: 0,0 to 20,20 (area 400)
        // h2: 5,5 to 15,15 (area 100)
        // intersection: 5,5 to 15,15 (area 100)
        // union: 400 + 100 - 100 = 400
        // overlap: 100 / 400 = 0.25
        let h1 = make_hotspot(0, 0, 20, 20);
        let h2 = make_hotspot(5, 5, 15, 15);
        assert_eq!(h1.overlap(&h2), 0.25);

        assert_eq!(h2.overlap_in(&h1), 1.0);
        assert_eq!(h1.overlap_in(&h2), 0.25);
    }

    #[test]
    fn test_corner_overlap() {
        // h1: 0,0 to 10,10 (area 100)
        // h2: 5,5 to 15,15 (area 100)
        // intersection: 5,5 to 10,10 (width 5, height 5, area 25)
        // union: 100 + 100 - 25 = 175
        // overlap: 25 / 175 = 1/7
        let h1 = make_hotspot(0, 0, 10, 10);
        let h2 = make_hotspot(5, 5, 15, 15);
        assert!((h1.overlap(&h2) - (1.0 / 7.0)).abs() < f32::EPSILON);
    }

    #[test]
    fn test_zero_area() {
        let h1 = make_hotspot(0, 0, 0, 0);
        let h2 = make_hotspot(0, 0, 10, 10);
        assert_eq!(h1.overlap(&h2), 0.0);

        let h1 = make_hotspot(0, 0, 0, 0);
        let h2 = make_hotspot(0, 0, 0, 0);
        assert_eq!(h1.overlap(&h2), 0.0);
    }

    #[test]
    fn test_overflow() {
        let h1 = make_hotspot(0, 0, u16::MAX, u16::MAX);
        let h2 = make_hotspot(0, 0, u16::MAX, u16::MAX);
        assert_eq!(h1.overlap(&h2), 1.0);
    }

    #[test]
    fn test_from_pixels_equal_coordinates() {
        // Test when x1 == x2 and y1 == y2 (single point)
        let h1 = make_hotspot(5, 5, 5, 5);
        assert_eq!(h1.lower_left, Coordinate { x: 5, y: 5 });
        assert_eq!(h1.upper_right, Coordinate { x: 5, y: 5 });

        // Test when x1 == x2 but y1 != y2 (vertical line)
        let h2 = make_hotspot(5, 0, 5, 10);
        assert_eq!(h2.lower_left, Coordinate { x: 5, y: 0 });
        assert_eq!(h2.upper_right, Coordinate { x: 5, y: 10 });

        // Test when y1 == y2 but x1 != x2 (horizontal line)
        let h3 = make_hotspot(0, 5, 10, 5);
        assert_eq!(h3.lower_left, Coordinate { x: 0, y: 5 });
        assert_eq!(h3.upper_right, Coordinate { x: 10, y: 5 });

        // Test with reversed coordinates (x2 < x1, y2 < y1)
        let h4 = make_hotspot(10, 10, 0, 0);
        assert_eq!(h4.lower_left, Coordinate { x: 0, y: 0 });
        assert_eq!(h4.upper_right, Coordinate { x: 10, y: 10 });
    }

    #[test]
    fn test_from_pixels_strict_inequality_logic() {
        // Test that the implementation uses strict < and > (not <= and >=)
        // by verifying behavior for all orderings including adjacent values

        // When x1 < x2: lower_left should get x1, upper_right should get x2
        let h = make_hotspot(5, 7, 6, 8);
        assert_eq!(h.lower_left.x, 5);
        assert_eq!(h.lower_left.y, 7);
        assert_eq!(h.upper_right.x, 6);
        assert_eq!(h.upper_right.y, 8);

        // When x1 > x2: lower_left should get x2, upper_right should get x1
        let h = make_hotspot(10, 20, 9, 19);
        assert_eq!(h.lower_left.x, 9);
        assert_eq!(h.lower_left.y, 19);
        assert_eq!(h.upper_right.x, 10);
        assert_eq!(h.upper_right.y, 20);

        // Test exhaustively with small values to cover all branches
        for x1 in 0u16..15 {
            for x2 in 0u16..15 {
                let h = make_hotspot(x1, 0, x2, 0);

                // Verify the correct value is in each position
                if x1 < x2 {
                    assert_eq!(h.lower_left.x, x1 as CoordinateValue);
                    assert_eq!(h.upper_right.x, x2 as CoordinateValue);
                } else {
                    assert_eq!(h.lower_left.x, x2 as CoordinateValue);
                    assert_eq!(h.upper_right.x, x1 as CoordinateValue);
                }
            }
        }

        // Same for y coordinates
        for y1 in 0u16..15 {
            for y2 in 0u16..15 {
                let h = make_hotspot(0, y1, 0, y2);

                if y1 < y2 {
                    assert_eq!(h.lower_left.y, y1 as CoordinateValue);
                    assert_eq!(h.upper_right.y, y2 as CoordinateValue);
                } else {
                    assert_eq!(h.lower_left.y, y2 as CoordinateValue);
                    assert_eq!(h.upper_right.y, y1 as CoordinateValue);
                }
            }
        }
    }

    #[test]
    fn test_max_overlap_symmetric() {
        // Test max_overlap with identical hotspots
        let h1 = make_hotspot(0, 0, 10, 10);
        let h2 = make_hotspot(0, 0, 10, 10);
        assert_eq!(h1.max_overlap(&h2), 1.0);
    }

    #[test]
    fn test_max_overlap_no_overlap() {
        // Test max_overlap with non-overlapping hotspots
        let h1 = make_hotspot(0, 0, 10, 10);
        let h2 = make_hotspot(20, 20, 30, 30);
        assert_eq!(h1.max_overlap(&h2), 0.0);
    }

    #[test]
    fn test_max_overlap_contained() {
        // h1: 0,0 to 20,20 (area 400)
        // h2: 5,5 to 15,15 (area 100)
        // h1.overlap_in(h2) = 100/400 = 0.25
        // h2.overlap_in(h1) = 100/100 = 1.0
        // max_overlap should return 1.0
        let h1 = make_hotspot(0, 0, 20, 20);
        let h2 = make_hotspot(5, 5, 15, 15);
        assert_eq!(h1.max_overlap(&h2), 1.0);
    }

    #[test]
    fn test_max_overlap_partial() {
        // h1: 0,0 to 10,10 (area 100)
        // h2: 5,0 to 15,10 (area 100)
        // intersection: 5,0 to 10,10 (area 50)
        // h1.overlap_in(h2) = 50/100 = 0.5
        // h2.overlap_in(h1) = 50/100 = 0.5
        // max_overlap should return 0.5
        let h1 = make_hotspot(0, 0, 10, 10);
        let h2 = make_hotspot(5, 0, 15, 10);
        assert_eq!(h1.max_overlap(&h2), 0.5);
    }

    #[test]
    fn test_debug_impls() {
        let pixel_builder = Hotspot::builder();
        assert_eq!(
            format!("{:?}", pixel_builder),
            "HotspotBuilder { kind: \"Pixel Representation\" }"
        );

        let percentage_builder = Hotspot::builder().with_repr::<PercentageRepr>();
        assert_eq!(
            format!("{:?}", percentage_builder),
            "HotspotBuilder { kind: \"Percentage Representation\" }"
        );
    }

    // Property-based tests (fuzzing)
    #[cfg(not(miri))]
    mod fuzz_tests {
        use super::*;
        use proptest::prelude::*;

        prop_compose! {
            fn arb_coordinate()(x in 0..CoordinateValue::MAX, y in 0..CoordinateValue::MAX) -> Coordinate {
                Coordinate { x, y }
            }
        }

        prop_compose! {
            fn arb_hotspot()(c1 in arb_coordinate(), c2 in arb_coordinate()) -> Hotspot<PixelRepr> {
                Hotspot::builder().from_pixels((c1, c2))
            }
        }

        prop_compose! {
            fn arb_dimensions()(
                width in 1..CoordinateValue::MAX,
                height in 1..CoordinateValue::MAX
            ) -> ImageDimensions {
                ImageDimensions { width, height }
            }
        }

        proptest! {
            #[test]
            fn fuzz_from_pixels_invariants(c1 in arb_coordinate(), c2 in arb_coordinate()) {
                let h = Hotspot::builder().from_pixels((c1, c2));

                // Invariant: lower_left should have smaller or equal coordinates
                prop_assert!(h.lower_left.x <= h.upper_right.x);
                prop_assert!(h.lower_left.y <= h.upper_right.y);

                // Test the exact branching logic for each coordinate
                // For lower_left: should use the branch `if x1 < x2 { x1 } else { x2 }`
                let expected_lower_x = if c1.x < c2.x { c1.x } else { c2.x };
                let expected_lower_y = if c1.y < c2.y { c1.y } else { c2.y };
                prop_assert_eq!(h.lower_left.x, expected_lower_x);
                prop_assert_eq!(h.lower_left.y, expected_lower_y);

                // For upper_right: should use the branch `if x1 > x2 { x1 } else { x2 }`
                let expected_top_x = if c1.x > c2.x { c1.x } else { c2.x };
                let expected_top_y = if c1.y > c2.y { c1.y } else { c2.y };
                prop_assert_eq!(h.upper_right.x, expected_top_x);
                prop_assert_eq!(h.upper_right.y, expected_top_y);
            }

            #[test]
            fn fuzz_overlap_symmetry(h1 in arb_hotspot(), h2 in arb_hotspot()) {
                let o1 = h1.overlap(&h2);
                let o2 = h2.overlap(&h1);
                prop_assert!((o1 - o2).abs() < f32::EPSILON);
            }

            #[test]
            fn fuzz_overlap_bounds(h1 in arb_hotspot(), h2 in arb_hotspot()) {
                let o = h1.overlap(&h2);
                prop_assert!(o >= 0.0);
                prop_assert!(o <= 1.0);
            }

            #[test]
            fn fuzz_overlap_in_bounds(h1 in arb_hotspot(), h2 in arb_hotspot()) {
                let o = h1.overlap_in(&h2);
                prop_assert!(o >= 0.0);
                prop_assert!(o <= 1.0);
            }

            #[test]
            fn fuzz_combine_hotspots_containment(h1 in arb_hotspot(), h2 in arb_hotspot()) {
                let combined = Hotspot::combine_hotspots(h1, h2);

                // Check h1 is inside
                prop_assert!(combined.upper_right.x >= h1.upper_right.x);
                prop_assert!(combined.upper_right.y >= h1.upper_right.y);
                prop_assert!(combined.lower_left.x <= h1.lower_left.x);
                prop_assert!(combined.lower_left.y <= h1.lower_left.y);

                // Check h2 is inside
                prop_assert!(combined.upper_right.x >= h2.upper_right.x);
                prop_assert!(combined.upper_right.y >= h2.upper_right.y);
                prop_assert!(combined.lower_left.x <= h2.lower_left.x);
                prop_assert!(combined.lower_left.y <= h2.lower_left.y);
            }

            #[test]
            fn fuzz_combine_hotspots_overlap_in(h1 in arb_hotspot(), h2 in arb_hotspot()) {
                let combined = Hotspot::combine_hotspots(h1, h2);

                let h1_area = (h1.upper_right.x - h1.lower_left.x) as InternalCalculationType * (h1.upper_right.y - h1.lower_left.y) as InternalCalculationType;
                if h1_area > 0 {
                    prop_assert!((h1.overlap_in(&combined) - 1.0).abs() < 1e-5);
                }

                let h2_area = (h2.upper_right.x - h2.lower_left.x) as InternalCalculationType * (h2.upper_right.y - h2.lower_left.y) as InternalCalculationType;
                if h2_area > 0 {
                    prop_assert!((h2.overlap_in(&combined) - 1.0).abs() < 1e-5);
                }
            }

            #[test]
            fn fuzz_percentage_roundtrip(
                h in arb_hotspot(),
                dims in arb_dimensions()
            ) {
                // Constrain hotspot to be within dimensions for valid percentage calculation
                let h_constrained = Hotspot::builder().from_pixels((
                    Coordinate {
                        x: h.lower_left.x % dims.width,
                        y: h.lower_left.y % dims.height
                    },
                    Coordinate {
                        x: h.upper_right.x % dims.width,
                        y: h.upper_right.y % dims.height
                    }
                ));

                let p = Hotspot::as_percentage(h_constrained, dims);
                let back = Hotspot::as_pixels(p, dims);

                // Calculate tolerance based on precision loss from u16 scaling
                let tolerance_x = (dims.width as f64 / u16::MAX as f64).ceil() as CoordinateValue + 1;
                let tolerance_y = (dims.height as f64 / u16::MAX as f64).ceil() as CoordinateValue + 1;

                let diff_x1 = back.lower_left.x.abs_diff(h_constrained.lower_left.x);
                let diff_y1 = back.lower_left.y.abs_diff(h_constrained.lower_left.y);
                let diff_x2 = back.upper_right.x.abs_diff(h_constrained.upper_right.x);
                let diff_y2 = back.upper_right.y.abs_diff(h_constrained.upper_right.y);

                prop_assert!(diff_x1 <= tolerance_x);
                prop_assert!(diff_y1 <= tolerance_y);
                prop_assert!(diff_x2 <= tolerance_x);
                prop_assert!(diff_y2 <= tolerance_y);
            }
        }
    }
}