grid1d 0.5.0

A mathematically rigorous, type-safe Rust library for 1D grid operations and interval partitions, supporting both native and arbitrary-precision numerics.
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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
#![deny(rustdoc::broken_intra_doc_links)]

//! Core traits defining the behaviour and capabilities of all interval types.
//!
//! This module contains the fundamental traits that all interval implementations
//! must satisfy. Concrete implementations live in [`bounded`](crate::intervals::bounded),
//! [`unbounded`](crate::intervals::unbounded), and the
//! [`Interval`] enum in [`crate::intervals`].
//!
//! ## Trait Overview
//!
//! | Trait | Purpose | Key Methods |
//! |-------|---------|------------|
//! | [`IntervalTrait`] | Universal interface for all interval types | `into_interval()`, `length()`, `midpoint()` |
//! | [`IntervalBoundsRuntime`] | Runtime access to lower and upper bounds | `lower_bound_runtime()`, `upper_bound_runtime()` |
//! | [`IntervalHull`] | Smallest interval enclosing two intervals | `hull(&other)` |
//! | [`Contains`] | Point and interval containment testing | `contains_point(&x)`, `contains_interval(&i)` |
//! | [`GetLowerBoundValue`] | Access to the finite lower bound value | `lower_bound_value()` |
//! | [`GetUpperBoundValue`] | Access to the finite upper bound value | `upper_bound_value()` |
//!
//! ## Example
//!
//! ```rust
//! use grid1d::intervals::*;
//!
//! let a = IntervalClosed::new(0.0_f64, 2.0);
//! let b = IntervalClosed::new(1.0_f64, 3.0);
//!
//! assert!(a.contains_point(&1.5));
//! assert_eq!(a.lower_bound_value(), &0.0);
//! assert_eq!(b.upper_bound_value(), &3.0);
//! ```

use crate::{
    bounds::{LowerBoundRuntime, UpperBoundRuntime},
    intervals::{Interval, operations::IntervalOperations},
};
use num_valid::{RealScalar, scalars::NonNegativeRealScalar};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;

//------------------------------------------------------------------------------------------------
/// Universal interface for all interval types providing common operations.
///
/// This trait provides a unified API for working with intervals regardless of their
/// specific type (closed, open, bounded, unbounded, etc.) and scalar type. It's the
/// foundation for generic interval programming in this library.
///
/// ## Core Operations
///
/// All intervals support three fundamental operations:
///
/// 1. **Point Containment**: [`contains_point`](Contains::contains_point)
///    - Tests if a single value lies within the interval
///    - Respects boundary conditions (open vs closed)
///    - O(1) operation for all interval types
///
/// 2. **Interval Containment**: [`contains_interval`](Contains::contains_interval)
///    - Tests if one interval is completely contained within another
///    - Handles complex boundary interactions correctly
///    - Supports cross-type containment testing
///
/// 3. **Intersection**: [`intersection`](IntervalOperations::intersection)
///    - Computes the overlap between two intervals
///    - Returns `None` for disjoint intervals
///    - Produces the most specific interval type possible
///
/// ## Mathematical Properties
///
/// The trait implementations guarantee these mathematical properties:
///
/// - **Reflexivity**: Every interval contains itself
/// - **Transitivity**: If A ⊆ B and B ⊆ C, then A ⊆ C
/// - **Commutativity**: A ∩ B = B ∩ A
/// - **Associativity**: (A ∩ B) ∩ C = A ∩ (B ∩ C)
/// - **Monotonicity**: If A ⊆ B, then A ∩ C ⊆ B ∩ C
///
/// ## Performance Characteristics by Scalar Type
///
/// | Operation | [`f64`] | [`RealNative64StrictFiniteInDebug`](num_valid::RealNative64StrictFiniteInDebug) | [`RealNative64StrictFinite`](num_valid::RealNative64StrictFinite) |
/// |-----------|---------|-----------------------------------|----------------------------|
/// | **Point queries** | O(1) raw | **O(1) identical** | O(1) + validation |
/// | **Containment** | O(1) comparisons | **O(1) identical** | O(1) + validation |
/// | **Intersections** | O(1) arithmetic | **O(1) identical** | O(1) + validation |
/// | **Memory usage** | 8-16 bytes | **8-16 bytes** | 8-16 bytes + metadata |
///
/// ## Generic Programming Examples
///
/// ### Interval Analysis Function
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// fn analyze_interval<I, T>(interval: &I) -> String
/// where
///     I: IntervalTrait<RealType = T>,
///     T: RealScalar + std::fmt::Display,
/// {
///     if interval.contains_point(&T::zero()) {
///         "Contains zero".to_string()
///     } else {
///         "Does not contain zero".to_string()
///     }
/// }
///
/// // Works with any interval type
/// let closed = IntervalClosed::new(-1.0, 1.0);
/// let open = IntervalOpen::new(0.0, 2.0);
/// let unbounded = IntervalLowerClosedUpperUnbounded::new(0.0);
///
/// assert_eq!(analyze_interval(&closed), "Contains zero");
/// assert_eq!(analyze_interval(&open), "Does not contain zero");
/// assert_eq!(analyze_interval(&unbounded), "Contains zero");
/// ```
///
/// ### Generic Intersection Function
/// ```rust
/// use grid1d::intervals::*;
///
/// fn safe_intersection<I1, I2>(a: &I1, b: &I2) -> Option<Interval<f64>>
/// where
///     I1: IntervalTrait<RealType = f64>,
///     I2: IntervalTrait<RealType = f64>,
/// {
///     a.intersection(b)
/// }
///
/// let closed = IntervalClosed::new(0.0, 2.0);
/// let open = IntervalOpen::new(1.0, 3.0);
///
/// if let Some(result) = safe_intersection(&closed, &open) {
///     println!("Intersection found: {:?}", result);
/// }
/// ```
///
/// ## Conversion to General Interval Type
///
/// All concrete types implementing `IntervalTrait` can be converted to the general
/// [`Interval`] enum via the [`Into`]/[`From`] traits:
///
/// ```rust
/// use grid1d::intervals::*;
///
/// // All concrete interval types convert to Interval<T>
/// let closed = IntervalClosed::new(0.0, 1.0);
/// let general: Interval<f64> = closed.into();
///
/// let open = IntervalOpen::new(0.0, 1.0);
/// let general2 = Interval::from(open);
///
/// let half_open = IntervalLowerClosedUpperOpen::new(0.0, 1.0);
/// let general3: Interval<f64> = half_open.into();
/// ```
///
/// This conversion is available for all interval types in the library:
/// - All bounded intervals: [`IntervalClosed`](crate::intervals::IntervalClosed), [`IntervalOpen`](crate::intervals::IntervalOpen), [`IntervalLowerClosedUpperOpen`](crate::intervals::IntervalLowerClosedUpperOpen), [`IntervalLowerOpenUpperClosed`](crate::intervals::IntervalLowerOpenUpperClosed)
/// - All unbounded intervals: [`IntervalLowerClosedUpperUnbounded`](crate::intervals::IntervalLowerClosedUpperUnbounded), [`IntervalLowerOpenUpperUnbounded`](crate::intervals::IntervalLowerOpenUpperUnbounded),
///   [`IntervalLowerUnboundedUpperClosed`](crate::intervals::IntervalLowerUnboundedUpperClosed), [`IntervalLowerUnboundedUpperOpen`](crate::intervals::IntervalLowerUnboundedUpperOpen), [`IntervalLowerUnboundedUpperUnbounded`](crate::intervals::IntervalLowerUnboundedUpperUnbounded)
/// - Singleton intervals: [`IntervalSingleton`](crate::intervals::IntervalSingleton)
/// - Enum variants: [`IntervalFinitePositiveLength`](crate::intervals::IntervalFinitePositiveLength), [`IntervalFiniteLength`](crate::intervals::IntervalFiniteLength), [`IntervalInfiniteLength`](crate::intervals::IntervalInfiniteLength)
pub trait IntervalTrait: Serialize + for<'a> Deserialize<'a> + IntervalOperations {
    /// Convert this interval into the general [`Interval`] enum by consuming it.
    ///
    /// This method provides an explicit, ergonomic way to convert any interval type
    /// to the most general `Interval<RealType>` enum, which can represent all possible
    /// interval types in a unified way. The conversion consumes `self` and is zero-cost.
    ///
    /// # Naming Convention
    ///
    /// This method follows Rust naming conventions:
    /// - `into_*`: Consumes `self`, zero-cost conversion (this method)
    /// - `to_*`: May clone or allocate, potentially expensive
    /// - `as_*`: Borrows `self`, returns a reference
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let closed = IntervalClosed::new(0.0, 1.0);
    /// let general = closed.into_interval();
    /// assert!(matches!(general, Interval::FiniteLength(_)));
    ///
    /// let unbounded = IntervalLowerClosedUpperUnbounded::new(0.0);
    /// let general2 = unbounded.into_interval();
    /// assert!(matches!(general2, Interval::InfiniteLength(_)));
    /// ```
    ///
    /// # Type Flexibility
    ///
    /// This method is particularly useful when working with heterogeneous collections
    /// of intervals or when you need to return different interval types from a function:
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// fn make_interval(bounded: bool) -> Interval<f64> {
    ///     if bounded {
    ///         IntervalClosed::new(0.0, 1.0).into_interval()
    ///     } else {
    ///         IntervalLowerClosedUpperUnbounded::new(0.0).into_interval()
    ///     }
    /// }
    /// ```
    ///
    /// # Working with Generic IntervalBounded
    ///
    /// The conversion also works with the generic `IntervalBounded<T, L, U>` type:
    ///
    /// ```rust
    /// use grid1d::{
    ///     bounds::{Closed, Open},
    ///     intervals::{*, bounded::*},
    /// };
    ///
    /// // Generic IntervalBounded can be converted to Interval
    /// let bounded: IntervalBounded<f64, Closed, Open> = IntervalBounded::new(0.0, 1.0);
    /// let general: Interval<f64> = bounded.into_interval();
    ///
    /// // This works because IntervalClosed, IntervalOpen, etc. are just type aliases
    /// // for IntervalBounded with specific bound type parameters
    /// ```
    #[inline(always)]
    fn into_interval(self) -> Interval<Self::RealType>
    where
        Self: Sized + Into<Interval<Self::RealType>>,
    {
        self.into()
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// Fundamental trait for runtime access to interval boundary information with dynamic bound type handling.
///
/// [`IntervalBoundsRuntime`] provides a unified interface for accessing interval boundaries where
/// the open/closed nature of bounds is determined at runtime rather than compile time. This trait
/// serves as the foundation for all interval types in the grid1d library, enabling dynamic boundary
/// introspection, cross-type operations, and flexible interval manipulation.
///
/// ## Design Philosophy
///
/// ### Runtime vs Compile-Time Boundary Access
///
/// Unlike compile-time bound access where boundary types are encoded in the type system,
/// [`IntervalBoundsRuntime`] provides dynamic access to boundary information:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use try_create::New;
///
/// // Different interval types with different boundary semantics
/// let closed = IntervalClosed::new(0.0, 1.0);           // [0, 1]
/// let open = IntervalOpen::new(0.0, 1.0);               // (0, 1)
/// let half_open = IntervalLowerClosedUpperOpen::new(0.0, 1.0); // [0, 1)
/// let unbounded = IntervalLowerClosedUpperUnbounded::new(0.0); // [0, ∞)
///
/// // All can be accessed uniformly through the trait
/// fn inspect_bounds<I: IntervalBoundsRuntime>(
///     interval: &I
/// ) -> (Option<LowerBoundRuntime<I::RealType>>, Option<UpperBoundRuntime<I::RealType>>) {
///     (interval.lower_bound_runtime(), interval.upper_bound_runtime())
/// }
///
/// let (lower, upper) = inspect_bounds(&closed);
/// // lower: Some(LowerBoundRuntime::Closed(...))
/// // upper: Some(UpperBoundRuntime::Closed(...))
///
/// let (lower, upper) = inspect_bounds(&unbounded);
/// // lower: Some(LowerBoundRuntime::Closed(...))
/// // upper: None (unbounded above)
/// ```
///
/// ### Unified Boundary Operations
///
/// The trait enables unified operations across different interval types:
///
/// | Operation | Purpose | Returns |
/// |-----------|---------|---------|
/// | [`lower_bound_runtime`](crate::intervals::IntervalBoundsRuntime::lower_bound_runtime) | Access lower boundary with type info | `Option<LowerBoundRuntime<T>>` |
/// | [`upper_bound_runtime`](crate::intervals::IntervalBoundsRuntime::upper_bound_runtime) | Access upper boundary with type info | `Option<UpperBoundRuntime<T>>` |
/// | [`max_lower_bound`](crate::intervals::IntervalBoundsRuntime::max_lower_bound) | Find most restrictive lower bound | `Option<LowerBoundRuntime<T>>` |
/// | [`min_upper_bound`](crate::intervals::IntervalBoundsRuntime::min_upper_bound) | Find most restrictive upper bound | `Option<UpperBoundRuntime<T>>` |
///
/// ## Associated Types
///
/// ### `RealType: RealScalar`
/// The scalar type used for boundary values and computations. Must implement [`num_valid::RealScalar`]
/// to ensure mathematical correctness and provide validation capabilities.
///
/// ## Core Operations
///
/// ### Boundary Access Methods
///
/// #### [`lower_bound_runtime`](crate::intervals::IntervalBoundsRuntime::lower_bound_runtime)
/// Returns the lower boundary information with runtime type encoding:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use try_create::New;
///
/// let closed_interval = IntervalClosed::new(1.0, 5.0);
/// let unbounded_interval = IntervalLowerUnboundedUpperClosed::new(5.0);
///
/// // Bounded interval returns boundary info
/// if let Some(lower) = closed_interval.lower_bound_runtime() {
///     match lower {
///         LowerBoundRuntime::Closed(bound) => {
///             println!("Lower bound [{}:", bound.as_ref()); // "[1.0:"
///         }
///         LowerBoundRuntime::Open(bound) => {
///             println!("Lower bound ({}:", bound.as_ref());
///         }
///     }
/// }
///
/// // Unbounded interval returns None
/// assert_eq!(unbounded_interval.lower_bound_runtime(), None);
/// ```
///
/// **Returns:**
/// - `Some(LowerBoundRuntime::Closed(_))` for intervals with closed lower bounds
/// - `Some(LowerBoundRuntime::Open(_))` for intervals with open lower bounds  
/// - `None` for intervals unbounded below (extending to -∞)
///
/// #### [`upper_bound_runtime`](crate::intervals::IntervalBoundsRuntime::upper_bound_runtime)
/// Returns the upper boundary information with runtime type encoding:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use try_create::New;
///
/// let closed_interval = IntervalClosed::new(1.0, 5.0);
/// let unbounded_interval = IntervalLowerClosedUpperUnbounded::new(1.0);
///
/// // Bounded interval returns boundary info
/// if let Some(upper) = closed_interval.upper_bound_runtime() {
///     match upper {
///         UpperBoundRuntime::Closed(bound) => {
///             println!(":{}]", bound.as_ref()); // ":5.0]"
///         }
///         UpperBoundRuntime::Open(bound) => {
///             println!(":{})", bound.as_ref());
///         }
///     }
/// }
///
/// // Unbounded interval returns None
/// assert_eq!(unbounded_interval.upper_bound_runtime(), None);
/// ```
///
/// **Returns:**
/// - `Some(UpperBoundRuntime::Closed(_))` for intervals with closed upper bounds
/// - `Some(UpperBoundRuntime::Open(_))` for intervals with open upper bounds
/// - `None` for intervals unbounded above (extending to +∞)
///
/// ### Boundary Comparison Operations
///
/// #### [`max_lower_bound`](crate::intervals::IntervalBoundsRuntime::max_lower_bound)
/// Finds the most restrictive (maximum) lower bound between two intervals:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use try_create::New;
///
/// let interval_a = IntervalClosed::new(0.0, 10.0);      // [0, 10]
/// let interval_b = IntervalLowerClosedUpperOpen::new(2.0, 8.0); // [2, 8)
///
/// // The most restrictive lower bound is [2
/// let max_lower = interval_a.max_lower_bound(&interval_b);
/// if let Some(LowerBoundRuntime::Closed(bound)) = max_lower {
///     assert_eq!(*bound.as_ref(), 2.0);
/// }
///
/// // With unbounded intervals
/// let unbounded = IntervalLowerUnboundedUpperClosed::new(5.0); // (-∞, 5]
/// let max_with_unbounded = interval_a.max_lower_bound(&unbounded);
/// // Returns [0 since unbounded has no lower bound
/// if let Some(LowerBoundRuntime::Closed(bound)) = max_with_unbounded {
///     assert_eq!(*bound.as_ref(), 0.0);
/// }
/// ```
///
/// **Behavior:**
/// - Returns the higher (more restrictive) of the two lower bounds
/// - If one interval is unbounded below, returns the other's lower bound
/// - If both are unbounded below, returns `None`
/// - Properly handles open vs closed boundary precedence
///
/// #### [`min_upper_bound`](crate::intervals::IntervalBoundsRuntime::min_upper_bound)
/// Finds the most restrictive (minimum) upper bound between two intervals:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use try_create::New;
///
/// let interval_a = IntervalClosed::new(0.0, 10.0);     // [0, 10]
/// let interval_b = IntervalOpen::new(2.0, 8.0);        // (2, 8)
///
/// // The most restrictive upper bound is 8)
/// let min_upper = interval_a.min_upper_bound(&interval_b);
/// if let Some(UpperBoundRuntime::Open(bound)) = min_upper {
///     assert_eq!(*bound.as_ref(), 8.0);
/// }
///
/// // With unbounded intervals
/// let unbounded = IntervalLowerClosedUpperUnbounded::new(0.0); // [0, +∞)
/// let min_with_unbounded = interval_a.min_upper_bound(&unbounded);
/// // Returns 10] since unbounded has no upper bound
/// if let Some(UpperBoundRuntime::Closed(bound)) = min_with_unbounded {
///     assert_eq!(*bound.as_ref(), 10.0);
/// }
/// ```
///
/// **Behavior:**
/// - Returns the lower (more restrictive) of the two upper bounds
/// - If one interval is unbounded above, returns the other's upper bound
/// - If both are unbounded above, returns `None`
/// - Properly handles open vs closed boundary precedence
///
/// ## Implementation Patterns
///
/// ### Finite Intervals
/// All finite intervals (closed, open, half-open) return `Some(_)` for both bounds:
///
/// ```rust,ignore
/// impl<RealType: RealScalar> IntervalBoundsRuntime for IntervalClosed<RealType> {
///     type RealType = RealType;
///
///     fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<RealType>> {
///         Some(IntervalBoundRuntime::Closed(self.lower_bound().clone()))
///     }
///
///     fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<RealType>> {
///         Some(IntervalBoundRuntime::Closed(self.upper_bound().clone()))
///     }
/// }
/// ```
///
/// ### Semi-Bounded Intervals
/// Semi-bounded intervals return `Some(_)` for the finite bound and `None` for the infinite bound:
///
/// ```rust,ignore
/// impl<RealType: RealScalar> IntervalBoundsRuntime for IntervalLowerClosedUpperUnbounded<RealType> {
///     type RealType = RealType;
///
///     fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<RealType>> {
///         Some(IntervalBoundRuntime::Closed(self.lower_bound().clone()))
///     }
///
///     fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<RealType>> {
///         None  // Unbounded above
///     }
/// }
/// ```
///
/// ### Unbounded Intervals
/// Fully unbounded intervals return `None` for both bounds:
///
/// ```rust,ignore
/// impl<RealType: RealScalar> IntervalBoundsRuntime for IntervalLowerUnboundedUpperUnbounded<RealType> {
///     type RealType = RealType;
///
///     fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<RealType>> {
///         None  // Unbounded below
///     }
///
///     fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<RealType>> {
///         None  // Unbounded above
///     }
/// }
/// ```
///
/// ### Singleton Intervals
/// Singleton intervals return the same value for both bounds with closed semantics:
///
/// ```rust,ignore
/// impl<RealType: RealScalar> IntervalBoundsRuntime for IntervalSingleton<RealType> {
///     type RealType = RealType;
///
///     fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<RealType>> {
///         Some(IntervalBoundRuntime::Closed(LowerBoundClosed::new(self.value().clone())))
///     }
///
///     fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<RealType>> {
///         Some(IntervalBoundRuntime::Closed(UpperBoundClosed::new(self.value().clone())))
///     }
/// }
/// ```
///
/// ## Advanced Usage Patterns
///
/// ### Generic Intersection Algorithm
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use num_valid::RealScalar;
///
/// /// Generic intersection algorithm using runtime bounds
/// fn intersection_bounds<I1, I2, T>(
///     a: &I1,
///     b: &I2,
/// ) -> Option<(LowerBoundRuntime<T>, UpperBoundRuntime<T>)>
/// where
///     I1: IntervalBoundsRuntime<RealType = T>,
///     I2: IntervalBoundsRuntime<RealType = T>,
///     T: RealScalar,
/// {
///     // Find most restrictive bounds
///     let lower = a.max_lower_bound(b)?;
///     let upper = a.min_upper_bound(b)?;
///     
///     // Check if intersection is valid (lower ≤ upper)
///     let lower_val = lower.as_ref();
///     let upper_val = upper.as_ref();
///     
///     if lower_val <= upper_val {
///         // Additional boundary compatibility check for exact equality
///         if lower_val == upper_val {
///             match (&lower, &upper) {
///                 (LowerBoundRuntime::Closed(_), UpperBoundRuntime::Closed(_)) => {
///                     Some((lower, upper)) // [a, a] is valid (singleton)
///                 }
///                 _ => None, // (a, a], [a, a), or (a, a) are empty
///             }
///         } else {
///             Some((lower, upper))
///         }
///     } else {
///         None // Disjoint intervals
///     }
/// }
///
/// let a = IntervalClosed::new(0.0, 2.0);    // [0, 2]
/// let b = IntervalOpen::new(1.0, 3.0);      // (1, 3)
///
/// if let Some((lower, upper)) = intersection_bounds(&a, &b) {
///     println!("Intersection exists:");
///     match lower {
///         LowerBoundRuntime::Open(bound) => println!("  Lower: ({}", bound.as_ref()),
///         LowerBoundRuntime::Closed(bound) => println!("  Lower: [{}",bound.as_ref()),
///     }
///     match upper {
///         UpperBoundRuntime::Open(bound) => println!("  Upper: {})", bound.as_ref()),
///         UpperBoundRuntime::Closed(bound) => println!("  Upper: {}]", bound.as_ref()),
///     }
/// }
/// // Output: Intersection is (1, 2]
/// ```
///
/// ### Interval Classification
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use num_valid::RealScalar;
///
/// #[derive(Debug, PartialEq)]
/// enum IntervalType {
///     Finite { closed_lower: bool, closed_upper: bool },
///     LowerBounded { closed: bool },
///     UpperBounded { closed: bool },
///     Unbounded,
///     Singleton,
/// }
///
/// /// Classify any interval based on its runtime bounds
/// fn classify_interval<I, T>(interval: &I) -> IntervalType
/// where
///     I: IntervalBoundsRuntime<RealType = T>,
///     T: RealScalar,
/// {
///     let lower = interval.lower_bound_runtime();
///     let upper = interval.upper_bound_runtime();
///     
///     match (lower, upper) {
///         (Some(lower_bound), Some(upper_bound)) => {
///             // Check if it's a singleton
///             let lower_val = lower_bound.as_ref();
///             let upper_val = upper_bound.as_ref();
///             
///             if lower_val == upper_val &&
///                matches!((&lower_bound, &upper_bound),
///                        (LowerBoundRuntime::Closed(_), UpperBoundRuntime::Closed(_))) {
///                 IntervalType::Singleton
///             } else {
///                 IntervalType::Finite {
///                     closed_lower: matches!(lower_bound, LowerBoundRuntime::Closed(_)),
///                     closed_upper: matches!(upper_bound, UpperBoundRuntime::Closed(_)),
///                 }
///             }
///         }
///         (Some(lower_bound), None) => {
///             IntervalType::LowerBounded {
///                 closed: matches!(lower_bound, LowerBoundRuntime::Closed(_)),
///             }
///         }
///         (None, Some(upper_bound)) => {
///             IntervalType::UpperBounded {
///                 closed: matches!(upper_bound, UpperBoundRuntime::Closed(_)),
///             }
///         }
///         (None, None) => IntervalType::Unbounded,
///     }
/// }
/// ```
///
/// ## Mathematical Properties
///
/// ### Boundary Ordering
/// The trait respects mathematical ordering of boundaries:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
///
/// // Lower bounds: more restrictive (higher) values dominate
/// let a = IntervalClosed::new(0.0, 5.0);    // [0, 5]
/// let b = IntervalClosed::new(2.0, 3.0);    // [2, 3]
///
/// let max_lower = a.max_lower_bound(&b);
/// // Returns [2 (more restrictive)
///
/// // Upper bounds: more restrictive (lower) values dominate  
/// let min_upper = a.min_upper_bound(&b);
/// // Returns 3] (more restrictive)
/// ```
///
/// ### Boundary Type Precedence
/// When bounds have the same value, the more restrictive type wins:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
///
/// let closed_interval = IntervalClosed::new(1.0, 2.0);        // [1, 2]
/// let half_open_interval = IntervalLowerOpenUpperClosed::new(1.0, 2.0); // (1, 2]
///
/// // For lower bounds with same value: closed ([) is more restrictive than open (()
/// let max_lower = closed_interval.max_lower_bound(&half_open_interval);
/// // Returns [1 (closed bound wins)
/// ```
///
/// ## Performance Characteristics
///
/// ### Memory Layout
/// - **Associated Type**: `RealType` adds no runtime overhead
/// - **Boundary Access**: Methods return owned [`IntervalBoundRuntime`](crate::intervals::IntervalBoundRuntime) values
/// - **Comparison Operations**: Default implementations with optimal algorithms
///
/// ### Time Complexity
/// | Operation | Complexity | Notes |
/// |-----------|------------|-------|
/// | [`lower_bound_runtime`](crate::intervals::IntervalBoundsRuntime::lower_bound_runtime) | O(1) | Direct field access and enum construction |
/// | [`upper_bound_runtime`](crate::intervals::IntervalBoundsRuntime::upper_bound_runtime) | O(1) | Direct field access and enum construction |
/// | [`max_lower_bound`](crate::intervals::IntervalBoundsRuntime::max_lower_bound) | O(1) | Pattern matching and comparison |
/// | [`min_upper_bound`](crate::intervals::IntervalBoundsRuntime::min_upper_bound) | O(1) | Pattern matching and comparison |
///
/// ### Space Complexity
/// - **Return Values**: Owned [`IntervalBoundRuntime`](crate::intervals::IntervalBoundRuntime) values (small enum + scalar)
/// - **No Allocation**: All operations work on stack-allocated data
/// - **Generic Efficiency**: Monomorphization ensures optimal code generation
///
/// ## Integration with Grid1D Architecture
///
/// ### Cross-Type Operations
/// The trait enables operations between different interval types:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use num_valid::RealScalar;
///
/// fn can_intervals_intersect<I1, I2, T>(a: &I1, b: &I2) -> bool
/// where
///     I1: IntervalBoundsRuntime<RealType = T>,
///     I2: IntervalBoundsRuntime<RealType = T>,
///     T: RealScalar,
/// {
///     // Use runtime boundary information to check intersection possibility
///     let max_lower = a.max_lower_bound(b);
///     let min_upper = a.min_upper_bound(b);
///     
///     match (max_lower, min_upper) {
///         (Some(lower), Some(upper)) => {
///             // Extract values for comparison
///             let lower_val = lower.as_ref();
///             let upper_val = upper.as_ref();
///             
///             lower_val <= upper_val // Non-empty intersection possible
///         }
///         _ => true, // At least one interval is unbounded
///     }
/// }
///
/// // Works across all interval types
/// let closed = IntervalClosed::new(0.0, 2.0);
/// let open = IntervalOpen::new(1.0, 3.0);
/// let unbounded = IntervalLowerClosedUpperUnbounded::new(-1.0);
///
/// assert!(can_intervals_intersect(&closed, &open));       // [0,2] ∩ (1,3) ≠ ∅
/// assert!(can_intervals_intersect(&closed, &unbounded));  // [0,2] ∩ [-1,∞) ≠ ∅
/// ```
///
/// ## Best Practices
///
/// ### When to Use Runtime Boundary Access
/// - ✅ **Dynamic interval analysis**: When interval types vary at runtime
/// - ✅ **Generic algorithms**: Operations that work across different interval types  
/// - ✅ **Intersection computations**: Finding overlaps between arbitrary intervals
/// - ✅ **Serialization/deserialization**: Converting intervals to/from external formats
/// - ✅ **User interfaces**: Displaying interval information to users
///
/// ### Type Safety Guidelines
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use num_valid::RealScalar;
///
/// // RECOMMENDED: Use associated types for consistency
/// fn process_interval_bounds<I>(interval: &I) -> String
/// where
///     I: IntervalBoundsRuntime,
///     I::RealType: std::fmt::Display,
/// {
///     let lower = interval.lower_bound_runtime();
///     let upper = interval.upper_bound_runtime();
///     // Process using I::RealType consistently
///     format!("Interval bounds processed")
/// }
/// ```
///
/// ## Error Handling and Edge Cases
///
/// ### Boundary Validation
/// Runtime boundary access preserves the validation guarantees of the underlying scalar types:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// type SafeReal = RealNative64StrictFiniteInDebug;
///
/// // Validation happens at interval construction, not boundary access
/// let safe_interval = IntervalClosed::new(
///     SafeReal::try_new(0.0).unwrap(),
///     SafeReal::try_new(1.0).unwrap()
/// );
///
/// // Boundary access is always safe after valid construction
/// let lower = safe_interval.lower_bound_runtime();
/// // lower is guaranteed to contain valid RealNative64StrictFiniteInDebug values
/// ```
///
/// ### Degenerate Cases
/// The trait handles degenerate interval cases correctly:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use try_create::New;
///
/// // Singleton interval
/// let singleton = IntervalSingleton::new(5.0);
/// let lower = singleton.lower_bound_runtime().unwrap();
/// let upper = singleton.upper_bound_runtime().unwrap();
///
/// // Both bounds point to the same value with closed semantics
/// match (lower, upper) {
///     (LowerBoundRuntime::Closed(l), UpperBoundRuntime::Closed(u)) => {
///         assert_eq!(l.as_ref(), u.as_ref());
///         assert_eq!(*l.as_ref(), 5.0);
///     }
///     _ => panic!("Singleton should have closed bounds"),
/// }
/// ```
///
/// The [`IntervalBoundsRuntime`] trait provides the essential foundation for dynamic interval
/// boundary access and manipulation in the grid1d library. It enables flexible, type-safe
/// operations across all interval types while maintaining mathematical correctness and optimal
/// performance through Rust's zero-cost abstractions.
pub trait IntervalBoundsRuntime: Debug {
    /// The scalar type used for interval bounds.
    ///
    /// This associated type must implement [`RealScalar`], ensuring it supports
    /// all necessary mathematical operations and comparisons.
    type RealType: RealScalar;

    /// Returns the lower boundary value if the interval is bounded below.
    ///
    /// # Returns
    /// - `Some(&value)` if the interval has a finite lower bound
    /// - `None` if the interval extends to negative infinity
    ///
    /// # Examples
    /// ```rust
    /// use grid1d::{bounds::*, intervals::*};
    /// use try_create::New;
    ///
    /// let bounded = IntervalClosed::new(1.0, 5.0);
    /// let unbounded = IntervalLowerUnboundedUpperClosed::new(5.0);
    ///
    /// assert_eq!(bounded.lower_bound_runtime(), Some(LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0))));
    /// assert_eq!(unbounded.lower_bound_runtime(), None);
    /// ```
    fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<Self::RealType>>;

    /// Returns the upper boundary value if the interval is bounded above.
    ///
    /// # Returns
    /// - `Some(&value)` if the interval has a finite upper bound
    /// - `None` if the interval extends to positive infinity
    ///
    /// # Examples
    /// ```rust
    /// use grid1d::{bounds::*, intervals::*};
    /// use try_create::New;
    ///
    /// let bounded = IntervalClosed::new(1.0, 5.0);
    /// let unbounded = IntervalLowerClosedUpperUnbounded::new(1.0);
    ///
    /// assert_eq!(bounded.upper_bound_runtime(), Some(UpperBoundRuntime::Closed(UpperBoundClosed::new(5.0))));
    /// assert_eq!(unbounded.upper_bound_runtime(), None);
    /// ```
    fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<Self::RealType>>;

    /// Finds the most restrictive (maximum) lower bound between two intervals.
    ///
    /// This method compares the lower bounds of two intervals and returns the one that
    /// is more restrictive (higher value). This is essential for intersection operations
    /// where the resulting interval's lower bound must satisfy both input intervals.
    ///
    /// # Mathematical Behavior
    /// - Returns the higher (more restrictive) of the two lower bounds
    /// - If one interval is unbounded below, returns the other's lower bound
    /// - If both are unbounded below, returns `None`
    /// - Properly handles open vs closed boundary precedence (closed is more restrictive)
    ///
    /// # Type Parameters
    /// - `Other`: Another interval type implementing `IntervalBoundsRuntime` with the same scalar type
    ///
    /// # Returns
    /// - `Some(LowerBoundRuntime)`: The most restrictive lower bound
    /// - `None`: If both intervals are unbounded below
    ///
    /// # Examples
    /// ```rust
    /// use grid1d::{bounds::*, intervals::*};
    /// use try_create::New;
    ///
    /// let interval_a = IntervalClosed::new(0.0, 10.0);      // [0, 10]
    /// let interval_b = IntervalLowerClosedUpperOpen::new(2.0, 8.0); // [2, 8)
    ///
    /// // The most restrictive lower bound is [2
    /// let max_lower = interval_a.max_lower_bound(&interval_b);
    /// if let Some(LowerBoundRuntime::Closed(bound)) = max_lower {
    ///     assert_eq!(*bound.as_ref(), 2.0);
    /// }
    ///
    /// // With unbounded intervals
    /// let unbounded = IntervalLowerUnboundedUpperClosed::new(5.0); // (-∞, 5]
    /// let max_with_unbounded = interval_a.max_lower_bound(&unbounded);
    /// // Returns [0 since unbounded has no lower bound
    /// if let Some(LowerBoundRuntime::Closed(bound)) = max_with_unbounded {
    ///     assert_eq!(*bound.as_ref(), 0.0);
    /// }
    /// ```
    fn max_lower_bound<Other>(&self, other: &Other) -> Option<LowerBoundRuntime<Self::RealType>>
    where
        Other: IntervalBoundsRuntime<RealType = Self::RealType>,
    {
        let lb_self = self.lower_bound_runtime();
        let lb_other = other.lower_bound_runtime();
        match (lb_self, lb_other) {
            (None, lb_other) => lb_other,
            (lb_self, None) => lb_self,
            (Some(lb_self), Some(lb_other)) => {
                Some(crate::bounds::max_lower_bound(lb_self, lb_other))
            }
        }
    }

    /// Finds the most restrictive (minimum) upper bound between two intervals.
    ///
    /// This method compares the upper bounds of two intervals and returns the one that
    /// is more restrictive (lower value). This is essential for intersection operations
    /// where the resulting interval's upper bound must satisfy both input intervals.
    ///
    /// # Mathematical Behavior
    /// - Returns the lower (more restrictive) of the two upper bounds
    /// - If one interval is unbounded above, returns the other's upper bound
    /// - If both are unbounded above, returns `None`
    /// - Properly handles open vs closed boundary precedence (open is more restrictive)
    ///
    /// # Type Parameters
    /// - `Other`: Another interval type implementing `IntervalBoundsRuntime` with the same scalar type
    ///
    /// # Returns
    /// - `Some(UpperBoundRuntime)`: The most restrictive upper bound
    /// - `None`: If both intervals are unbounded above
    ///
    /// # Examples
    /// ```rust
    /// use grid1d::{bounds::*, intervals::*};
    /// use try_create::New;
    ///
    /// let interval_a = IntervalClosed::new(0.0, 10.0);     // [0, 10]
    /// let interval_b = IntervalOpen::new(2.0, 8.0);        // (2, 8)
    ///
    /// // The most restrictive upper bound is 8)
    /// let min_upper = interval_a.min_upper_bound(&interval_b);
    /// if let Some(UpperBoundRuntime::Open(bound)) = min_upper {
    ///     assert_eq!(*bound.as_ref(), 8.0);
    /// }
    ///
    /// // With unbounded intervals
    /// let unbounded = IntervalLowerClosedUpperUnbounded::new(0.0); // [0, +∞)
    /// let min_with_unbounded = interval_a.min_upper_bound(&unbounded);
    /// // Returns 10] since unbounded has no upper bound
    /// if let Some(UpperBoundRuntime::Closed(bound)) = min_with_unbounded {
    ///     assert_eq!(*bound.as_ref(), 10.0);
    /// }
    /// ```
    fn min_upper_bound<Other>(&self, other: &Other) -> Option<UpperBoundRuntime<Self::RealType>>
    where
        Other: IntervalBoundsRuntime<RealType = Self::RealType>,
    {
        let ub_self = self.upper_bound_runtime();
        let ub_other = other.upper_bound_runtime();
        match (ub_self, ub_other) {
            (None, ub_other) => ub_other,
            (ub_self, None) => ub_self,
            (Some(ub_self), Some(ub_other)) => {
                Some(crate::bounds::min_upper_bound(ub_self, ub_other))
            }
        }
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// Trait for computing the **convex hull** (interval hull) between two intervals.
///
/// The convex hull is the smallest interval that contains both input intervals,
/// preserving the most **inclusive boundary semantics**.
///
/// ## Mathematical Definition
///
/// For two intervals `A` and `B`, their convex hull `hull(A, B)` is defined as:
///
/// ```text
/// hull(A, B) = [min(inf A, inf B), max(sup A, sup B)]
/// ```
///
/// where the boundary types follow the **most inclusive principle**:
/// - **Lower bound**: Take the minimum value with the **most inclusive** boundary type
/// - **Upper bound**: Take the maximum value with the **most inclusive** boundary type
/// - **Inclusion hierarchy**: `Closed ⊃ Open` (closed is more inclusive than open)
///
/// ### Boundary Inclusion Rules
///
/// When computing the hull, boundary types are resolved according to inclusion precedence:
///
/// | Input Bounds | Result Bound | Rationale |
/// |--------------|--------------|-----------|
/// | `Closed` + `Closed` | `Closed` | Both include boundary → include in hull |
/// | `Closed` + `Open` | `Closed` | Closed is more inclusive → include in hull |
/// | `Open` + `Open` | `Open` | Both exclude boundary → exclude in hull |
///
/// **Example**: For intervals `[0, 1]` and `(0, 2)`:
/// - Lower bound: Both have value 0, but `[` (closed) is more inclusive than `(` (open) → result uses `[`
/// - Upper bound: Values 1 vs 2, take max(1,2)=2 with bound type from `(0, 2)` → result uses `)`
/// - Final hull: `[0, 2)`
///
/// This ensures that the hull contains **exactly** the union of all points contained
/// in either input interval, with no points added or removed incorrectly.
///
/// ## Core Operation
///
/// ### [`hull`](IntervalHull::hull) Method
///
/// Computes the convex hull between `self` and another interval of potentially different type.
///
/// **Signature**: `fn hull(&self, other: &Other) -> Self::Output`
///
/// **Parameters**:
/// - `other`: Another finite positive-length interval (may be different type)
///
/// **Returns**: An interval containing both input intervals with correct boundary semantics
///
/// ## Generic Design and Type Safety
///
/// The trait is designed for maximum flexibility while maintaining type safety:
/// - **Generic over interval types**: Works between any interval implementing the trait [`IntervalTrait`]
/// - **Scalar type consistency**: Both intervals must use the same `RealType`
/// - **Type-safe output**: Result type depends on input boundary combinations
/// - **Compile-time verification**: Invalid combinations are caught at compile time
///
/// ## Mathematical Properties
///
/// All implementations guarantee these fundamental mathematical properties:
///
/// ### 1. **Containment Property**
/// ```text
/// A ⊆ hull(A, B) and B ⊆ hull(A, B)
/// ```
/// The hull always contains both input intervals completely.
///
/// ### 2. **Minimality Property**
/// ```text
/// If A ⊆ C and B ⊆ C, then hull(A, B) ⊆ C
/// ```
/// The hull is the smallest interval containing both inputs.
///
/// ### 3. **Commutativity Property**
/// ```text
/// hull(A, B) = hull(B, A)
/// ```
/// Order of operands doesn't affect the result.
///
/// ### 4. **Idempotence Property**
/// ```text
/// hull(A, A) = A (for compatible types)
/// ```
/// Hull of an interval with itself is the interval.
///
/// ### 5. **Associativity Property**
/// ```text
/// hull(hull(A, B), C) = hull(A, hull(B, C))
/// ```
/// Grouping doesn't affect the final result.
///
/// ## Comprehensive Usage Examples
///
/// ### Basic Hull Operations
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// type Real = RealNative64StrictFiniteInDebug;
///
/// // Same boundary types → preserve type
/// let closed1 = IntervalClosed::new(
///     Real::try_new(1.0).unwrap(),
///     Real::try_new(3.0).unwrap()
/// );
/// let closed2 = IntervalClosed::new(
///     Real::try_new(2.0).unwrap(),
///     Real::try_new(5.0).unwrap()
/// );
///
/// let hull = closed1.hull(&closed2);
/// // Result: [1.0, 5.0] (closed)
/// assert_eq!(hull.lower_bound_value(), &1.0);
/// assert_eq!(hull.upper_bound_value(), &5.0);
/// ```
///
/// ### Cross-Type Hull Operations
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::TryNew;
///
/// let closed = IntervalClosed::new(1.0, 3.0);      // [1, 3]
/// let open = IntervalOpen::new(2.0, 5.0);          // (2, 5)
///
/// let hull = closed.hull(&open);
/// // Result: [1.0, 5.0) - closed lower wins, open upper wins  
/// match hull {
///     IntervalFinitePositiveLength::LowerClosedUpperOpen(result) => {
///         assert_eq!(*result.lower_bound_value(), 1.0);
///         assert_eq!(*result.upper_bound_value(), 5.0);
///     }
///     _ => unreachable!(),
/// }
/// ```
///
/// ### Complex Boundary Combinations
/// ```rust
/// use grid1d::intervals::*;
///
/// let left_closed = IntervalLowerClosedUpperOpen::new(1.0, 3.0);   // [1, 3)
/// let right_closed = IntervalLowerOpenUpperClosed::new(2.0, 5.0);  // (2, 5]
///
/// let hull = left_closed.hull(&right_closed);
/// // Result: [1.0, 5.0] - closed lower wins, closed upper wins
/// match hull {
///     IntervalFinitePositiveLength::Closed(result) => {
///         assert_eq!(*result.lower_bound_value(), 1.0);
///         assert_eq!(*result.upper_bound_value(), 5.0);
///     }
///     _ => unreachable!(),
/// }
/// ```
///
/// ### Disjoint Intervals
/// ```rust
/// use grid1d::intervals::*;
///
/// let left = IntervalClosed::new(1.0, 2.0);    // [1, 2]
/// let right = IntervalClosed::new(4.0, 5.0);   // [4, 5]
///
/// let hull = left.hull(&right);
/// // Result: [1.0, 5.0] - spans both intervals and the gap
/// assert_eq!(*hull.lower_bound_value(), 1.0);
/// assert_eq!(*hull.upper_bound_value(), 5.0);
/// assert_eq!(*hull.length().as_ref(), 4.0);  // Includes the gap
/// ```
///
/// ### Containment Relationships
/// ```rust
/// use grid1d::intervals::*;
///
/// let outer = IntervalClosed::new(0.0, 10.0);  // [0, 10]
/// let inner = IntervalClosed::new(3.0, 7.0);   // [3, 7]
///
/// let hull = outer.hull(&inner);
/// // Result: [0.0, 10.0] - same as outer interval
/// assert_eq!(*hull.lower_bound_value(), 0.0);
/// assert_eq!(*hull.upper_bound_value(), 10.0);
/// ```
///
/// ## Advanced Usage Patterns
///
/// ### Multi-Interval Hull
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Compute hull of multiple intervals using fold
/// fn multi_hull(intervals: Vec<IntervalClosed<f64>>) -> Option<IntervalFinitePositiveLength<f64>> {
///     let mut iter = intervals.into_iter();
///     let first = iter.next()?;
///     Some(iter.fold(first.into(), |acc: IntervalFinitePositiveLength<f64>, interval| {
///         acc.hull(&interval)
///     }))
/// }
///
/// let intervals = vec![
///     IntervalClosed::new(1.0, 2.0),
///     IntervalClosed::new(3.0, 4.0),
///     IntervalClosed::new(5.0, 6.0),
/// ];
///
/// if let Some(hull) = multi_hull(intervals) {
///     // Result: [1.0, 6.0]
///     assert_eq!(*hull.lower_bound_value(), 1.0);
///     assert_eq!(*hull.upper_bound_value(), 6.0);
/// }
/// ```
///
/// ### Boundary-Aware Hull Analysis
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Analyze how boundary types affect hull computation
/// let closed = IntervalClosed::new(0.0, 1.0);           // [0, 1]
/// let open = IntervalOpen::new(0.0, 1.0);               // (0, 1)
/// let left_open = IntervalLowerOpenUpperClosed::new(0.0, 1.0);  // (0, 1]
/// let right_open = IntervalLowerClosedUpperOpen::new(0.0, 1.0); // [0, 1)
///
/// // Same bounds, different boundary types
/// let hull_closed_open = closed.hull(&open);
/// let hull_left_right = left_open.hull(&right_open);
///
/// // Both should result in closed intervals due to boundary inclusion rules
/// // (closed boundaries win over open boundaries at same values)
/// match (hull_closed_open, hull_left_right) {
///     (
///         IntervalFinitePositiveLength::Closed(h1),
///         IntervalFinitePositiveLength::Closed(h2)
///     ) => {
///         assert_eq!(h1.lower_bound_value(), h2.lower_bound_value());
///         assert_eq!(h1.upper_bound_value(), h2.upper_bound_value());
///     }
///     _ => unreachable!("Expected closed intervals"),
/// }
/// ```
///
/// ## Implementation Strategy
///
/// The trait provides implementations for all combinations of finite positive-length intervals:
///
/// ### Homogeneous Implementations
/// - [`IntervalClosed`](crate::intervals::IntervalClosed) with [`IntervalClosed`](crate::intervals::IntervalClosed) → [`IntervalClosed`](crate::intervals::IntervalClosed)
/// - [`IntervalOpen`](crate::intervals::IntervalOpen) with [`IntervalOpen`](crate::intervals::IntervalOpen) → [`IntervalOpen`](crate::intervals::IntervalOpen)
/// - [`IntervalLowerClosedUpperOpen`](crate::intervals::IntervalLowerClosedUpperOpen) with [`IntervalLowerClosedUpperOpen`](crate::intervals::IntervalLowerClosedUpperOpen) → [`IntervalLowerClosedUpperOpen`](crate::intervals::IntervalLowerClosedUpperOpen)
/// - [`IntervalLowerOpenUpperClosed`](crate::intervals::IntervalLowerOpenUpperClosed) with [`IntervalLowerOpenUpperClosed`](crate::intervals::IntervalLowerOpenUpperClosed) → [`IntervalLowerOpenUpperClosed`](crate::intervals::IntervalLowerOpenUpperClosed)
///
/// ### Heterogeneous Implementations
/// All combinations between different interval types, following boundary inclusion rules:
/// - [`IntervalClosed`](crate::intervals::IntervalClosed) with [`IntervalOpen`](crate::intervals::IntervalOpen) → Result depends on boundary positions (e.g., [`IntervalLowerClosedUpperOpen`](crate::intervals::IntervalLowerClosedUpperOpen))
/// - [`IntervalClosed`](crate::intervals::IntervalClosed) with [`IntervalLowerClosedUpperOpen`](crate::intervals::IntervalLowerClosedUpperOpen) → Result depends on boundary positions  
/// - [`IntervalClosed`](crate::intervals::IntervalClosed) with [`IntervalLowerOpenUpperClosed`](crate::intervals::IntervalLowerOpenUpperClosed) → Result depends on boundary positions
/// - And all symmetric variants...
///
/// ### Enum Implementation
/// - [`IntervalFinitePositiveLength`](crate::intervals::IntervalFinitePositiveLength) with [`IntervalFinitePositiveLength`](crate::intervals::IntervalFinitePositiveLength) → [`IntervalFinitePositiveLength`](crate::intervals::IntervalFinitePositiveLength)
///
/// ## Performance Characteristics
///
/// ### Time Complexity
/// - **All operations**: O(1) - constant time regardless of interval types
/// - **Boundary analysis**: O(1) - simple comparisons and type matching
/// - **Result construction**: O(1) - direct value assignment
///
/// ### Space Complexity
/// - **Memory usage**: O(1) - no additional allocation beyond result interval
/// - **Stack usage**: Minimal - simple function calls with value parameters
/// - **Cache efficiency**: Excellent - operates on compact interval data
///
/// ### Scalar Type Performance Impact
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::{RealNative64StrictFiniteInDebug, RealNative64StrictFinite};
///
/// // Performance comparison across scalar types
/// type FastInterval = IntervalClosed<f64>;
/// type OptimalInterval = IntervalClosed<RealNative64StrictFiniteInDebug>;
/// type SafeInterval = IntervalClosed<RealNative64StrictFinite>;
///
/// // All have nearly identical hull performance:
/// // - f64: Maximum speed, no validation overhead
/// // - RealNative64StrictFiniteInDebug: Same speed as f64 in release builds
/// // - RealNative64StrictFinite: Small overhead for validation
/// ```
///
/// ## Error Handling and Edge Cases
///
/// ### Compile-Time Safety
/// ```rust
/// use grid1d::intervals::*;
///
/// // This won't compile - scalar type mismatch:
/// // let interval_f64 = IntervalClosed::new(1.0_f64, 2.0_f64);
/// // let interval_f32 = IntervalClosed::new(1.0_f32, 2.0_f32);
/// // let hull = interval_f64.hull(&interval_f32); // ERROR!
/// ```
///
/// ### Precision Considerations
/// ```rust
/// use grid1d::intervals::*;
///
/// // Very small intervals
/// let tiny1 = IntervalClosed::new(0.0, f64::EPSILON);
/// let tiny2 = IntervalClosed::new(f64::EPSILON, 2.0 * f64::EPSILON);
///
/// let hull = tiny1.hull(&tiny2);
/// // Result: [0.0, 2ε] - mathematically correct even for tiny intervals
/// ```
///
/// ## Integration with Other Traits
///
/// ### Containment Verification
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Verify that hull satisfies containment property
/// fn verify_hull_containment<I1, I2>(a: &I1, b: &I2) -> bool
/// where
///     I1: IntervalHull<I2> + Clone,
///     I2: IntervalFinitePositiveLengthTrait<RealType = I1::RealType> + Clone,
///     I1::Output: Contains<RealType = I1::RealType>,
///     Interval<I1::RealType>: From<I1> + From<I2> + From<I1::Output>,
/// {
///     let hull = a.hull(b);
///     let hull_general: Interval<I1::RealType> = hull.into();
///     let a_general: Interval<I1::RealType> = a.clone().into();
///     let b_general: Interval<I1::RealType> = b.clone().into();
///     
///     hull_general.contains_interval(&a_general) &&
///     hull_general.contains_interval(&b_general)
/// }
/// ```
///
/// ### Set Operations Integration
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Compare hull with union operation
/// fn hull_vs_union_comparison() {
///     let a = IntervalClosed::new(1.0, 3.0);
///     let b = IntervalClosed::new(2.0, 5.0);
///     
///     // Hull always produces a single connected interval
///     let hull = a.hull(&b);
///     
///     // Union might produce disjoint intervals (but not in this case)
///     let union = a.union(&b);
///     
///     match union {
///         IntervalUnion::SingleConnected(connected) => {
///             // When union is connected, it should match the hull
///             // (modulo boundary type differences)
///         }
///         IntervalUnion::TwoDisjoint { .. } => {
///             // Hull always connects disjoint intervals
///             // This is where hull differs from union
///         }
///     }
/// }
/// ```
///
/// ## Mathematical Foundations and Proofs
///
/// ### Correctness Theorem
/// For any intervals `A` and `B` with finite positive length:
/// ```text
/// hull(A, B) = [min(inf A, inf B), max(sup A, sup B)]
/// ```
/// where boundary inclusion follows the most inclusive principle.
///
/// ### Proof Sketch of Containment Property
/// 1. **Lower bound**: `min(inf A, inf B) ≤ inf A` and `min(inf A, inf B) ≤ inf B`
/// 2. **Upper bound**: `max(sup A, sup B) ≥ sup A` and `max(sup A, sup B) ≥ sup B`
/// 3. **Boundary inclusion**: Most inclusive boundaries ensure all points in A ∪ B are contained
/// 4. **Therefore**: `A ⊆ hull(A, B)` and `B ⊆ hull(A, B)` ∎
///
/// ### Proof Sketch of Minimality Property
/// 1. **Assumption**: Interval C contains both A and B
/// 2. **Lower bound**: `inf C ≤ inf A` and `inf C ≤ inf B` ⟹ `inf C ≤ min(inf A, inf B)`
/// 3. **Upper bound**: `sup C ≥ sup A` and `sup C ≥ sup B` ⟹ `sup C ≥ max(sup A, sup B)`
/// 4. **Therefore**: `hull(A, B) ⊆ C` ∎
///
/// ## Best Practices and Recommendations
///
/// ### When to Use [`IntervalHull`]
/// - **Bounding box computation**: Find minimal interval containing multiple regions
/// - **Range analysis**: Determine combined range of multiple functions
/// - **Geometric algorithms**: Convex hull computation in 1D space
/// - **Data analysis**: Find overall range of multiple datasets
/// - **Optimization**: Combine constraint domains
///
/// ### Avoiding Common Pitfalls
/// ```rust
/// use grid1d::intervals::*;
///
/// // WRONG: Assuming hull preserves original boundary types
/// fn incorrect_assumption() {
///     let closed = IntervalClosed::new(1.0, 3.0);
///     let open = IntervalOpen::new(2.0, 5.0);
///     let hull = closed.hull(&open);
///     
///     // DON'T assume the result is closed just because one input was closed
///     // The result depends on boundary inclusion rules
/// }
///
/// // CORRECT: Handle all possible result types
/// fn correct_handling() {
///     let closed = IntervalClosed::new(1.0, 3.0);
///     let open = IntervalOpen::new(2.0, 5.0);
///     let hull = closed.hull(&open);
///     
///     match hull {
///         IntervalFinitePositiveLength::Closed(_) => { /* Handle closed */ }
///         IntervalFinitePositiveLength::Open(_) => { /* Handle open */ }
///         IntervalFinitePositiveLength::LowerClosedUpperOpen(_) => { /* Handle half-open */ }
///         IntervalFinitePositiveLength::LowerOpenUpperClosed(_) => { /* Handle half-open */ }
///     }
/// }
/// ```
///
/// The [`IntervalHull`] trait is fundamental for interval arithmetic and computational geometry
/// applications, providing mathematically sound and computationally efficient convex hull
/// operations while maintaining the library's strong type safety guarantees.
///
/// ## Support for All Interval Types
///
/// This trait is **fully generalized** to compute the convex hull between **any two intervals** implementing [`IntervalTrait`], including:
/// - **Bounded intervals**: [`IntervalClosed`](crate::intervals::IntervalClosed), [`IntervalOpen`](crate::intervals::IntervalOpen), [`IntervalLowerClosedUpperOpen`](crate::intervals::IntervalLowerClosedUpperOpen), [`IntervalLowerOpenUpperClosed`](crate::intervals::IntervalLowerOpenUpperClosed)
/// - **Half-unbounded intervals**: [`IntervalLowerClosedUpperUnbounded`](crate::intervals::IntervalLowerClosedUpperUnbounded), [`IntervalLowerOpenUpperUnbounded`](crate::intervals::IntervalLowerOpenUpperUnbounded), [`IntervalLowerUnboundedUpperClosed`](crate::intervals::IntervalLowerUnboundedUpperClosed), [`IntervalLowerUnboundedUpperOpen`](crate::intervals::IntervalLowerUnboundedUpperOpen)
/// - **Fully unbounded**: [`IntervalLowerUnboundedUpperUnbounded`](crate::intervals::IntervalLowerUnboundedUpperUnbounded)
/// - **Singleton intervals**: [`IntervalSingleton`](crate::intervals::IntervalSingleton)
/// - **Enum types**: [`Interval`], [`IntervalFiniteLength`](crate::intervals::IntervalFiniteLength), [`IntervalInfiniteLength`](crate::intervals::IntervalInfiniteLength), [`IntervalFinitePositiveLength`](crate::intervals::IntervalFinitePositiveLength)
///
/// ### Hull Rules for Different Interval Types
///
/// The hull operation follows a fundamental principle:
///
/// **If ANY interval is unbounded in a direction, the hull is unbounded in that direction.**
///
/// Specifically:
/// - **Both bounded**: Returns smallest bounded interval containing both (specific bounded type)
/// - **One or both unbounded above**: Returns interval unbounded above with minimum lower bound
/// - **One or both unbounded below**: Returns interval unbounded below with maximum upper bound
/// - **Both fully unbounded**: Returns the universal interval `(-∞, +∞)`
///
/// ### Examples with Unbounded Intervals
///
/// ```rust
/// use grid1d::intervals::*;
///
/// // Case 1: Both bounded → bounded result
/// let bounded1 = IntervalClosed::new(0.0, 2.0);  // [0, 2]
/// let bounded2 = IntervalClosed::new(1.0, 3.0);  // [1, 3]
/// let hull = bounded1.hull(&bounded2);           // [0, 3]
///
/// // Case 2: Bounded with half-unbounded → unbounded result
/// let bounded = IntervalClosed::new(0.0, 2.0);              // [0, 2]
/// let unbounded = IntervalLowerClosedUpperUnbounded::new(1.0);  // [1, +∞)
/// let hull = bounded.hull(&unbounded);                       // [0, +∞)
/// // Explanation: Takes min lower bound (0) and unbounded upper
///
/// // Case 3: Bounded with opposite-direction unbounded → fully unbounded
/// let bounded = IntervalClosed::new(-2.0, 1.0);              // [-2, 1]
/// let upper_unbounded = IntervalLowerUnboundedUpperClosed::new(0.0);  // (-∞, 0]
/// let hull = bounded.hull(&upper_unbounded);                  // (-∞, 1]
/// // Explanation: Unbounded below, max upper bound (1)
///
/// // Case 4: Two half-unbounded in same direction → half-unbounded result
/// let unbounded1 = IntervalLowerClosedUpperUnbounded::new(0.0);  // [0, +∞)
/// let unbounded2 = IntervalLowerClosedUpperUnbounded::new(5.0);  // [5, +∞)
/// let hull = unbounded1.hull(&unbounded2);                       // [0, +∞)
/// // Explanation: Min lower bound (0), both unbounded above
///
/// // Case 5: Mixed boundary types with unbounded
/// let open = IntervalOpen::new(0.0, 2.0);                        // (0, 2)
/// let unbounded = IntervalLowerClosedUpperUnbounded::new(1.5);   // [1.5, +∞)
/// let hull = open.hull(&unbounded);                              // (0, +∞)
/// // Explanation: Open lower wins (more restrictive), unbounded upper
///
/// // Case 6: Fully unbounded with any interval → fully unbounded
/// let bounded = IntervalClosed::new(0.0, 10.0);     // [0, 10]
/// let fully_unbounded = IntervalLowerUnboundedUpperUnbounded::new();  // (-∞, +∞)
/// let hull = bounded.hull(&fully_unbounded);        // (-∞, +∞)
/// ```
///
/// ### Return Type Strategy
///
/// The trait uses different output types depending on the input combinations:
///
/// - **Bounded-to-bounded**: Returns [`IntervalFinitePositiveLength<RealType>`](crate::intervals::IntervalFinitePositiveLength) to preserve type specificity and performance
/// - **Bounded-to-unbounded**: Returns [`Interval<RealType>`] (universal enum) to accommodate any result type
/// - **Unbounded-to-bounded**: Returns [`Interval<RealType>`]
/// - **Unbounded-to-unbounded**: Returns [`Interval<RealType>`]
/// - **Using enum types**: Always returns [`Interval<RealType>`]
///
/// This design provides optimal performance for bounded intervals while supporting full generality.
pub trait IntervalHull<Other: IntervalTrait<RealType = Self::RealType>>: IntervalTrait {
    /// The type of interval returned by the hull operation.
    ///
    /// This associated type ensures type safety while allowing different implementations
    /// to return the most appropriate interval type based on their boundary semantics.
    /// The output type must implement [`IntervalTrait`] and use the same scalar type
    /// as the input intervals.
    ///
    /// For generalized hulls, the output is typically the universal [`Interval<RealType>`]
    /// enum which can represent any interval type (bounded, unbounded, etc.).
    type Output: IntervalTrait<RealType = Self::RealType>;

    /// Computes the convex hull (interval hull) between this interval and another.
    ///
    /// The convex hull is the smallest interval that contains both input intervals,
    /// following the **most inclusive boundary principle**:
    /// - Takes the minimum of lower bounds with most inclusive boundary type
    /// - Takes the maximum of upper bounds with most inclusive boundary type
    /// - Open boundaries are less inclusive than closed boundaries
    /// - Handles unbounded intervals correctly
    ///
    /// ## Mathematical Guarantee
    ///
    /// The result `H = self.hull(other)` satisfies:
    /// - **Containment**: `self ⊆ H` and `other ⊆ H`
    /// - **Minimality**: If `self ⊆ I` and `other ⊆ I`, then `H ⊆ I`
    /// - **Commutativity**: `self.hull(other) = other.hull(self)`
    ///
    /// ## Parameters
    ///
    /// - `other`: Another interval implementing [`IntervalTrait`] with the same scalar type
    ///
    /// ## Returns
    ///
    /// An interval of type [`Self::Output`] that represents the convex hull.
    /// The exact type depends on the boundary types and boundedness of the input intervals.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// // Same types → preserve type when possible
    /// let a = IntervalClosed::new(1.0, 3.0);  // [1, 3]
    /// let b = IntervalClosed::new(2.0, 5.0);  // [2, 5]
    /// let hull = a.hull(&b);                  // [1, 5]
    ///
    /// // Different types → follow inclusion rules
    /// let closed = IntervalClosed::new(1.0, 3.0);  // [1, 3]
    /// let open = IntervalOpen::new(2.0, 5.0);      // (2, 5)
    /// let hull = closed.hull(&open);               // [1, 5) - closed lower wins, open upper wins
    ///
    /// // With unbounded intervals
    /// let bounded = IntervalClosed::new(0.0, 2.0);
    /// let unbounded = IntervalLowerClosedUpperUnbounded::new(1.0);
    /// let hull = bounded.hull(&unbounded);  // [0, +∞)
    /// ```
    fn hull(&self, other: &Other) -> Self::Output;
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// Core trait for point containment testing in mathematical intervals.
///
/// The [`Contains`] trait provides the fundamental operation for testing whether a specific
/// point belongs to an interval. This trait forms the foundation for all point-based queries
/// and is complemented by the [`contains_interval`](Contains::contains_interval) method
/// for interval-to-interval containment testing.
///
/// ## Mathematical Foundation
///
/// Point containment is the most basic operation in interval mathematics. For any interval `I`
/// and point `x`, the containment test `x ∈ I` determines whether the point lies within the
/// interval according to its boundary conditions:
///
/// - **Closed intervals** `[a,b]`: `x ∈ [a,b] ⟺ a ≤ x ≤ b`
/// - **Open intervals** `(a,b)`: `x ∈ (a,b) ⟺ a < x < b`
/// - **Half-open intervals** `[a,b)`: `x ∈ [a,b) ⟺ a ≤ x < b`
/// - **Half-open intervals** `(a,b]`: `x ∈ (a,b] ⟺ a < x ≤ b`
/// - **Singleton intervals** `{a}`: `x ∈ {a} ⟺ x = a`
/// - **Unbounded intervals**: Various combinations with infinite extents
///
/// ## Design Philosophy
///
/// The [`Contains`] trait is intentionally minimal and focused:
///
/// - **Single Responsibility**: Only handles point containment, not interval containment
/// - **Generic Design**: Works with any scalar type implementing [`RealScalar`]
/// - **Performance First**: Designed for O(1) operations with minimal overhead
/// - **Type Safety**: Prevents containment queries with incompatible types
/// - **Mathematical Correctness**: Respects boundary semantics exactly
///
/// ## Relationship with Interval Containment
///
/// Point containment ([`contains_point`](Contains::contains_point)) and interval containment
/// ([`contains_interval`](Contains::contains_interval)) are related but distinct operations:
///
/// ```text
/// Point Containment:     x ∈ I     (scalar ∈ interval)
/// Interval Containment:  A ⊆ B     (interval ⊆ interval)
/// ```
///
/// ### Key Differences
///
/// | Aspect | Point Containment | Interval Containment |
/// |--------|-------------------|---------------------|
/// | **Input** | Single scalar value | Another interval |
/// | **Output** | `bool` | `bool` |
/// | **Complexity** | O(1) - at most 2 comparisons | O(1) - boundary logic |
/// | **Use Cases** | Point queries, evaluation domains | Set operations, subset testing |
/// | **Mathematical Basis** | Element membership `x ∈ I` | Subset relation `A ⊆ B` |
///
/// ### Mathematical Relationship
///
/// Interval containment can be expressed in terms of point containment:
/// ```text
/// A ⊆ B ⟺ ∀x ∈ A: x ∈ B
/// ```
/// However, for efficiency, interval containment is implemented by comparing boundaries
/// rather than testing all points.
///
/// ## Core Operation
///
/// ### [`contains_point`](Contains::contains_point)
/// Tests whether a specific point belongs to the interval.
///
/// **Signature**: `fn contains_point(&self, point: &RealType) -> bool`
///
/// **Behavior**:
/// - Returns `true` if the point is within the interval
/// - Returns `false` if the point is outside the interval
/// - Respects boundary inclusion/exclusion semantics
/// - Always O(1) complexity regardless of interval type
///
/// ## Usage Examples
///
/// ### Basic Point Containment
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::{New, TryNew};
///
/// type Real = RealNative64StrictFiniteInDebug;
///
/// let closed = IntervalClosed::new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// let open = IntervalOpen::new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// let singleton = IntervalSingleton::new(Real::try_new(0.5).unwrap());
///
/// // Closed interval includes boundaries
/// assert!(closed.contains_point(&Real::try_new(0.0).unwrap()));   // Lower bound
/// assert!(closed.contains_point(&Real::try_new(0.5).unwrap()));   // Interior
/// assert!(closed.contains_point(&Real::try_new(1.0).unwrap()));   // Upper bound
///
/// // Open interval excludes boundaries
/// assert!(!open.contains_point(&Real::try_new(0.0).unwrap()));    // Lower bound excluded
/// assert!(open.contains_point(&Real::try_new(0.5).unwrap()));     // Interior
/// assert!(!open.contains_point(&Real::try_new(1.0).unwrap()));    // Upper bound excluded
///
/// // Singleton contains only exact match
/// assert!(singleton.contains_point(&Real::try_new(0.5).unwrap())); // Exact match
/// assert!(!singleton.contains_point(&Real::try_new(0.4).unwrap())); // Any other value
/// ```
///
/// ### Comparison with Interval Containment
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let outer = IntervalClosed::new(0.0, 2.0);    // [0, 2]
/// let inner = IntervalClosed::new(0.5, 1.5);    // [0.5, 1.5]
/// let point_interval = IntervalSingleton::new(1.0); // {1}
///
/// // Point containment: test specific values
/// assert!(outer.contains_point(&1.0));          // Point 1.0 ∈ [0, 2] ✓
/// assert!(inner.contains_point(&1.0));          // Point 1.0 ∈ [0.5, 1.5] ✓
///
/// // Interval containment: test subset relationships
/// assert!(outer.contains_interval(&inner));      // [0, 2] ⊇ [0.5, 1.5] ✓
/// assert!(outer.contains_interval(&point_interval)); // [0, 2] ⊇ {1} ✓
/// assert!(inner.contains_interval(&point_interval)); // [0.5, 1.5] ⊇ {1} ✓
/// assert!(!inner.contains_interval(&outer));     // [0.5, 1.5] ⊉ [0, 2] ✗
/// ```
///
/// ### Generic Programming with Point Containment
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// /// Count how many test points are contained in an interval
/// fn count_contained_points<I, T>(interval: &I, test_points: &[T]) -> usize
/// where
///     I: Contains<RealType = T>,
///     T: RealScalar,
/// {
///     test_points.iter()
///         .filter(|&point| interval.contains_point(point))
///         .count()
/// }
///
/// /// Filter points to only those contained in an interval
/// fn filter_points_in_interval<I, T>(interval: &I, points: Vec<T>) -> Vec<T>
/// where
///     I: Contains<RealType = T>,
///     T: RealScalar,
/// {
///     points.into_iter()
///         .filter(|point| interval.contains_point(point))
///         .collect()
/// }
///
/// let interval = IntervalClosed::new(-1.0, 1.0);
/// let test_points = vec![-2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0];
///
/// let count = count_contained_points(&interval, &test_points);
/// assert_eq!(count, 5); // -1.0, -0.5, 0.0, 0.5, 1.0
///
/// let filtered = filter_points_in_interval(&interval, test_points);
/// assert_eq!(filtered, vec![-1.0, -0.5, 0.0, 0.5, 1.0]);
/// ```
///
/// ## Performance Characteristics
///
/// ### Time Complexity
/// - **All interval types**: O(1) regardless of interval size or type
/// - **Bounded intervals**: At most 2 comparisons (lower ≤ x ≤ upper)
/// - **Semi-bounded intervals**: 1 comparison (x ≥ lower or x ≤ upper)
/// - **Unbounded intervals**: Constant time (always true)
/// - **Singletons**: 1 equality comparison (x == value)
///
/// ### Space Complexity
/// - **Memory usage**: O(1) - no additional allocation
/// - **Stack usage**: Minimal - simple comparison operations
/// - **Cache efficiency**: Excellent - operates on interval bounds directly
///
/// ### Scalar Type Performance Impact
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::{RealNative64StrictFiniteInDebug, RealNative64StrictFinite, RealScalar};
///
/// // All these have nearly identical performance for point containment:
/// type FastInterval = IntervalClosed<f64>;
/// type OptimalInterval = IntervalClosed<RealNative64StrictFiniteInDebug>;
/// type SafeInterval = IntervalClosed<RealNative64StrictFinite>;
///
/// fn benchmark_point_containment<T: RealScalar>(
///     interval: &IntervalClosed<T>,
///     test_point: &T
/// ) -> bool {
///     // This compiles to identical assembly for f64 and RealNative64StrictFiniteInDebug
///     // Slight overhead for RealNative64StrictFinite due to validation
///     interval.contains_point(test_point)
/// }
/// ```
///
/// ## Boundary Semantics and Edge Cases
///
/// ### Boundary Inclusion Rules
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// // Demonstrate different boundary behaviors
/// let closed = IntervalClosed::new(0.0, 1.0);           // [0, 1]
/// let open = IntervalOpen::new(0.0, 1.0);               // (0, 1)
/// let left_open = IntervalLowerOpenUpperClosed::new(0.0, 1.0);  // (0, 1]
/// let right_open = IntervalLowerClosedUpperOpen::new(0.0, 1.0); // [0, 1)
///
/// let lower_bound = 0.0;
/// let upper_bound = 1.0;
/// let interior = 0.5;
///
/// // Lower boundary behavior
/// assert!(closed.contains_point(&lower_bound));      // [0,1] includes 0
/// assert!(!open.contains_point(&lower_bound));       // (0,1) excludes 0
/// assert!(!left_open.contains_point(&lower_bound));  // (0,1] excludes 0
/// assert!(right_open.contains_point(&lower_bound));  // [0,1) includes 0
///
/// // Upper boundary behavior
/// assert!(closed.contains_point(&upper_bound));      // [0,1] includes 1
/// assert!(!open.contains_point(&upper_bound));       // (0,1) excludes 1
/// assert!(left_open.contains_point(&upper_bound));   // (0,1] includes 1
/// assert!(!right_open.contains_point(&upper_bound)); // [0,1) excludes 1
///
/// // Interior points (always included for positive-length intervals)
/// assert!(closed.contains_point(&interior));
/// assert!(open.contains_point(&interior));
/// assert!(left_open.contains_point(&interior));
/// assert!(right_open.contains_point(&interior));
/// ```
///
/// ### Floating-Point Precision Considerations
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalClosed::new(0.0, 1.0);
///
/// // Exact boundary values
/// assert!(interval.contains_point(&0.0));
/// assert!(interval.contains_point(&1.0));
///
/// // Values very close to boundaries
/// assert!(interval.contains_point(&f64::EPSILON));           // Just above 0
/// assert!(interval.contains_point(&(1.0 - f64::EPSILON)));   // Just below 1
/// assert!(!interval.contains_point(&-f64::EPSILON));         // Just below 0
/// assert!(!interval.contains_point(&(1.0 + f64::EPSILON)));  // Just above 1
///
/// // For very small intervals, be aware of precision limits
/// let tiny = IntervalClosed::new(1.0, 1.0 + f64::EPSILON);
/// assert!(tiny.contains_point(&1.0));
/// assert!(tiny.contains_point(&(1.0 + f64::EPSILON)));
/// assert_eq!(tiny.length().into_inner(), f64::EPSILON);
/// ```
///
/// ## Implementation Requirements
///
/// Types implementing [`Contains`] must guarantee:
///
/// ### Mathematical Correctness
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// // These properties must hold for all implementations:
/// fn verify_contains_properties<I, T>(interval: &I, point: &T)
/// where
///     I: Contains<RealType = T>,
///     T: RealScalar,
/// {
///     let result = interval.contains_point(point);
///     
///     // Consistency: repeated calls must give same result
///     assert_eq!(result, interval.contains_point(point));
///     
///     // The result should be deterministic for the same inputs
///     assert_eq!(result, interval.contains_point(&point.clone()));
/// }
/// ```
///
/// ### Performance Requirements
/// - **O(1) time complexity**: All implementations must be constant time
/// - **No allocation**: Point containment should not allocate memory
/// - **Minimal computation**: Use the most efficient boundary checks possible
///
/// ### Type Safety Requirements
/// - **Scalar type consistency**: Point type must match interval's scalar type
/// - **Reference semantics**: Accept points by reference to avoid unnecessary copies
/// - **Generic compatibility**: Work with any [`RealScalar`] implementation
///
/// ## Advanced Usage Patterns
///
/// ### Predicate Functions and Filtering
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// /// Create a predicate function from an interval
/// fn interval_predicate<I, T>(interval: I) -> impl Fn(&T) -> bool
/// where
///     I: Contains<RealType = T>,
///     T: RealScalar,
/// {
///     move |point: &T| interval.contains_point(point)
/// }
///
/// /// Filter a dataset based on multiple interval constraints
/// fn filter_by_intervals<T>(
///     data: Vec<T>,
///     constraints: &[impl Contains<RealType = T>]
/// ) -> Vec<T>
/// where
///     T: RealScalar,
/// {
///     data.into_iter()
///         .filter(|point| {
///             constraints.iter().all(|interval| interval.contains_point(point))
///         })
///         .collect()
/// }
/// ```
///
/// ### Statistical Analysis
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Compute statistics for points within an interval
/// fn interval_statistics<I>(
///     interval: &I,
///     data: &[f64]
/// ) -> Option<(f64, f64, usize)>
/// where
///     I: Contains<RealType = f64>,
/// {
///     let contained_points: Vec<f64> = data.iter()
///         .filter(|&x| interval.contains_point(x))
///         .cloned()
///         .collect();
///         
///     if contained_points.is_empty() {
///         return None;
///     }
///     
///     let count = contained_points.len();
///     let sum: f64 = contained_points.iter().sum();
///     let mean = sum / count as f64;
///     let variance = contained_points.iter()
///         .map(|x| (x - mean).powi(2))
///         .sum::<f64>() / count as f64;
///     
///     Some((mean, variance, count))
/// }
///
/// let interval = IntervalClosed::new(-1.0, 1.0);
/// let data = vec![-2.0, -0.5, 0.0, 0.5, 2.0];
///
/// if let Some((mean, variance, count)) = interval_statistics(&interval, &data) {
///     println!("Points in interval: count={}, mean={}, variance={}", count, mean, variance);
/// }
/// ```
///
/// ## Common Pitfalls and Best Practices
///
/// ### Avoiding Common Mistakes
/// ```rust
/// use grid1d::intervals::*;
///
/// // WRONG: Assuming all intervals include their "endpoints"
/// fn naive_endpoint_test<I>(interval: &I) -> bool
/// where
///     I: Contains<RealType = f64> + GetLowerBoundValue<LowerBoundValue = f64> + GetUpperBoundValue<UpperBoundValue = f64>,
/// {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     // This fails for open intervals!
///     interval.contains_point(&lower) && interval.contains_point(&upper)
/// }
///
/// // CORRECT: Test boundary inclusion explicitly
/// fn proper_boundary_test<I>(interval: &I) -> (bool, bool)
/// where
///     I: Contains<RealType = f64> + GetLowerBoundValue<LowerBoundValue = f64> + GetUpperBoundValue<UpperBoundValue = f64>,
/// {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     (interval.contains_point(&lower), interval.contains_point(&upper))
/// }
///
/// let closed = IntervalClosed::new(0.0, 1.0);
/// let open = IntervalOpen::new(0.0, 1.0);
///
/// assert!(naive_endpoint_test(&closed));     // Works for closed
/// assert!(!naive_endpoint_test(&open));      // Fails for open (correct behavior)
///
/// assert_eq!(proper_boundary_test(&closed), (true, true));   // Both included
/// assert_eq!(proper_boundary_test(&open), (false, false));   // Both excluded
/// ```
///
/// ### Performance Best Practices
/// ```rust
/// use grid1d::intervals::*;
///
/// // GOOD: Reuse intervals for multiple point tests
/// fn efficient_batch_testing(interval: &IntervalClosed<f64>, points: &[f64]) -> Vec<bool> {
///     points.iter()
///         .map(|point| interval.contains_point(point))
///         .collect()
/// }
///
/// // AVOID: Creating intervals repeatedly for the same bounds
/// fn inefficient_testing(lower: f64, upper: f64, points: &[f64]) -> Vec<bool> {
///     points.iter()
///         .map(|point| {
///             let interval = IntervalClosed::new(lower, upper); // Wasteful!
///             interval.contains_point(point)
///         })
///         .collect()
/// }
/// ```
///
/// ## Mathematical Properties and Guarantees
///
/// The [`Contains`] trait implementations maintain these essential properties:
///
/// ### Consistency Properties
/// - **Deterministic**: Same input always produces same output
/// - **Reflexive**: For any point in the interval, containment is stable
/// - **Boundary Correct**: Respects mathematical interval notation exactly
///
/// ### Performance Properties  
/// - **Constant Time**: O(1) for all interval types and point queries
/// - **Memory Efficient**: No allocation, minimal stack usage
/// - **Cache Friendly**: Operations on compact data structures
///
/// ### Type Safety Properties
/// - **Scalar Consistency**: Point and interval scalar types must match
/// - **Generic Correctness**: Works with any [`RealScalar`] implementation
/// - **Reference Safety**: Accepts points by reference safely
///
/// These guarantees are preserved across all interval types and scalar types,
/// ensuring that point containment testing is both mathematically correct and
/// computationally efficient throughout the library.
pub trait Contains: IntervalBoundsRuntime + Clone + PartialEq {
    /// Tests whether a point is contained within this interval.
    ///
    /// This is the fundamental operation that all interval types must implement.
    /// The behavior depends on the specific interval type and its boundary conditions.
    ///
    /// # Boundary Behavior
    ///
    /// - **Closed intervals** `[a, b]`: Include both endpoints
    /// - **Open intervals** `(a, b)`: Exclude both endpoints  
    /// - **Half-open intervals**: Include one endpoint, exclude the other
    /// - **Unbounded intervals**: Have infinite extent in one or both directions
    /// - **Singleton intervals**: Contain exactly one point
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use try_create::New;
    ///
    /// let closed = IntervalClosed::new(0.0, 1.0);
    /// assert!(closed.contains_point(&0.0));    // Endpoints included
    /// assert!(closed.contains_point(&1.0));    // Endpoints included
    /// assert!(closed.contains_point(&0.5));    // Interior point
    ///
    /// let open = IntervalOpen::new(0.0, 1.0);
    /// assert!(!open.contains_point(&0.0));     // Endpoints excluded
    /// assert!(!open.contains_point(&1.0));     // Endpoints excluded
    /// assert!(open.contains_point(&0.5));      // Interior point
    ///
    /// let half_open = IntervalLowerOpenUpperClosed::new(0.0, 1.0);
    /// assert!(!half_open.contains_point(&0.0)); // Lower bound excluded
    /// assert!(half_open.contains_point(&1.0));  // Upper bound included
    ///
    /// let singleton = IntervalSingleton::new(42.0);
    /// assert!(singleton.contains_point(&42.0));  // Exact match
    /// assert!(!singleton.contains_point(&41.0)); // No match
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1) for all interval types, involving at most two comparisons.
    fn contains_point(&self, x: &Self::RealType) -> bool;

    /// Tests whether a point is within `epsilon` distance of this interval.
    ///
    /// Returns `true` if the point `x` lies inside the interval expanded by `epsilon`
    /// on both sides, i.e. if `dist(x, I) ≤ epsilon`. Concretely:
    ///
    /// - If the interval has a finite lower bound `a`: requires `x ≥ a − epsilon`
    /// - If the interval has a finite upper bound `b`: requires `x ≤ b + epsilon`
    /// - Unbounded sides impose no constraint
    ///
    /// # Notes
    ///
    /// The open/closed nature of the boundary is **ignored**: the expansion strip is always
    /// treated as closed. In particular, for `epsilon = 0` this function may return `true`
    /// for boundary points of open intervals where `contains_point` would return `false`.
    /// This behaviour is intentional—the typical use case is numerical tolerance checking
    /// in finite-element or grid methods where boundary semantics are irrelevant.
    ///
    /// # Arguments
    ///
    /// - `x`: the point to test.
    /// - `epsilon`: non-negative tolerance; use
    ///   [`NonNegativeRealScalar::try_new(0.0)`](num_valid::scalars::NonNegativeRealScalar) for
    ///   exact containment with boundary relaxation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use num_valid::scalars::NonNegativeRealScalar;
    /// use try_create::TryNew;
    ///
    /// let closed = IntervalClosed::new(0.0, 1.0);
    /// let eps = NonNegativeRealScalar::try_new(0.1).unwrap();
    ///
    /// // Interior point
    /// assert!(closed.contains_point_with_tolerance(&0.5, &eps));
    ///
    /// // Just outside — within tolerance
    /// assert!(closed.contains_point_with_tolerance(&-0.05, &eps));
    /// assert!(closed.contains_point_with_tolerance(&1.05, &eps));
    ///
    /// // Too far outside
    /// assert!(!closed.contains_point_with_tolerance(&-0.2, &eps));
    /// assert!(!closed.contains_point_with_tolerance(&1.2, &eps));
    ///
    /// // Open interval: boundary points are included when epsilon = 0
    /// let open = IntervalOpen::new(0.0, 1.0);
    /// let zero_eps = NonNegativeRealScalar::try_new(0.0).unwrap();
    /// assert!(open.contains_point_with_tolerance(&0.0, &zero_eps)); // differs from contains_point!
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1), involving at most two additions and two comparisons.
    #[inline(always)]
    fn contains_point_with_tolerance(
        &self,
        x: &Self::RealType,
        epsilon: &NonNegativeRealScalar<Self::RealType>,
    ) -> bool {
        let eps = epsilon.as_ref();

        // Check lower side: x >= lower_bound - epsilon  ⟺  x + epsilon >= lower_bound
        let lower_ok = match self.lower_bound_runtime() {
            None => true,
            Some(lower) => &(x.clone() + eps) >= lower.as_ref(),
        };

        if !lower_ok {
            return false;
        }

        // Check upper side: x <= upper_bound + epsilon  ⟺  x - epsilon <= upper_bound
        match self.upper_bound_runtime() {
            None => true,
            Some(upper) => x <= &(upper.as_ref().clone() + eps),
        }
    }

    /// Tests whether this interval completely contains another interval.
    ///
    /// Returns `true` if and only if every point in `other` is also contained in `self`.
    /// This includes proper handling of boundary conditions - for example, the closed
    /// interval `[0., 1.]` contains the open interval `(0., 1.)`, but not vice versa.
    ///
    /// # Mathematical Definition
    ///
    /// For intervals A and B, A contains B (A ⊇ B) if and only if:
    /// - The lower bound of A is ≤ the lower bound of B (with proper boundary handling)
    /// - The upper bound of A is ≥ the upper bound of B (with proper boundary handling)
    ///
    /// # Boundary Rules
    ///
    /// - Closed bounds can contain open bounds at the same value
    /// - Open bounds cannot contain closed bounds at the same value
    /// - Unbounded sides always contain any bounded side
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let outer = IntervalClosed::new(0.0, 2.0);       // [0, 2]
    /// let inner = IntervalOpen::new(0.5, 1.5);         // (0.5, 1.5)
    /// let boundary = IntervalClosed::new(0.0, 1.0);    // [0, 1]
    /// let open_boundary = IntervalOpen::new(0.0, 1.0); // (0, 1)
    ///
    /// assert!(outer.contains_interval(&inner));      // [0, 2] ⊇ (0.5, 1.5) ✓
    /// assert!(outer.contains_interval(&boundary));   // [0, 2] ⊇ [0, 1] ✓
    /// assert!(boundary.contains_interval(&open_boundary)); // [0, 1] ⊇ (0, 1) ✓
    /// assert!(!open_boundary.contains_interval(&boundary)); // (0, 1) ⊉ [0, 1] ✗
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1) and involves only bound comparisons.
    fn contains_interval<IntervalType: IntervalTrait<RealType = Self::RealType>>(
        &self,
        other: &IntervalType,
    ) -> bool {
        let lower_bound_b_is_contained =
            match (self.lower_bound_runtime(), other.lower_bound_runtime()) {
                // If the lower bound of `self` is unbounded, it will contain any other lower bound
                (None, _) => true,

                // If the lower bound of `self` is not unbounded while the lower bound of `other` is unbounded, `self` cannot contain `other`
                (_, None) => false,

                (Some(lower_bound_a), Some(lower_bound_b)) => lower_bound_a <= lower_bound_b,
            };

        let upper_bound_b_is_contained =
            match (self.upper_bound_runtime(), other.upper_bound_runtime()) {
                // If the upper bound of `self` is unbounded, it will contain any other upper bound
                (None, _) => true,

                // If the upper bound of `self` is not unbounded while the upper bound of `other` is unbounded, `self` cannot contain `other`
                (_, None) => false,

                (Some(upper_bound_a), Some(upper_bound_b)) => upper_bound_b <= upper_bound_a,
            };

        lower_bound_b_is_contained && upper_bound_b_is_contained
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// Common interface for intervals that have a finite lower bound.
///
/// The [`GetLowerBoundValue`] trait provides unified access to the lower bound of intervals
/// that have a finite lower boundary. This enables generic programming over intervals
/// with lower bounds while maintaining type safety and performance.
///
/// ## Implementing Types
///
/// All interval types with finite lower bounds implement this trait:
///
/// ### Bounded Intervals
/// - [`IntervalClosed`](crate::intervals::IntervalClosed): `[a, b]`, [`IntervalOpen`](crate::intervals::IntervalOpen): `(a, b)`
/// - [`IntervalLowerOpenUpperClosed`](crate::intervals::IntervalLowerOpenUpperClosed): `(a, b]`, [`IntervalLowerClosedUpperOpen`](crate::intervals::IntervalLowerClosedUpperOpen): `[a, b)`
///
/// ### Lower-Bounded, Upper-Unbounded Intervals
/// - [`IntervalLowerClosedUpperUnbounded`](crate::intervals::IntervalLowerClosedUpperUnbounded): `[a, +∞)`
/// - [`IntervalLowerOpenUpperUnbounded`](crate::intervals::IntervalLowerOpenUpperUnbounded): `(a, +∞)`
///
/// ## Core Operation
///
/// - [`lower_bound_value`](GetLowerBoundValue::lower_bound_value): Returns a reference to the lower bound value
///
/// This method provides **read-only access** with **zero computational cost**.
///
/// ## Usage Examples
///
/// ### Basic Lower Bound Access
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// type Real = RealNative64StrictFiniteInDebug;
///
/// let closed = IntervalClosed::new(
///     Real::try_new(-2.0).unwrap(),
///     Real::try_new(5.0).unwrap()
/// );
/// let unbounded = IntervalLowerClosedUpperUnbounded::new(
///     Real::try_new(0.0).unwrap()
/// );
///
/// assert_eq!(closed.lower_bound_value(), &-2.0);
/// assert_eq!(unbounded.lower_bound_value(), &0.0);
/// ```
///
/// ### Generic Programming Over Lower-Bounded Intervals
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// fn analyze_lower_bound<I, T>(interval: &I) -> String
/// where
///     I: GetLowerBoundValue<LowerBoundValue = T>,
///     T: RealScalar + std::fmt::Display,
/// {
///     format!("Lower bound: {}", interval.lower_bound_value())
/// }
///
/// let closed = IntervalClosed::new(-1.0, 1.0);
/// let unbounded = IntervalLowerOpenUpperUnbounded::new(5.0);
///
/// println!("{}", analyze_lower_bound(&closed));      // "Lower bound: -1"
/// println!("{}", analyze_lower_bound(&unbounded));   // "Lower bound: 5"
/// ```
///
/// ### Constraint Processing
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// fn find_minimum_lower_bound<I, T>(intervals: &[I]) -> Option<T>
/// where
///     I: GetLowerBoundValue<LowerBoundValue = T>,
///     T: RealScalar + Clone + PartialOrd,
/// {
///     intervals.iter()
///         .map(|interval| interval.lower_bound_value())
///         .min_by(|a, b| a.partial_cmp(b).unwrap())
///         .cloned()
/// }
///
/// let intervals = vec![
///     IntervalClosed::new(1.0, 5.0),
///     IntervalClosed::new(-2.0, 3.0),
///     IntervalClosed::new(0.0, 4.0),
/// ];
///
/// let min_lower = find_minimum_lower_bound(&intervals).unwrap();
/// assert_eq!(min_lower, -2.0);
/// ```
pub trait GetLowerBoundValue: Debug {
    /// The scalar type used for the lower bound value.
    type LowerBoundValue: RealScalar;

    /// Return the lower bound of the interval.
    ///
    /// This method provides read-only access to the interval's lower bound value.
    /// The returned reference is guaranteed to be valid for the lifetime of the interval.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let interval = IntervalClosed::new(1.0, 3.0);
    /// assert_eq!(interval.lower_bound_value(), &1.0);
    ///
    /// let lower_closed_interval = IntervalLowerClosedUpperUnbounded::new(5.0);
    /// let lower_open_interval = IntervalLowerOpenUpperUnbounded::new(10.0);
    ///
    /// assert_eq!(lower_closed_interval.lower_bound_value(), &5.0);
    /// assert_eq!(lower_open_interval.lower_bound_value(), &10.0);
    ///
    /// // Both intervals extend infinitely to the right
    /// assert!(lower_closed_interval.contains_point(&1000.0));
    /// assert!(lower_open_interval.contains_point(&1000.0));
    ///
    /// // But they differ in their treatment of the lower bound
    /// assert!(lower_closed_interval.contains_point(&5.0));   // [5, +∞) includes 5
    /// assert!(!lower_open_interval.contains_point(&10.0));   // (10, +∞) excludes 10
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1) and typically compiles to a simple memory access.
    /// There is no computational overhead regardless of the scalar type used.
    fn lower_bound_value(&self) -> &Self::LowerBoundValue;

    /// Check if the lower bound is closed (included in the interval).
    ///
    /// This method returns `true` if the lower bound value is part of the interval,
    /// and `false` if it is excluded. This corresponds to the mathematical distinction
    /// between closed bounds `[a` and open bounds `(a`.
    ///
    /// ## Mathematical Interpretation
    ///
    /// - **Closed lower bound** (`true`): The interval includes its lower bound value
    ///   - Mathematical notation: `[a, ...` where `x ≥ a`
    ///   - The boundary point `a` is contained in the interval
    ///
    /// - **Open lower bound** (`false`): The interval excludes its lower bound value
    ///   - Mathematical notation: `(a, ...` where `x > a`
    ///   - The boundary point `a` is not contained in the interval
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use num_valid::RealNative64StrictFiniteInDebug;
    /// use try_create::TryNew;
    ///
    /// type Real = RealNative64StrictFiniteInDebug;
    ///
    /// let closed = IntervalClosed::new(
    ///     Real::try_new(0.0).unwrap(),
    ///     Real::try_new(1.0).unwrap()
    /// );
    /// assert!(closed.is_lower_bound_closed());      // [0, 1] has closed lower bound
    ///
    /// let open = IntervalOpen::new(
    ///     Real::try_new(0.0).unwrap(),
    ///     Real::try_new(1.0).unwrap()
    /// );
    /// assert!(!open.is_lower_bound_closed());       // (0, 1) has open lower bound
    ///
    /// let half_open = IntervalLowerClosedUpperOpen::new(
    ///     Real::try_new(0.0).unwrap(),
    ///     Real::try_new(1.0).unwrap()
    /// );
    /// assert!(half_open.is_lower_bound_closed());   // [0, 1) has closed lower bound
    ///
    /// let other_half = IntervalLowerOpenUpperClosed::new(
    ///     Real::try_new(0.0).unwrap(),
    ///     Real::try_new(1.0).unwrap()
    /// );
    /// assert!(!other_half.is_lower_bound_closed()); // (0, 1] has open lower bound
    /// ```
    ///
    /// ## Relationship with Point Containment
    ///
    /// The lower bound closure directly affects point containment at the boundary:
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let closed = IntervalClosed::new(0.0, 1.0);
    /// let open = IntervalOpen::new(0.0, 1.0);
    ///
    /// // Closed lower bound contains the boundary value
    /// assert!(closed.is_lower_bound_closed());
    /// assert!(closed.contains_point(&0.0));        // Lower bound included
    ///
    /// // Open lower bound excludes the boundary value
    /// assert!(!open.is_lower_bound_closed());
    /// assert!(!open.contains_point(&0.0));         // Lower bound excluded
    /// ```
    ///
    /// ## Generic Programming Applications
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use num_valid::RealScalar;
    ///
    /// fn analyze_lower_boundary<I, T>(interval: &I) -> String
    /// where
    ///     I: GetLowerBoundValue<LowerBoundValue = T>,
    ///     T: RealScalar + std::fmt::Display,
    /// {
    ///     let bound_value = interval.lower_bound_value();
    ///     let inclusion = if interval.is_lower_bound_closed() {
    ///         "included"
    ///     } else {
    ///         "excluded"
    ///     };
    ///     
    ///     format!("Lower bound {} is {}", bound_value, inclusion)
    /// }
    ///
    /// let closed = IntervalClosed::new(-1.0, 1.0);
    /// let open = IntervalLowerOpenUpperClosed::new(-1.0, 1.0);
    ///
    /// assert_eq!(analyze_lower_boundary(&closed), "Lower bound -1 is included");
    /// assert_eq!(analyze_lower_boundary(&open), "Lower bound -1 is excluded");
    /// ```
    ///
    /// ## Performance
    ///
    /// This operation is O(1) and typically compiles to a simple constant or type-based
    /// determination. There is no computational overhead regardless of the scalar type used.
    fn is_lower_bound_closed(&self) -> bool;

    /// Check if the lower bound is open (excluded from the interval).
    ///
    /// This method returns `true` if the lower bound value is excluded from the interval,
    /// and `false` if it is included. This is the logical complement of [`is_lower_bound_closed()`](GetLowerBoundValue::is_lower_bound_closed).
    ///
    /// ## Mathematical Interpretation
    ///
    /// - **Open lower bound** (`true`): The interval excludes its lower bound value
    ///   - Mathematical notation: `(a, ...` where `x > a`
    ///   - The boundary point `a` is not contained in the interval
    ///
    /// - **Closed lower bound** (`false`): The interval includes its lower bound value
    ///   - Mathematical notation: `[a, ...` where `x ≥ a`
    ///   - The boundary point `a` is contained in the interval
    ///
    /// ## Relationship with `is_lower_bound_closed()`
    ///
    /// This method is defined as the logical complement of [`is_lower_bound_closed()`](GetLowerBoundValue::is_lower_bound_closed):
    /// ```text
    /// is_lower_bound_open() == !is_lower_bound_closed()
    /// ```
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use num_valid::RealNative64StrictFiniteInDebug;
    /// use try_create::TryNew;
    ///
    /// type Real = RealNative64StrictFiniteInDebug;
    ///
    /// let open = IntervalOpen::new(
    ///     Real::try_new(0.0).unwrap(),
    ///     Real::try_new(1.0).unwrap()
    /// );
    /// assert!(open.is_lower_bound_open());          // (0, 1) has open lower bound
    /// assert!(!open.is_lower_bound_closed());       // Complement relationship
    ///
    /// let closed = IntervalClosed::new(
    ///     Real::try_new(0.0).unwrap(),
    ///     Real::try_new(1.0).unwrap()
    /// );
    /// assert!(!closed.is_lower_bound_open());       // [0, 1] has closed lower bound
    /// assert!(closed.is_lower_bound_closed());      // Complement relationship
    ///
    /// let half_open = IntervalLowerOpenUpperClosed::new(
    ///     Real::try_new(0.0).unwrap(),
    ///     Real::try_new(1.0).unwrap()
    /// );
    /// assert!(half_open.is_lower_bound_open());     // (0, 1] has open lower bound
    /// assert!(!half_open.is_lower_bound_closed());  // Complement relationship
    /// ```
    ///
    /// ## Usage in Boundary Analysis
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use num_valid::RealScalar;
    ///
    /// fn check_boundary_types<I, T>(interval: &I) -> (bool, bool)
    /// where
    ///     I: GetLowerBoundValue<LowerBoundValue = T>,
    ///     T: RealScalar,
    /// {
    ///     let lower_open = interval.is_lower_bound_open();
    ///     let lower_closed = interval.is_lower_bound_closed();
    ///     
    ///     // These should always be complements
    ///     assert_eq!(lower_open, !lower_closed);
    ///     
    ///     (lower_open, lower_closed)
    /// }
    ///
    /// let open_interval = IntervalOpen::new(0.0, 1.0);
    /// let (is_open, is_closed) = check_boundary_types(&open_interval);
    /// assert!(is_open && !is_closed);
    ///
    /// let closed_interval = IntervalClosed::new(0.0, 1.0);
    /// let (is_open, is_closed) = check_boundary_types(&closed_interval);
    /// assert!(!is_open && is_closed);
    /// ```
    ///
    /// ## Strict Inequality Testing
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use num_valid::RealScalar;
    ///
    /// fn requires_strict_lower_bound<I, T>(interval: &I) -> bool
    /// where
    ///     I: GetLowerBoundValue<LowerBoundValue = T>,
    ///     T: RealScalar,
    /// {
    ///     // Check if the interval enforces x > lower_bound (strict inequality)
    ///     interval.is_lower_bound_open()
    /// }
    ///
    /// let strict_interval = IntervalOpen::new(0.0, 1.0);           // (0, 1) requires x > 0
    /// let inclusive_interval = IntervalClosed::new(0.0, 1.0);      // [0, 1] allows x ≥ 0
    ///
    /// assert!(requires_strict_lower_bound(&strict_interval));      // true: x > 0 required
    /// assert!(!requires_strict_lower_bound(&inclusive_interval));  // false: x ≥ 0 allowed
    /// ```
    ///
    /// ## Performance
    ///
    /// This operation is O(1) and typically compiles to a simple constant or type-based
    /// determination. Since it's implemented as the logical complement of
    /// [`is_lower_bound_closed()`](GetLowerBoundValue::is_lower_bound_closed), it has identical performance characteristics.
    #[inline(always)]
    fn is_lower_bound_open(&self) -> bool {
        !self.is_lower_bound_closed()
    }
}

/// Common interface for intervals that have a finite upper bound.
///
/// The [`GetUpperBoundValue`] trait provides unified access to the upper bound of intervals
/// that have a finite upper boundary. This enables generic programming over intervals
/// with upper bounds while maintaining type safety and performance.
///
/// ## Implementing Types
///
/// All interval types with finite upper bounds implement this trait:
///
/// ### Bounded Intervals
/// - [`IntervalClosed`](crate::intervals::IntervalClosed): `[a, b]`, [`IntervalOpen`](crate::intervals::IntervalOpen): `(a, b)`
/// - [`IntervalLowerOpenUpperClosed`](crate::intervals::IntervalLowerOpenUpperClosed): `(a, b]`, [`IntervalLowerClosedUpperOpen`](crate::intervals::IntervalLowerClosedUpperOpen): `[a, b)`
///
/// ### Upper-Bounded, Lower-Unbounded Intervals
/// - [`IntervalLowerUnboundedUpperClosed`](crate::intervals::IntervalLowerUnboundedUpperClosed): `(-∞, b]`
/// - [`IntervalLowerUnboundedUpperOpen`](crate::intervals::IntervalLowerUnboundedUpperOpen): `(-∞, b)`
///
/// ## Core Operation
///
/// - [`upper_bound_value`](GetUpperBoundValue::upper_bound_value): Returns a reference to the upper bound value
///
/// This method provides **read-only access** with **zero computational cost**.
///
/// ## Usage Examples
///
/// ### Basic Upper Bound Access
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// type Real = RealNative64StrictFiniteInDebug;
///
/// let closed = IntervalClosed::new(
///     Real::try_new(-2.0).unwrap(),
///     Real::try_new(5.0).unwrap()
/// );
/// let unbounded = IntervalLowerUnboundedUpperClosed::new(
///     Real::try_new(10.0).unwrap()
/// );
///
/// assert_eq!(closed.upper_bound_value(), &5.0);
/// assert_eq!(unbounded.upper_bound_value(), &10.0);
/// ```
///
/// ### Generic Programming Over Upper-Bounded Intervals
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// fn analyze_upper_bound<I, T>(interval: &I) -> String
/// where
///     I: GetUpperBoundValue<UpperBoundValue = T>,
///     T: RealScalar + std::fmt::Display,
/// {
///     format!("Upper bound: {}", interval.upper_bound_value())
/// }
///
/// let closed = IntervalClosed::new(-1.0, 1.0);
/// let unbounded = IntervalLowerUnboundedUpperClosed::new(5.0);
///
/// println!("{}", analyze_upper_bound(&closed));      // "Upper bound: 1"
/// println!("{}", analyze_upper_bound(&unbounded));   // "Upper bound: 5"
/// ```
pub trait GetUpperBoundValue: Debug {
    /// The scalar type used for the upper bound value.
    ///
    /// This type must satisfy the [`RealScalar`] trait, ensuring it represents
    /// a valid real number suitable for interval arithmetic.
    type UpperBoundValue: RealScalar;

    /// Return the upper bound of the interval.
    ///
    /// This method provides read-only access to the interval's upper bound value.
    /// The returned reference is guaranteed to be valid for the lifetime of the interval.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let interval = IntervalClosed::new(1.0, 3.0);
    /// assert_eq!(interval.upper_bound_value(), &3.0);
    ///
    /// let upper_closed_interval = IntervalLowerUnboundedUpperClosed::new(15.0);
    /// let upper_open_interval = IntervalLowerUnboundedUpperOpen::new(20.0);
    /// assert_eq!(upper_closed_interval.upper_bound_value(), &15.0);
    /// assert_eq!(upper_open_interval.upper_bound_value(), &20.0);
    ///
    /// // Both intervals extend infinitely to the left
    /// assert!(upper_closed_interval.contains_point(&-1000.0));
    /// assert!(upper_open_interval.contains_point(&-1000.0));
    ///
    /// // But they differ in their treatment of the upper bound
    /// assert!(upper_closed_interval.contains_point(&15.0));   // (-∞, 15] includes 15
    /// assert!(!upper_open_interval.contains_point(&20.0));    // (-∞, 20) excludes 20
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1) and typically compiles to a simple memory access.
    /// There is no computational overhead regardless of the scalar type used.
    fn upper_bound_value(&self) -> &Self::UpperBoundValue;

    /// Check if the upper bound of the interval is closed (inclusive).
    ///
    /// Returns `true` if the upper boundary point is included in the interval,
    /// `false` if it is excluded. This determines whether the interval uses
    /// a `≤` (closed) or `<` (open) relation at the upper endpoint.
    ///
    /// # Boundary Semantics
    ///
    /// The upper bound closure affects:
    /// - **Point containment**: Whether `upper_bound_value` is in the interval
    /// - **Mathematical notation**: Closed uses `]`, open uses `)`
    /// - **Interval arithmetic**: Affects intersection and union operations
    ///
    /// ## Interval Type Behavior
    ///
    /// | Interval Type                    | Notation    | Returns |
    /// |----------------------------------|-------------|---------|
    /// | `IntervalClosed`                 | `[a, b]`    | `true`  |
    /// | `IntervalOpen`                   | `(a, b)`    | `false` |
    /// | `IntervalLowerClosedUpperOpen`   | `[a, b)`    | `false` |
    /// | `IntervalLowerOpenUpperClosed`   | `(a, b]`    | `true`  |
    /// | `IntervalLowerUnboundedUpperClosed` | `(-∞, b]` | `true`  |
    /// | `IntervalLowerUnboundedUpperOpen`   | `(-∞, b)` | `false` |
    /// | `IntervalSingleton`              | `{a}`       | `true`  |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// // Closed upper bound - includes the endpoint
    /// let closed = IntervalClosed::new(0.0, 10.0);
    /// assert!(closed.is_upper_bound_closed());
    /// assert!(closed.contains_point(&10.0));  // 10 is in [0, 10]
    ///
    /// // Open upper bound - excludes the endpoint
    /// let half_open = IntervalLowerClosedUpperOpen::new(0.0, 10.0);
    /// assert!(!half_open.is_upper_bound_closed());
    /// assert!(!half_open.contains_point(&10.0));  // 10 is not in [0, 10)
    ///
    /// // Unbounded intervals
    /// let upper_closed = IntervalLowerUnboundedUpperClosed::new(5.0);
    /// assert!(upper_closed.is_upper_bound_closed());  // (-∞, 5] includes 5
    /// assert!(upper_closed.contains_point(&5.0));
    ///
    /// let upper_open = IntervalLowerUnboundedUpperOpen::new(5.0);
    /// assert!(!upper_open.is_upper_bound_closed());   // (-∞, 5) excludes 5
    /// assert!(!upper_open.contains_point(&5.0));
    /// ```
    ///
    /// # Generic Programming
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use num_valid::RealScalar;
    ///
    /// fn check_endpoint_inclusion<I>(interval: &I, point: &I::RealType) -> bool
    /// where
    ///     I: GetUpperBoundValue + IntervalTrait,
    ///     I::UpperBoundValue: PartialEq<I::RealType>,
    /// {
    ///     if interval.upper_bound_value() == point {
    ///         interval.is_upper_bound_closed()
    ///     } else {
    ///         interval.contains_point(point)
    ///     }
    /// }
    ///
    /// let closed = IntervalClosed::new(0.0, 10.0);
    /// let open = IntervalOpen::new(0.0, 10.0);
    ///
    /// assert!(check_endpoint_inclusion(&closed, &10.0));   // Closed includes endpoint
    /// assert!(!check_endpoint_inclusion(&open, &10.0));    // Open excludes endpoint
    /// ```
    ///
    /// # See Also
    ///
    /// - [`is_upper_bound_open`](GetUpperBoundValue::is_upper_bound_open) - Logical complement
    /// - [`is_lower_bound_closed`](GetLowerBoundValue::is_lower_bound_closed) - Lower bound closure
    /// - [`upper_bound_value`](GetUpperBoundValue::upper_bound_value) - Get the upper bound value
    fn is_upper_bound_closed(&self) -> bool;

    /// Check if the upper bound of the interval is open (exclusive).
    ///
    /// Returns `true` if the upper boundary point is excluded from the interval,
    /// `false` if it is included. This is the logical complement of
    /// [`is_upper_bound_closed`](GetUpperBoundValue::is_upper_bound_closed).
    ///
    /// # Boundary Semantics
    ///
    /// An open upper bound means:
    /// - The interval uses a strict `<` inequality at the upper endpoint
    /// - The upper bound value itself is **not** contained in the interval
    /// - Mathematical notation uses `)` instead of `]`
    /// - The interval extends arbitrarily close to, but never reaches, the upper bound
    ///
    /// ## Interval Type Behavior
    ///
    /// | Interval Type                    | Notation    | Returns |
    /// |----------------------------------|-------------|---------|
    /// | `IntervalClosed`                 | `[a, b]`    | `false` |
    /// | `IntervalOpen`                   | `(a, b)`    | `true`  |
    /// | `IntervalLowerClosedUpperOpen`   | `[a, b)`    | `true`  |
    /// | `IntervalLowerOpenUpperClosed`   | `(a, b]`    | `false` |
    /// | `IntervalLowerUnboundedUpperClosed` | `(-∞, b]` | `false` |
    /// | `IntervalLowerUnboundedUpperOpen`   | `(-∞, b)` | `true`  |
    /// | `IntervalSingleton`              | `{a}`       | `false` |
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// // Half-open interval [0, 10) - open upper bound
    /// let half_open = IntervalLowerClosedUpperOpen::new(0.0, 10.0);
    /// assert!(half_open.is_upper_bound_open());
    /// assert!(!half_open.contains_point(&10.0));  // 10 excluded
    /// assert!(half_open.contains_point(&9.999));  // Points arbitrarily close included
    ///
    /// // Fully open interval (0, 10) - open upper bound
    /// let open = IntervalOpen::new(0.0, 10.0);
    /// assert!(open.is_upper_bound_open());
    /// assert!(!open.contains_point(&10.0));
    ///
    /// // Closed interval [0, 10] - NOT open upper bound
    /// let closed = IntervalClosed::new(0.0, 10.0);
    /// assert!(!closed.is_upper_bound_open());
    /// assert!(closed.contains_point(&10.0));  // 10 included
    ///
    /// // Unbounded open interval (-∞, 5)
    /// let unbounded = IntervalLowerUnboundedUpperOpen::new(5.0);
    /// assert!(unbounded.is_upper_bound_open());
    /// assert!(!unbounded.contains_point(&5.0));
    /// ```
    ///
    /// # Complement Relationship
    ///
    /// This method is the logical complement of `is_upper_bound_closed()`:
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// // Test complement relationship for each interval type
    /// let closed = IntervalClosed::new(0.0, 1.0);
    /// assert_eq!(closed.is_upper_bound_open(), !closed.is_upper_bound_closed());
    ///
    /// let open = IntervalOpen::new(0.0, 1.0);
    /// assert_eq!(open.is_upper_bound_open(), !open.is_upper_bound_closed());
    ///
    /// let half_open1 = IntervalLowerClosedUpperOpen::new(0.0, 1.0);
    /// assert_eq!(half_open1.is_upper_bound_open(), !half_open1.is_upper_bound_closed());
    ///
    /// let half_open2 = IntervalLowerOpenUpperClosed::new(0.0, 1.0);
    /// assert_eq!(half_open2.is_upper_bound_open(), !half_open2.is_upper_bound_closed());
    /// ```
    ///
    /// # Implementation Note
    ///
    /// This method has a default implementation as `!self.is_upper_bound_closed()`.
    /// Types implementing [`GetUpperBoundValue`] only need to implement
    /// `is_upper_bound_closed()`, and this method is automatically derived.
    ///
    /// # See Also
    ///
    /// - [`is_upper_bound_closed`](GetUpperBoundValue::is_upper_bound_closed) - Logical complement
    /// - [`is_lower_bound_open`](GetLowerBoundValue::is_lower_bound_open) - Lower bound openness
    /// - [`upper_bound_value`](GetUpperBoundValue::upper_bound_value) - Get the upper bound value
    #[inline(always)]
    fn is_upper_bound_open(&self) -> bool {
        !self.is_upper_bound_closed()
    }
}
//------------------------------------------------------------------------------------------------