bounding_box 0.4.2

A library for rectilinear, 2-dimensional bounding boxes
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
/*!
[`ToBoundingBox`]: crate::ToBoundingBox
[`BoundingBox`]: crate::BoundingBox
[`contains_point`]: crate::BoundingBox::contains_point
[`approx_contains_point`]: crate::BoundingBox::approx_contains_point

A library for rectilinear, 2-dimensional bounding boxes.

 */
#![doc = include_str!("../docs/main.md")]
#![deny(missing_docs)]

#[cfg(feature = "approx")]
use approx::ulps_eq;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/**
A rectilinear, 2-dimensional [bounding box](https://en.wikipedia.org/wiki/Minimum_bounding_rectangle).

A 2-dimensional rectilinear bounding box is described by four values: minimum
x-value, maximum x-value, minimum y-value and and maximum y-value. This struct
can be created either from any type which implements [`Into<BoundingBox>`] or
from the constructors [`new`](BoundingBox::new) or
[`try_new`](BoundingBox::try_new). The values defining a bounding box (`xmin`,
`xmax`, `ymin`, `ymax`) are called "extremas".

Since a bounding box only consists of four f64 values (32 bytes), it is cheap to
copy, hence it implements the
[`Copy`](https://doc.rust-lang.org/std/marker/trait.Copy.html) trait.

# Features

This struct can be serialized / deserialized if the `serde` feature is enabled.
 */
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BoundingBox {
    xmin: f64,
    xmax: f64,
    ymin: f64,
    ymax: f64,
}

impl BoundingBox {
    /**
    Generates a bounding box from minimum and maximum x- and y-values.

    # Panics
    Panics if `xmin > xmax` or if `ymin > ymax`.

    # Examples

    ```
    use bounding_box::BoundingBox;

    let _ = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    ```

    This example panics because `xmin > xmax`.

    ```should_panic
    use bounding_box::BoundingBox;

    let _ = BoundingBox::new(2.0, 1.0, 0.0, 1.0);
    ```
     */
    pub fn new(xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Self {
        return Self::try_new(xmin, xmax, ymin, ymax)
            .expect("one of the conditions xmin <= xmax and ymin <= ymax is not fulfilled");
    }

    /**
    Like [`BoundingBox::new`], but returns `None` instead of panicking if `xmin > xmax` or if `ymin > ymax`.

    # Examples

    ```
    use bounding_box::BoundingBox;

    assert!(BoundingBox::try_new(0.0, 1.0, 0.0, 1.0).is_some());
    assert!(BoundingBox::try_new(2.0, 1.0, 0.0, 1.0).is_none());
    ```
     */
    pub fn try_new(xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Option<Self> {
        if xmin > xmax || ymin > ymax {
            return None;
        }
        return Some(BoundingBox {
            xmin,
            xmax,
            ymin,
            ymax,
        });
    }

    /**
    Returns the minimum x-value of the bounding box.
     */
    pub fn xmin(&self) -> f64 {
        return self.xmin;
    }

    /**
    Returns the maximum x-value of the bounding box.
     */
    pub fn xmax(&self) -> f64 {
        return self.xmax;
    }

    /**
    Returns the minimum y-value of the bounding box.
     */
    pub fn ymin(&self) -> f64 {
        return self.ymin;
    }

    /**
    Returns the maximum y-value of the bounding box.
     */
    pub fn ymax(&self) -> f64 {
        return self.ymax;
    }

    /**
    Fallible sets a new value for `xmin`. If the new value is bigger than `xmax`, the old value is left unchanged
    and this function returns `false`. Otherwise, it returns `true` and the old value is replaced by the new value.

    # Examples

    ```
    use bounding_box::BoundingBox;

    let mut bb = BoundingBox::new(0.0, 1.0, 0.0, 1.0);

    assert_eq!(bb.xmin(), 0.0);
    assert!(bb.try_set_xmin(0.5));
    assert_eq!(bb.xmin(), 0.5);

    assert!(!bb.try_set_xmin(1.5));
    assert_eq!(bb.xmin(), 0.5);
    ```
     */
    pub fn try_set_xmin(&mut self, val: f64) -> bool {
        if val > self.xmax {
            return false;
        } else {
            self.xmin = val;
            return true;
        }
    }

    /**
    Fallible sets a new value for `xmax`. If the new value is smaller than `xmin`, the old value is left unchanged
    and this function returns `false`. Otherwise, it returns `true` and the old value is replaced by the new value.

    # Examples

    ```
    use bounding_box::BoundingBox;

    let mut bb = BoundingBox::new(0.0, 1.0, 0.0, 1.0);

    assert_eq!(bb.xmax(), 1.0);
    assert!(bb.try_set_xmax(0.5));
    assert_eq!(bb.xmax(), 0.5);

    assert!(!bb.try_set_xmax(-0.5));
    assert_eq!(bb.xmax(), 0.5);
    ```
     */
    pub fn try_set_xmax(&mut self, val: f64) -> bool {
        if val < self.xmin {
            return false;
        } else {
            self.xmax = val;
            return true;
        }
    }

    /**
    Fallible sets a new value for `ymin`. If the new value is bigger than `ymax`, the old value is left unchanged
    and this function returns `false`. Otherwise, it returns `true` and the old value is replaced by the new value.

    # Examples

    ```
    use bounding_box::BoundingBox;

    let mut bb = BoundingBox::new(0.0, 1.0, 0.0, 1.0);

    assert_eq!(bb.ymin(), 0.0);
    assert!(bb.try_set_ymin(0.5));
    assert_eq!(bb.ymin(), 0.5);

    assert!(!bb.try_set_ymin(1.5));
    assert_eq!(bb.ymin(), 0.5);
    ```
     */
    pub fn try_set_ymin(&mut self, val: f64) -> bool {
        if val > self.ymax {
            return false;
        } else {
            self.ymin = val;
            return true;
        }
    }

    /**
    Fallible sets a new value for `ymax`. If the new value is smaller than `ymin`, the old value is left unchanged
    and this function returns `false`. Otherwise, it returns `true` and the old value is replaced by the new value.

    # Examples

    ```
    use bounding_box::BoundingBox;

    let mut bb = BoundingBox::new(0.0, 1.0, 0.0, 1.0);

    assert_eq!(bb.ymax(), 1.0);
    assert!(bb.try_set_ymax(0.5));
    assert_eq!(bb.ymax(), 0.5);

    assert!(!bb.try_set_ymax(-0.5));
    assert_eq!(bb.ymax(), 0.5);
    ```
     */
    pub fn try_set_ymax(&mut self, val: f64) -> bool {
        if val < self.ymin {
            return false;
        } else {
            self.ymax = val;
            return true;
        }
    }

    /**
    Creates a bounding box from an iterator over vertices.

    If the iterator is empty, this function returns `None`.
    ```
    use bounding_box::BoundingBox;

    let verts = vec![
        [1.0, 0.0],
        [-5.0, 2.0],
        [3.0, -12.3],
        [7.0, 0.0],
        [2.0, 11.0],
        [1.0, -6.0],
    ];

     let bb = BoundingBox::from_points(verts.into_iter()).expect("iterator yields at least one elment");
     assert_eq!(bb.xmin(), -5.0);
     assert_eq!(bb.xmax(), 7.0);
     assert_eq!(bb.ymin(), -12.3);
     assert_eq!(bb.ymax(), 11.0);
     ```
     */
    pub fn from_points<'a, T: Into<[f64; 2]>, I: Iterator<Item = T>>(mut verts: I) -> Option<Self> {
        match verts.next() {
            Some(pt) => {
                let pt: [f64; 2] = pt.into();
                let mut xmin = pt[0];
                let mut xmax = pt[0];
                let mut ymin = pt[1];
                let mut ymax = pt[1];
                for vert in verts {
                    let pt: [f64; 2] = vert.into();
                    if pt[0] > xmax {
                        xmax = pt[0]
                    }
                    if pt[0] < xmin {
                        xmin = pt[0]
                    }
                    if pt[1] > ymax {
                        ymax = pt[1]
                    }
                    if pt[1] < ymin {
                        ymin = pt[1]
                    }
                }
                return Some(BoundingBox::new(xmin, xmax, ymin, ymax));
            }
            None => return None,
        }
    }

    /**
    Creates a bounding box from an iterator over any types implementing
    [`Into<BoundingBox>`].

    If the iterator is empty, this function returns `None`.

    ```
    use bounding_box::BoundingBox;

    struct Circle {
        center: [f64; 2],
        radius: f64
    }

    impl From<&Circle> for BoundingBox {
        fn from(c: &Circle) -> BoundingBox {
            return BoundingBox::new(c.center[0] - c.radius,
                                    c.center[0] + c.radius,
                                    c.center[1] - c.radius,
                                    c.center[1] + c.radius);
        }
    }

    let c1 = Circle {center: [0.0, 0.0], radius: 1.0};
    let c2 = Circle {center: [0.0, 2.0], radius: 1.0};
    let c3 = Circle {center: [0.0, 2.0], radius: 2.0};

    let bb = BoundingBox::from_bounded_entities([&c1, &c2, &c3].into_iter()).expect("iterator has at least one element");
    assert_eq!(bb.xmin(), -2.0);
    assert_eq!(bb.xmax(), 2.0);
    assert_eq!(bb.ymin(), -1.0);
    assert_eq!(bb.ymax(), 4.0);
     ```
     */
    pub fn from_bounded_entities<T: Into<BoundingBox>, I: Iterator<Item = T>>(
        mut entities: I,
    ) -> Option<Self> {
        let first_bb: BoundingBox = entities.next()?.into();
        let bb = entities.fold(first_bb, |acc, drawable| drawable.into().union(&acc));
        return Some(bb);
    }

    /**
    Creates the union of two bounding boxes.

    The union of two bounding boxes is the minimum bounding box which contains both bounding boxes.

    # Examples

    ```
    use bounding_box::BoundingBox;

    let bb1 = BoundingBox::new(-1.0, 3.5, 2.0, 3.0);
    let bb2 = BoundingBox::new(-5.0, 2.5, -1.0, 5.0);
    let bb = bb1.union(&bb2);

    assert_eq!(bb.xmin(), -5.0);
    assert_eq!(bb.xmax(), 3.5);
    assert_eq!(bb.ymin(), -1.0);
    assert_eq!(bb.ymax(), 5.0);
    ```
    */
    pub fn union(&self, other: &BoundingBox) -> BoundingBox {
        let xmin: f64;
        let xmax: f64;
        let ymin: f64;
        let ymax: f64;
        if self.xmin > other.xmin {
            xmin = other.xmin;
        } else {
            xmin = self.xmin;
        }
        if self.xmax > other.xmax {
            xmax = self.xmax;
        } else {
            xmax = other.xmax;
        }
        if self.ymin > other.ymin {
            ymin = other.ymin;
        } else {
            ymin = self.ymin;
        }
        if self.ymax > other.ymax {
            ymax = self.ymax;
        } else {
            ymax = other.ymax;
        }
        return BoundingBox {
            xmin,
            xmax,
            ymin,
            ymax,
        };
    }

    /**
    Returns true if `self` contains a given point.

    A point is also seen as included if it is located on the edge of a bounding box.

    # Examples
    ```
    use bounding_box::BoundingBox;

    let bb = BoundingBox::new(0.0, 1.0, 0.0, 1.0);

    assert!(bb.contains_point([0.5, 0.5]));
    assert!(bb.contains_point([0.0, 0.0]));
    assert!(bb.contains_point([0.0, 0.0]));
    assert!(!bb.contains_point([-1.0, 0.0]));
    assert!(!bb.contains_point([0.0, 2.0]));
     */
    pub fn contains_point<T: Into<[f64; 2]>>(&self, point: T) -> bool {
        let point: [f64; 2] = point.into();
        return (self.xmin < point[0] || self.xmin == point[0])
            && (self.ymin < point[1] || self.ymin == point[1])
            && (self.xmax > point[0] || self.xmax == point[0])
            && (self.ymax > point[1] || self.ymax == point[1]);
    }

    /**
    Like [`BoundingBox::contains_point`], but with absolute and ULPs tolerances.

    This variant of [`BoundingBox::contains_point`] allows specifying an absolute and
    an [ULP](https://en.wikipedia.org/wiki/Unit_in_the_last_place) tolerance. These tolerances
    are used to check if the given point lies "approximately" on an edge of the bounding box.

    # Examples
    ```
    use bounding_box::BoundingBox;

    let bb = BoundingBox::new(0.0, 1.0, 0.0, 1.0);

    // Exact check: Point is outside the bounding box
    assert!(!bb.contains_point([1.0001, 1.0]));

    // Check using tolerances: Point is inside bounding box
    assert!(bb.approx_contains_point([1.0001, 1.0], 1e-3, 0));

    // Check using a finer tolerance: Point is outside the bounding box
    assert!(!bb.approx_contains_point([1.0001, 1.0], 1e-6, 0));
    ```

    # Features

    This function uses the [`ulps_eq`](https://docs.rs/approx/latest/approx/macro.ulps_eq.html)
    macro of the [approx] crate, therefore the `approx ` feature needs to be enabled.
     */
    #[cfg(feature = "approx")]
    pub fn approx_contains_point<T: Into<[f64; 2]>>(
        &self,
        point: T,
        epsilon: f64,
        max_ulps: u32,
    ) -> bool {
        let point: [f64; 2] = point.into();
        return (self.xmin < point[0]
            || ulps_eq!(self.xmin, point[0], epsilon = epsilon, max_ulps = max_ulps))
            && (self.ymin < point[1]
                || ulps_eq!(self.ymin, point[1], epsilon = epsilon, max_ulps = max_ulps))
            && (self.xmax > point[0]
                || ulps_eq!(self.xmax, point[0], epsilon = epsilon, max_ulps = max_ulps))
            && (self.ymax > point[1]
                || ulps_eq!(self.ymax, point[1], epsilon = epsilon, max_ulps = max_ulps));
    }

    /**
    Returns true if `self` contains `other`.

    A bounding box contains another bounding box, if the latter can be placed inside the former.
    This is true even if the boxes share some extremums. This also means that a bounding box always contains itself (see examples).

    # Examples
    ```
    use bounding_box::BoundingBox;

    // bb1 contains bb2, but not the other way around
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(0.2, 0.8, 0.2, 0.8);
    assert!(bb1.contains(&bb2));
    assert!(!bb2.contains(&bb1));

    // bb1 contains itself
    assert!(bb1.contains(&bb1));

    // bb1 and bb2 share a border
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(0.2, 1.0, 0.2, 0.8);
    assert!(bb1.contains(&bb2));

    // bb1 and bb2 are separated from each other, and therefore neither of one contains the other
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(2.0, 3.0, 2.0, 3.0);
    assert!(!bb1.contains(&bb2));
    assert!(!bb2.contains(&bb1));
    ```
    */
    pub fn contains(&self, other: &Self) -> bool {
        return self.xmin <= other.xmin
            && self.ymin <= other.ymin
            && self.xmax >= other.xmax
            && self.ymax >= other.ymax;
    }

    /**
    Like [`BoundingBox::contains`], but with absolute and ULPs tolerances.

    This variant of [`BoundingBox::contains`] allows specifying an absolute and
    an [ULP](https://en.wikipedia.org/wiki/Unit_in_the_last_place) tolerance. These tolerances
    are used to check if the extremas of the boxes are "approximately" equal.
    This check is performed using the [`ulps_eq`](https://docs.rs/approx/latest/approx/macro.ulps_eq.html)
    macro of the [approx] crate. Please see its documentation.

    ```
    use bounding_box::BoundingBox;

    // bb1 contains bb2 depending on the selected tolerances
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(0.0, 1.0001, 0.0, 0.5);

    assert!(!bb1.contains(&bb2));
    assert!(bb1.approx_contains(&bb2, 1e-3, 0));
    assert!(!bb1.approx_contains(&bb2, 1e-6, 0));
    ```

    # Features

    This function uses the [`ulps_eq`](https://docs.rs/approx/latest/approx/macro.ulps_eq.html)
    macro of the [approx] crate, therefore the `approx ` feature needs to be enabled.
    */
    #[cfg(feature = "approx")]
    pub fn approx_contains(&self, other: &Self, epsilon: f64, max_ulps: u32) -> bool {
        return (self.xmin < other.xmin
            || ulps_eq!(
                self.xmin,
                other.xmin,
                epsilon = epsilon,
                max_ulps = max_ulps
            ))
            && (self.ymin < other.ymin
                || ulps_eq!(
                    self.ymin,
                    other.ymin,
                    epsilon = epsilon,
                    max_ulps = max_ulps
                ))
            && (self.xmax > other.xmax
                || ulps_eq!(
                    self.xmax,
                    other.xmax,
                    epsilon = epsilon,
                    max_ulps = max_ulps
                ))
            && (self.ymax > other.ymax
                || ulps_eq!(
                    self.ymax,
                    other.ymax,
                    epsilon = epsilon,
                    max_ulps = max_ulps
                ));
    }

    /**
    Check if the two bounding boxes are approximately equal.
    This check is performed using the [`ulps_eq`](https://docs.rs/approx/latest/approx/macro.ulps_eq.html)
    macro of the [approx] crate. Please see its documentation.

    ```
    use bounding_box::BoundingBox;

    // bb1 contains bb2 depending on the selected tolerances
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(0.0, 1.0001, 0.0, 1.0);

    assert!(!bb1.eq(&bb2));
    assert!(bb1.approx_eq(&bb2, 1e-3, 0));
    assert!(!bb1.approx_eq(&bb2, 1e-6, 0));
    ```

    # Features

    This function uses the [`ulps_eq`](https://docs.rs/approx/latest/approx/macro.ulps_eq.html)
    macro of the [approx] crate, therefore the `approx ` feature needs to be enabled.
     */
    #[cfg(feature = "approx")]
    pub fn approx_eq(&self, other: &Self, epsilon: f64, max_ulps: u32) -> bool {
        return ulps_eq!(
            self.xmin(),
            other.xmin(),
            epsilon = epsilon,
            max_ulps = max_ulps
        ) && ulps_eq!(
            self.xmax(),
            other.xmax(),
            epsilon = epsilon,
            max_ulps = max_ulps
        ) && ulps_eq!(
            self.ymin(),
            other.ymin(),
            epsilon = epsilon,
            max_ulps = max_ulps
        ) && ulps_eq!(
            self.ymax(),
            other.ymax(),
            epsilon = epsilon,
            max_ulps = max_ulps
        );
    }

    /**
    Returns true if the bounding boxes intersect.

    The boxes are NOT intersecting if they are just [touching](BoundingBox::touches).

    # Examples
    ```
    use bounding_box::BoundingBox;

    // bb1 and bb2 intersect
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(-1.0, 1.0, 0.2, 0.8);
    assert!(bb1.intersects(&bb2));

     // bb1 and bb2 do not intersect
    let bb1 = BoundingBox::new(-1.0, 3.5, 2.0, 3.0);
    let bb2 = BoundingBox::new(-5.0, 2.5, -1.0, 1.0);
    assert!(!bb1.intersects(&bb2));

    // bb2 is contained in bb1
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(0.2, 1.0, 0.2, 0.8);
    assert!(bb1.intersects(&bb2));

    // bb1 is contained in bb2
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(0.2, 1.0, 0.2, 0.8);
    assert!(bb2.intersects(&bb1));

    // bb1 touches bb2 => no intersection
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(1.0, 2.0, 0.0, 1.0);
    assert!(!bb2.intersects(&bb1));
    ```
     */
    pub fn intersects(&self, other: &Self) -> bool {
        return self.xmin() < other.xmax()
            && other.xmin() < self.xmax()
            && self.ymin() < other.ymax()
            && other.ymin() < self.ymax();
    }

    /**
    Check if the bounding boxes are touching.

    The bounding boxes are touching if they share at least one extremum and are not intersecting each other.

    # Examples
    ```
    use bounding_box::BoundingBox;

    // bb1 touches bb2 => no intersection
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(1.0, 2.0, 0.0, 1.0);
    assert!(bb2.touches(&bb1));

    // bb1 is included in bb2 and two edges are touching
    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(0.0, 2.0, 0.0, 1.0);
    assert!(!bb2.touches(&bb1));

    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(1.0001, 2.0, 0.0, 1.0);
    assert!(!bb2.touches(&bb1));
    ```
     */
    pub fn touches(&self, other: &Self) -> bool {
        if self.intersects(&other) {
            return false;
        } else {
            return self.xmin() == other.xmax()
                || self.xmax() == other.xmin()
                || self.ymin() == other.ymax()
                || self.ymax() == other.ymin();
        }
    }

    /**
    Like [`BoundingBox::touches`], but with absolute and ULPs tolerances.

    This variant of [`BoundingBox::touches`] allows specifying an absolute and
    an [ULP](https://en.wikipedia.org/wiki/Unit_in_the_last_place) tolerance. These tolerances
    are used to check if the boxes share at least one extremas "approximately".
    This check is performed using the [`ulps_eq`](https://docs.rs/approx/latest/approx/macro.ulps_eq.html)
    macro of the [approx] crate. Please see its documentation.

    # Examples
    ```
    use bounding_box::BoundingBox;

    let bb1 = BoundingBox::new(0.0, 1.0, 0.0, 1.0);
    let bb2 = BoundingBox::new(1.0001, 2.0, 0.0, 1.0);
    assert!(!bb1.touches(&bb2));
    assert!(bb1.approx_touches(&bb2, 1e-3, 0));
    assert!(!bb1.approx_touches(&bb2, 1e-6, 0));
    ```

    # Features

    This function uses the [`ulps_eq`](https://docs.rs/approx/latest/approx/macro.ulps_eq.html)
    macro of the [approx] crate, therefore the `approx ` feature needs to be enabled.
    */
    #[cfg(feature = "approx")]
    pub fn approx_touches(&self, other: &Self, epsilon: f64, max_ulps: u32) -> bool {
        if self.intersects(&other) {
            return false;
        } else {
            return ulps_eq!(
                self.xmin(),
                other.xmax(),
                epsilon = epsilon,
                max_ulps = max_ulps
            ) || ulps_eq!(
                self.xmax(),
                other.xmin(),
                epsilon = epsilon,
                max_ulps = max_ulps
            ) || ulps_eq!(
                self.ymin(),
                other.ymax(),
                epsilon = epsilon,
                max_ulps = max_ulps
            ) || ulps_eq!(
                self.ymax(),
                other.ymin(),
                epsilon = epsilon,
                max_ulps = max_ulps
            );
        }
    }

    /**
    Returns the width of the bounding box.

    # Examples
    ```
    use bounding_box::BoundingBox;

    let bb = BoundingBox::new(-1.0, 1.0, 2.0, 7.0);
    assert_eq!(bb.width(), 2.0);
    ```
     */
    pub fn width(&self) -> f64 {
        return self.xmax - self.xmin;
    }

    /**
    Returns the height of the bounding box.

    # Examples
    ```
    use bounding_box::BoundingBox;

    let bb = BoundingBox::new(-1.0, 1.0, 2.0, 7.0);
    assert_eq!(bb.height(), 5.0);
    ```
     */
    pub fn height(&self) -> f64 {
        return self.ymax - self.ymin;
    }

    /**
    Returns the center of the bounding box.

    # Examples
    ```
    use bounding_box::BoundingBox;

    let bb = BoundingBox::new(-1.0, 1.0, 2.0, 7.0);
    assert_eq!(bb.center(), [0.0, 4.5]);
    ```
     */
    pub fn center(&self) -> [f64; 2] {
        let x = 0.5 * (self.xmax + self.xmin);
        let y = 0.5 * (self.ymax + self.ymin);
        return [x, y];
    }

    /**
    Translates the bounding box by the given `shift`.

    # Examples
    ```
    use bounding_box::BoundingBox;

    let mut bb = BoundingBox::new(0.0, 1.0, 1.0, 2.0);
    bb.translate([1.0, -1.0]);
    assert_eq!(bb.xmin(), 1.0);
    assert_eq!(bb.xmax(), 2.0);
    assert_eq!(bb.ymin(), 0.0);
    assert_eq!(bb.ymax(), 1.0);
    ```
     */
    pub fn translate<T: Into<[f64; 2]>>(&mut self, shift: T) -> () {
        let shift: [f64; 2] = shift.into();
        self.xmin += shift[0];
        self.xmax += shift[0];
        self.ymin += shift[1];
        self.ymax += shift[1];
    }

    /**
    Scales the width and height of `self` while keeping the center fixed.

    The bounding box is scaled by multiplying its width and height by the factor
    and then recalculating the extremas by adding / subtracting half the width / height
    from the center.

    # Examples
    ```
    use bounding_box::BoundingBox;

    let mut bb = BoundingBox::new(0.0, 1.0, 2.0, 4.0);

    assert_eq!(bb.center(), [0.5, 3.0]);
    assert_eq!(bb.width(), 1.0);
    assert_eq!(bb.height(), 2.0);

    bb.scale(2.0);

    assert_eq!(bb.center(), [0.5, 3.0]);
    assert_eq!(bb.width(), 2.0);
    assert_eq!(bb.height(), 4.0);

    assert_eq!(bb.xmin(), -0.5);
    assert_eq!(bb.xmax(), 1.5);
    assert_eq!(bb.ymin(), 1.0);
    assert_eq!(bb.ymax(), 5.0);
    ```
     */
    pub fn scale(&mut self, factor: f64) -> () {
        let dw = 0.5 * (factor - 1.0) * self.width();
        let dh = 0.5 * (factor - 1.0) * self.height();
        self.xmin = self.xmin - dw;
        self.xmax = self.xmax + dw;
        self.ymin = self.ymin - dh;
        self.ymax = self.ymax + dh;
    }

    /**
    Remove any singular dimensions by "buffering" them with `add_to_extr`.

    The value `add_to_extr` is applied to both the minimum and the maximum value of a singular dimension.
    For example, if the bounding box width is 0 (`xmin` = `xmax`) and `add_to_extr = 1.0`, the new width will be 2.0.

    # Examples
    ```
    use bounding_box::BoundingBox;

    let mut bb = BoundingBox::new(0.0, 0.0, -1.0, 1.0);
    assert_eq!(bb.width(), 0.0);

    bb.remove_singular_dimensions(1.0);
    assert_eq!(bb.width(), 2.0);
    assert_eq!(bb.xmin(), -1.0);
    assert_eq!(bb.xmax(), 1.0);

    // =================================================

    let mut bb = BoundingBox::new(-1.0, 1.0, 2.0, 2.0);
    assert_eq!(bb.height(), 0.0);

    bb.remove_singular_dimensions(3.0);
    assert_eq!(bb.height(), 6.0);
    assert_eq!(bb.ymin(), -1.0);
    assert_eq!(bb.ymax(), 5.0);
    ```
     */
    pub fn remove_singular_dimensions(&mut self, add_to_extr: f64) {
        if self.width() == 0.0 {
            self.xmin -= add_to_extr;
            self.xmax += add_to_extr;
        }
        if self.height() == 0.0 {
            self.ymin -= add_to_extr;
            self.ymax += add_to_extr;
        }
    }

    /**
    Returns true if the bounding box is finite.

    # Examples
    ```
    use std::f64::INFINITY;
    use bounding_box::BoundingBox;

    assert!(BoundingBox::new(0.0, 1.0, 0.0, 1.0).is_finite());
    assert!(!BoundingBox::new(0.0, INFINITY, 0.0, 1.0).is_finite());
    ```
     */
    pub fn is_finite(&self) -> bool {
        return self.xmin.is_finite()
            && self.xmax.is_finite()
            && self.ymin.is_finite()
            && self.ymax.is_finite();
    }
}

impl From<[f64; 2]> for BoundingBox {
    fn from(v: [f64; 2]) -> Self {
        return (&v).into();
    }
}

impl From<&'_ [f64; 2]> for BoundingBox {
    fn from(v: &'_ [f64; 2]) -> Self {
        return BoundingBox::new(v[0], v[0], v[1], v[1]);
    }
}

/**
This trait provides an associated method
[`bounding_box`](ToBoundingBox::bounding_box) for all types `T` which
implement [`Into<BoundingBox>`] for a shared reference `T` and therefore avoids
typing `BoundingBox::from(&T)`:

```
use bounding_box::{BoundingBox, ToBoundingBox};

struct Circle {
    center: [f64; 2],
    radius: f64
}

impl From<&Circle> for BoundingBox {
    fn from(c: &Circle) -> BoundingBox {
        return BoundingBox::new(c.center[0] - c.radius,
                                c.center[0] + c.radius,
                                c.center[1] - c.radius,
                                c.center[1] + c.radius);
    }
}

let c = Circle {center: [0.0, 0.0], radius: 1.0};
assert_eq!(c.bounding_box(), BoundingBox::from(&c));
```

Of course this trait can also be implemented manually, but it is heavily
recommended to instead implement `From<&T> for BoundingBox` instead.
 */
pub trait ToBoundingBox {
    /**
    Returns a bounding box for the implementor.

    # Example

    ```
    use bounding_box::{BoundingBox, ToBoundingBox};

    struct Circle {
        center: [f64; 2],
        radius: f64
    }

    impl From<&Circle> for BoundingBox {
        fn from(c: &Circle) -> BoundingBox {
            return BoundingBox::new(c.center[0] - c.radius,
                                    c.center[0] + c.radius,
                                    c.center[1] - c.radius,
                                    c.center[1] + c.radius);
        }
    }

    let c = Circle {center: [0.0, 0.0], radius: 1.0};
    let bb = c.bounding_box();
    assert_eq!(bb.xmin(), -1.0);
    assert_eq!(bb.ymin(), -1.0);
    assert_eq!(bb.xmax(), 1.0);
    assert_eq!(bb.ymax(), 1.0);
    ```
     */
    fn bounding_box(&self) -> BoundingBox;
}

impl<T> ToBoundingBox for T
where
    for<'a> &'a T: Into<BoundingBox>,
{
    fn bounding_box(&self) -> BoundingBox {
        self.into()
    }
}