grid1d 0.5.3

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
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
#![deny(rustdoc::broken_intra_doc_links)]

//! Bounded interval types with finite, positive-length domains.
//!
//! This module provides all interval types where both bounds are finite. Every type
//! has a well-defined, non-zero length. All items are re-exported at
//! [`crate::intervals`], so `use grid1d::intervals::*` is sufficient.
//!
//! ## Types
//!
//! ### Generic Base Type
//!
//! | Type | Description |
//! |------|------------|
//! | [`IntervalBounded`] | Generic bounded interval parameterised over lower/upper [`crate::bounds::BoundType`] |
//!
//! ### Concrete Type Aliases
//!
//! | Type | Notation | Description |
//! |------|----------|------------|
//! | [`IntervalClosed`] | `[a, b]` | Both bounds included |
//! | [`IntervalOpen`] | `(a, b)` | Both bounds excluded |
//! | [`IntervalLowerClosedUpperOpen`] | `[a, b)` | Lower included, upper excluded |
//! | [`IntervalLowerOpenUpperClosed`] | `(a, b]` | Lower excluded, upper included |
//! | [`IntervalSingleton`] | `{a}` | Single point (zero length) |
//!
//! ### Enum Wrappers
//!
//! | Type | Description |
//! |------|------------|
//! | [`IntervalFinitePositiveLength`] | Enum over the four bounded non-singleton variants |
//! | [`IntervalFiniteLength`] | Extends `IntervalFinitePositiveLength` with [`IntervalSingleton`] |
//! | [`SubIntervalInPartition`] | Enum for grid partition sub-intervals (single/first/middle/last) |
//!
//! ### Traits
//!
//! | Trait | Purpose |
//! |-------|---------|
//! | [`IntervalFinitePositiveLengthTrait`] | Supertrait for all positive-length bounded intervals |
//! | [`IntervalFromBounds`] | Construction from raw bound values: `new()`, `try_new()`, `new_unit_interval()`, `new_symmetric_interval()` |
//!
//! ## Example
//!
//! ```rust
//! use grid1d::intervals::*;
//!
//! let closed = IntervalClosed::new(0.0_f64, 1.0);              // [0, 1]
//! let half_open = IntervalLowerClosedUpperOpen::new(0.0_f64, 1.0); // [0, 1)
//!
//! assert!(closed.contains_point(&1.0));
//! assert!(!half_open.contains_point(&1.0)); // upper bound excluded
//! ```

use crate::{
    GetLowerBoundValue, GetUpperBoundValue,
    bounds::{LowerBoundClosed, UpperBoundClosed},
    grids::traits::Grid1DIntervalBuilder,
    intervals::{
        BoundType, Closed, Contains, ErrorsIntervalConstruction, IntervalBoundRuntime,
        IntervalBoundsRuntime, IntervalHull, IntervalTrait, LowerBound, LowerBoundRuntime, Open,
        UpperBound, UpperBoundRuntime, ValueWithinBound, compute_hull_bounded_intervals,
        operations::IntervalOperations,
    },
};
use duplicate::duplicate_item;
use getset::Getters;
use into_inner::IntoInner;
use num::{One, Zero};
use num_valid::{
    Constants, RealScalar, core::errors::capture_backtrace, scalars::PositiveRealScalar,
};
use serde::{Deserialize, Serialize};
use std::ops::Neg;
use try_create::{New, TryNew};

/// Common interface for intervals with finite, positive, measurable length.
///
/// The [`IntervalFinitePositiveLengthTrait`] trait provides a unified interface for all interval
/// types that have positive length (non-zero measure), enabling generic programming over
/// bounded intervals while excluding both infinite intervals and singleton points.
///
/// ## Mathematical Foundation
///
/// This trait applies to intervals where the upper bound is strictly greater than the lower bound:
/// - **Positive measure**: `μ(I) = |upper - lower| > 0`
/// - **Uncountable cardinality**: Contains infinitely many points
/// - **Non-trivial geometry**: Has well-defined length, midpoint, and interior
/// - **Integration support**: Can support non-zero integrals
///
/// ## Core Operations
///
/// ### Required Methods
/// - [`lower_bound_value`](GetLowerBoundValue::lower_bound_value): Access the lower bound
/// - [`upper_bound_value`](GetUpperBoundValue::upper_bound_value): Access the upper bound
/// - [`into_bounds_pair`](IntervalFinitePositiveLengthTrait::into_bounds_pair): Consume interval to get `(lower, upper)` pair
///
/// ### Provided Methods
///
/// #### Geometric properties
/// - [`length`](IntervalFinitePositiveLengthTrait::length): Compute interval length `|upper - lower|`
/// - [`midpoint`](IntervalFinitePositiveLengthTrait::midpoint): Compute midpoint `(upper + lower) / 2`
/// - [`is_symmetric`](IntervalFinitePositiveLengthTrait::is_symmetric): Test if symmetric around origin (`lower + upper == 0`)
///
/// #### Affine transformations
/// - [`translate`](IntervalFinitePositiveLengthTrait::translate): Shift both bounds by a scalar offset; preserves length and boundary semantics
/// - [`scale`](IntervalFinitePositiveLengthTrait::scale): Scale the half-length around the midpoint by a strictly positive factor
/// - [`expand`](IntervalFinitePositiveLengthTrait::expand): Expand symmetrically by adding a fixed amount to each side; preserves midpoint
///
/// #### Type conversions
/// - [`interior`](IntervalFinitePositiveLengthTrait::interior): Convert to open interval with same bounds
/// - [`closure`](IntervalFinitePositiveLengthTrait::closure): Convert to closed interval with same bounds
///
/// #### Utilities
/// - [`clamp`](IntervalFinitePositiveLengthTrait::clamp): Clamp a scalar value to the interval's `[lower, upper]` range
///
/// ## Usage Examples
///
/// ### Basic Geometric Operations
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// type Real = RealNative64StrictFiniteInDebug;
///
/// let interval = IntervalClosed::new(
///     Real::try_new(-2.0).unwrap(),
///     Real::try_new(3.0).unwrap()
/// );
///
/// // Geometric properties
/// assert_eq!(interval.length().as_ref(), &5.0);           // |3 - (-2)| = 5
/// assert_eq!(interval.midpoint().as_ref(), &0.5);        // (-2 + 3) / 2 = 0.5
/// assert!(!interval.is_symmetric());                      // -2 + 3 ≠ 0
///
/// // Convert to different boundary types
/// let open_version = interval.clone().interior();  // (-2, 3)
/// let closed_version = interval.clone().closure();  // [-2, 3]
/// ```
///
/// ### Generic Programming with Different Interval Types
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// fn analyze_interval<I, T>(interval: &I) -> String
/// where
///     I: IntervalFinitePositiveLengthTrait<RealType = T>,
///     T: RealScalar + std::fmt::Display,
/// {
///     format!(
///         "Interval [{}, {}]: length = {}, symmetric = {}",
///         interval.lower_bound_value(),
///         interval.upper_bound_value(),
///         interval.length(),
///         interval.is_symmetric()
///     )
/// }
///
/// let closed = IntervalClosed::new(0.0, 1.0);
/// let open = IntervalOpen::new(-1.0, 1.0);
///
/// println!("{}", analyze_interval(&closed));
/// // Output: "Interval [0, 1]: length = 1, symmetric = false"
///
/// println!("{}", analyze_interval(&open));
/// // Output: "Interval [-1, 1]: length = 2, symmetric = true"
/// ```
pub trait IntervalFinitePositiveLengthTrait:
    IntervalTrait
    + GetLowerBoundValue<LowerBoundValue = Self::RealType>
    + GetUpperBoundValue<UpperBoundValue = Self::RealType>
{
    /// Return the length of the interval.
    ///
    /// Computes the Euclidean distance between the upper and lower bounds:
    /// `length = upper_bound - lower_bound`. This represents the measure
    /// (Lebesgue measure) of the interval.
    ///
    /// # Mathematical Properties
    ///
    /// - Always positive: `length() > 0` for all intervals implementing this trait
    /// - Scale invariant under positive scaling
    /// - Translation invariant
    /// - Additive for adjacent intervals
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let interval = IntervalClosed::new(-2.0, 3.0);
    /// assert_eq!(interval.length().into_inner(), 5.0);  // |3 - (-2)| = 5
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1), requiring only a single subtraction.
    #[inline(always)]
    fn length(&self) -> PositiveRealScalar<Self::RealType> {
        PositiveRealScalar::try_new(self.upper_bound_value().clone() - self.lower_bound_value())
            .unwrap()
    }

    /// Return the midpoint of the interval.
    ///
    /// Computes the center point of the interval using the numerically stable formula
    /// `midpoint = lower_bound + (upper_bound - lower_bound) / 2`. This avoids potential
    /// overflow that would occur with the naive formula `(lower_bound + upper_bound) / 2`
    /// when both bounds are large in magnitude.
    ///
    /// # Mathematical Properties
    ///
    /// - Containment depends on boundary type: closed intervals contain their midpoint,
    ///   while open intervals may or may not (depends on whether midpoint touches boundaries)
    /// - Unique center point: only one point equidistant from both bounds
    /// - Translation equivariant: `translate(interval, c).midpoint() = interval.midpoint() + c`
    /// - Scale equivariant: `scale(interval, k).midpoint() = k * interval.midpoint()`
    ///
    /// # Numerical Stability
    ///
    /// The formula `lower + (upper - lower) / 2` is preferred over `(lower + upper) / 2`
    /// because:
    /// - `upper - lower` is always positive and bounded by the interval length, avoiding
    ///   overflow even when both bounds are large in magnitude (e.g. near `±f64::MAX`)
    /// - The only remaining edge case is an interval of length close to `2 · f64::MAX`,
    ///   which cannot arise when the `RealScalar` type enforces finite bounds
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let closed = IntervalClosed::new(-2.0, 3.0);
    /// assert_eq!(closed.midpoint(), 0.5);  // -2 + (3 - (-2)) / 2 = 0.5
    ///
    /// // Midpoint containment depends on boundary type
    /// assert!(closed.contains_point(&closed.midpoint()));  // Closed contains midpoint
    ///
    /// let open = IntervalOpen::new(-2.0, 3.0);
    /// assert_eq!(open.midpoint(), 0.5);   // Same midpoint value
    /// assert!(open.contains_point(&open.midpoint()));      // Open also contains interior midpoint
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1), requiring one subtraction, one multiplication, and one addition.
    #[inline(always)]
    fn midpoint(&self) -> Self::RealType {
        let l = self.lower_bound_value();
        let u = self.upper_bound_value();
        let delta = u.clone() - l;
        delta * Self::RealType::one_div_2() + l
    }

    /// Return `true` if the interval is symmetric about the origin.
    ///
    /// An interval is symmetric if its lower and upper bounds are negatives of each other,
    /// meaning `lower_bound + upper_bound = 0`. This is equivalent to the midpoint being
    /// at the origin.
    ///
    /// # Mathematical Properties
    ///
    /// - Equivalent condition: `midpoint() == 0`
    /// - Preserved under uniform scaling: `scale(symmetric_interval, k)` is symmetric
    /// - Lost under translation: `translate(symmetric_interval, c)` is not symmetric (unless `c = 0`)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let symmetric = IntervalClosed::new(-2.0, 2.0);
    /// assert!(symmetric.is_symmetric());      // -2 + 2 = 0
    ///
    /// let asymmetric = IntervalClosed::new(1.0, 3.0);
    /// assert!(!asymmetric.is_symmetric());    // 1 + 3 ≠ 0
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1), requiring one clone, one sign change and one comparison.
    #[inline]
    fn is_symmetric(&self) -> bool {
        &self.lower_bound_value().clone().neg() == self.upper_bound_value()
    }

    /// Consumes the interval and returns its lower and upper bounds as a pair.
    ///
    /// This is an efficient way to extract both bound values when the interval
    /// object itself is no longer needed, avoiding clones.
    ///
    /// # Returns
    ///
    /// A tuple `(lower_bound, upper_bound)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let interval = IntervalClosed::new(1.5, 2.5);
    /// let (lower, upper) = interval.into_bounds_pair();
    /// assert_eq!(lower, 1.5);
    /// assert_eq!(upper, 2.5);
    /// // interval is no longer accessible here
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1) and typically compiles to efficient move operations.
    fn into_bounds_pair(self) -> (Self::RealType, Self::RealType);

    /// Convert this interval to an open interval with the same bounds.
    ///
    /// Creates a new [`IntervalOpen`] with the same lower and upper bound values,
    /// but with both boundaries excluded. This represents the interior of the interval.
    ///
    /// # Mathematical Properties
    ///
    /// - **Bounds preservation**: The numeric values of the bounds remain unchanged
    /// - **Containment**: `interval.interior() ⊆ interval` for all interval types
    /// - **Idempotence**: `interval.interior().interior() = interval.interior()`
    /// - **Interior property**: For any interval I, `interior(I)` is the largest open set contained in I
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let closed = IntervalClosed::new(0.0, 1.0); // [0, 1]
    /// let interior = closed.clone().interior();   // (0, 1)
    ///
    /// // Same bounds, different boundary inclusion
    /// assert_eq!(interior.lower_bound_value(), &0.0);
    /// assert_eq!(interior.upper_bound_value(), &1.0);
    ///
    /// // Different containment behavior
    /// assert!(closed.contains_point(&0.0));       // [0,1] contains 0
    /// assert!(!interior.contains_point(&0.0));    // (0,1) excludes 0
    /// assert!(interior.contains_point(&0.5));     // Both contain interior points
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1), involving only a move of the bound values and construction
    /// of a new interval type.
    #[inline(always)]
    fn interior(self) -> IntervalOpen<Self::RealType> {
        let (lower_bound, upper_bound) = self.into_bounds_pair();
        IntervalOpen::new(lower_bound, upper_bound)
    }

    /// Convert this interval to a closed interval with the same bounds.
    ///
    /// Creates a new [`IntervalClosed`] with the same lower and upper bound values,
    /// but with both boundaries included. This represents the closure of the interval.
    ///
    /// # Mathematical Properties
    ///
    /// - **Bounds preservation**: The numeric values of the bounds remain unchanged
    /// - **Containment**: `interval ⊆ interval.closure()` for all interval types
    /// - **Idempotence**: `interval.closure().closure() = interval.closure()`
    /// - **Closure property**: For any interval I, `closure(I)` is the smallest closed set containing I
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// let open = IntervalOpen::new(0.0, 1.0);    // (0, 1)
    /// let closure = open.clone().closure();      // [0, 1]
    ///
    /// // Same bounds, different boundary inclusion
    /// assert_eq!(closure.lower_bound_value(), &0.0);
    /// assert_eq!(closure.upper_bound_value(), &1.0);
    ///
    /// // Different containment behavior
    /// assert!(!open.contains_point(&0.0));       // (0,1) excludes 0
    /// assert!(closure.contains_point(&0.0));     // [0,1] contains 0
    /// assert!(closure.contains_point(&0.5));     // Both contain interior points
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1), involving only a move of the bound values and construction
    /// of a new interval type.
    #[inline(always)]
    fn closure(self) -> IntervalClosed<Self::RealType> {
        let (lower_bound, upper_bound) = self.into_bounds_pair();
        IntervalClosed::new(lower_bound, upper_bound)
    }

    /// Clamp the value `x` by the lower bound and the upper bound of the current interval.
    ///
    /// If the input value `x` is less than `self.lower_bound()` then this returns `self.lower_bound().
    /// If the input value `x` is greater than `self.upper_bound()` then this returns `self.upper_bound().
    /// Otherwise this returns the value `x`.
    #[inline(always)]
    fn clamp(&self, x: Self::RealType) -> Self::RealType {
        let lower_bound = self.lower_bound_value();
        if &x < lower_bound {
            return lower_bound.clone();
        }
        let upper_bound = self.upper_bound_value();
        if &x > upper_bound {
            return upper_bound.clone();
        }
        x
    }

    /// Translate the interval by the given `amount`.
    ///
    /// Returns a new interval of the same type whose lower and upper bounds are each shifted
    /// by `amount`:
    ///
    /// ```text
    /// translate([a, b], c) = [a + c, b + c]
    /// translate((a, b), c) = (a + c, b + c)
    /// translate([a, b), c) = [a + c, b + c)
    /// translate((a, b], c) = (a + c, b + c]
    /// ```
    ///
    /// # Mathematical Properties
    ///
    /// - **Length preservation**: `translate(I, c).length() == I.length()` for all `c`
    /// - **Midpoint shift**: `translate(I, c).midpoint() == I.midpoint() + c`
    /// - **Boundary semantics preserved**: the open/closed nature of each bound is unchanged
    /// - **Invertibility**: `translate(translate(I, c), -c) == I`
    /// - **Additivity**: `translate(translate(I, a), b) == translate(I, a + b)`
    ///
    /// # Arguments
    ///
    /// - `amount`: The scalar value by which both bounds are shifted.
    ///   Positive values shift right; negative values shift left.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    ///
    /// // Translate a closed interval to the right
    /// let interval = IntervalClosed::new(1.0_f64, 3.0_f64);
    /// let shifted = interval.translate(2.0);
    /// assert_eq!(shifted.lower_bound_value(), &3.0);
    /// assert_eq!(shifted.upper_bound_value(), &5.0);
    /// assert_eq!(shifted.length().into_inner(), interval.length().into_inner()); // length preserved
    ///
    /// // Translate to the left (negative amount)
    /// let left = interval.translate(-1.5);
    /// assert_eq!(left.lower_bound_value(), &-0.5);
    /// assert_eq!(left.upper_bound_value(), &1.5);
    ///
    /// // Boundary semantics are preserved
    /// let half_open = IntervalLowerClosedUpperOpen::new(0.0_f64, 4.0_f64);
    /// let shifted_half = half_open.translate(1.0);
    /// assert_eq!(shifted_half.lower_bound_value(), &1.0);
    /// assert_eq!(shifted_half.upper_bound_value(), &5.0);
    /// assert!(shifted_half.is_lower_bound_closed());
    /// assert!(!shifted_half.is_upper_bound_closed());
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1), requiring two additions and one interval construction.
    fn translate(&self, amount: Self::RealType) -> Self;

    /// Scale the interval about its midpoint by a strictly positive `factor`.
    ///
    /// Returns a new interval of the same type whose midpoint is unchanged, but whose
    /// half-length is multiplied by `factor`:
    ///
    /// ```text
    /// let center = midpoint(I)
    /// let new_half_len = (length(I) / 2) * factor
    ///
    /// scale(I, k) = [center - new_half_len,  center + new_half_len]
    /// ```
    ///
    /// The factor must be strictly positive (encoded by [`PositiveRealScalar`]):
    /// - `factor > 1` expands the interval
    /// - `0 < factor < 1` contracts the interval
    /// - `factor = 1` is the identity
    ///
    /// # Mathematical Properties
    ///
    /// - **Midpoint invariance**: `scale(I, k).midpoint() == I.midpoint()` for all `k > 0`
    /// - **Length scaling**: `scale(I, k).length() == I.length() * k`
    /// - **Boundary semantics preserved**: the open/closed nature of each bound is unchanged
    /// - **Identity**: `scale(I, 1)` returns an interval equal to `I`
    /// - **Invertibility**: `scale(scale(I, k), 1/k) == I`
    /// - **Multiplicativity**: `scale(scale(I, a), b) == scale(I, a * b)`
    /// - **Symmetry preservation**: if `I` is symmetric (midpoint = 0), so is `scale(I, k)`
    ///
    /// # Arguments
    ///
    /// - `factor`: A strictly positive scalar by which the half-length is multiplied.
    ///   Construct with [`PositiveRealScalar::try_new`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use num_valid::scalars::PositiveRealScalar;
    /// use try_create::TryNew;
    ///
    /// // Expand a closed interval by factor 2 around its midpoint
    /// let interval = IntervalClosed::new(0.0_f64, 4.0_f64); // midpoint = 2, length = 4
    /// let factor = PositiveRealScalar::try_new(2.0_f64).unwrap();
    /// let expanded = interval.scale(&factor);
    /// assert_eq!(expanded.lower_bound_value(), &-2.0); // midpoint - 2*half_len = 2 - 4 = -2
    /// assert_eq!(expanded.upper_bound_value(), &6.0);  // midpoint + 2*half_len = 2 + 4 = 6
    /// assert_eq!(expanded.length().into_inner(), 8.0); // 4 * 2 = 8
    ///
    /// // Contract by factor 0.5
    /// let factor_half = PositiveRealScalar::try_new(0.5_f64).unwrap();
    /// let contracted = interval.scale(&factor_half);
    /// assert_eq!(contracted.lower_bound_value(), &1.0); // 2 - 1 = 1
    /// assert_eq!(contracted.upper_bound_value(), &3.0); // 2 + 1 = 3
    /// assert_eq!(contracted.length().into_inner(), 2.0); // 4 * 0.5 = 2
    ///
    /// // Boundary semantics are preserved
    /// let half_open = IntervalLowerClosedUpperOpen::new(0.0_f64, 4.0_f64);
    /// let scaled = half_open.scale(&factor);
    /// assert!(scaled.is_lower_bound_closed());
    /// assert!(!scaled.is_upper_bound_closed());
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1), requiring one midpoint computation, two multiplications,
    /// two additions, and one interval construction.
    fn scale(&self, factor: &PositiveRealScalar<Self::RealType>) -> Self;

    /// Expand the interval symmetrically by a strictly positive `amount` on each side.
    ///
    /// Returns a new interval of the same type whose lower bound is shifted down by `amount`
    /// and whose upper bound is shifted up by `amount`:
    ///
    /// ```text
    /// expand([a, b], ε) = [a - ε,  b + ε]
    /// expand((a, b), ε) = (a - ε,  b + ε)
    /// expand([a, b), ε) = [a - ε,  b + ε)
    /// expand((a, b], ε) = (a - ε,  b + ε]
    /// ```
    ///
    /// Unlike [`scale`](IntervalFinitePositiveLengthTrait::scale), which multiplies the half-length,
    /// `expand` adds a fixed absolute amount to each side.
    ///
    /// # Mathematical Properties
    ///
    /// - **Midpoint invariance**: `expand(I, ε).midpoint() == I.midpoint()` for all `ε > 0`
    /// - **Length increase**: `expand(I, ε).length() == I.length() + 2 * ε`
    /// - **Strict containment**: `I ⊂ expand(I, ε)` (every point of `I` is in the expansion)
    /// - **Boundary semantics preserved**: the open/closed nature of each bound is unchanged
    /// - **Additivity**: `expand(expand(I, a), b) == expand(I, a + b)`
    ///
    /// # Arguments
    ///
    /// - `amount`: A strictly positive scalar added to the upper bound and subtracted from
    ///   the lower bound. Construct with [`PositiveRealScalar::try_new`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use num_valid::scalars::PositiveRealScalar;
    /// use try_create::TryNew;
    ///
    /// // Expand a closed interval by 1.0 on each side
    /// let interval = IntervalClosed::new(1.0_f64, 5.0_f64); // midpoint=3, length=4
    /// let eps = PositiveRealScalar::try_new(1.0_f64).unwrap();
    /// let expanded = interval.expand(&eps);
    /// assert_eq!(expanded.lower_bound_value(), &0.0);  // 1 - 1 = 0
    /// assert_eq!(expanded.upper_bound_value(), &6.0);  // 5 + 1 = 6
    /// assert_eq!(expanded.length().into_inner(), 6.0); // 4 + 2*1 = 6
    ///
    /// // Midpoint is unchanged
    /// assert_eq!(expanded.midpoint(), interval.midpoint());
    ///
    /// // Boundary semantics are preserved
    /// let half_open = IntervalLowerClosedUpperOpen::new(1.0_f64, 5.0_f64);
    /// let expanded_half = half_open.expand(&eps);
    /// assert!(expanded_half.is_lower_bound_closed());
    /// assert!(!expanded_half.is_upper_bound_closed());
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1), requiring two additions and one interval construction.
    fn expand(&self, amount: &PositiveRealScalar<Self::RealType>) -> Self;
}
//--------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------------
/// Trait for constructing a concrete interval type from raw lower and upper bound values.
///
/// Implemented by all bounded finite-positive-length interval types
/// ([`IntervalClosed`], [`IntervalOpen`], [`IntervalLowerClosedUpperOpen`],
/// [`IntervalLowerOpenUpperClosed`]).
/// Use this as an additional bound when generic code needs to *materialise* an interval
/// from raw scalar bounds, rather than only inspect an existing one.
///
/// # Methods
///
/// | Method | Description |
/// |--------|-------------|
/// | [`try_new`](IntervalFromBounds::try_new) | Fallible construction from raw bounds; returns `Err` if `lower >= upper` |
/// | [`new`](IntervalFromBounds::new) | Infallible construction (panics in debug mode on invalid bounds) |
/// | [`new_unit_interval`](IntervalFromBounds::new_unit_interval) | Convenience constructor for `[0, 1]` (or open/half-open equivalent) |
/// | [`new_symmetric_interval`](IntervalFromBounds::new_symmetric_interval) | Convenience constructor for `[-extent, +extent]` centred at zero |
pub trait IntervalFromBounds: IntervalFinitePositiveLengthTrait {
    /// Build and return a new instance of the interval from its lower and upped bound.
    ///
    /// # Arguments
    ///
    /// - `lower_bound`: The lower bound of the interval.
    /// - `upper_bound`: The upper bound of the interval.
    ///
    /// # Errors
    ///
    /// If the lower bound is greater than or equal to the upper bound, this function returns an error
    /// (wrapped by the [`Err`] type).
    /// An error is also returned if any of the bounds is not a finite floating-point number.
    fn try_new(
        lower_bound: Self::RealType,
        upper_bound: Self::RealType,
    ) -> Result<Self, ErrorsIntervalConstruction<Self::RealType>>;

    /// Build and return a new instance of the interval from its lower and upped bound.
    ///
    /// # Arguments
    ///
    /// - `lower_bound`: The lower bound of the interval.
    /// - `upper_bound`: The upper bound of the interval.
    ///
    /// # Panics
    ///
    /// In debug mode this function internally calls the [`Self::try_new`] method and will panic if
    /// this method returns an error. In release mode the interval is build without any check on the input bounds.
    fn new(lower_bound: Self::RealType, upper_bound: Self::RealType) -> Self;

    /// Build and return the unit interval `[0, 1]` with the boundary semantics of the concrete
    /// implementing type.
    ///
    /// This is a convenience constructor equivalent to `Self::new(T::zero(), T::one())`, where
    /// `T` is `Self::RealType`. It can never fail, since `0 < 1` holds for all supported scalar
    /// types.
    ///
    /// The boundary type (open, closed, half-open) is determined by the concrete implementing type:
    ///
    /// | Type | Result |
    /// |------|--------|
    /// | [`IntervalClosed`] | `[0, 1]` |
    /// | [`IntervalOpen`] | `(0, 1)` |
    /// | [`IntervalLowerClosedUpperOpen`] | `[0, 1)` |
    /// | [`IntervalLowerOpenUpperClosed`] | `(0, 1]` |
    ///
    /// # Examples
    ///
    /// ```
    /// use grid1d::intervals::*;
    ///
    /// // Standard mathematical unit interval [0, 1]
    /// let unit: IntervalClosed<f64> = IntervalClosed::new_unit_interval();
    /// assert_eq!(unit.lower_bound_value(), &0.0);
    /// assert_eq!(unit.upper_bound_value(), &1.0);
    /// assert_eq!(unit.length().into_inner(), 1.0);
    /// assert_eq!(unit.midpoint(), 0.5);
    ///
    /// // Half-open variant: lower included, upper excluded
    /// let half_open: IntervalLowerClosedUpperOpen<f64> =
    ///     IntervalLowerClosedUpperOpen::new_unit_interval();
    /// assert!(half_open.contains_point(&0.0));
    /// assert!(!half_open.contains_point(&1.0));
    /// ```
    fn new_unit_interval() -> Self {
        Self::new(Self::RealType::zero(), Self::RealType::one())
    }

    /// Build and return a symmetric interval `[−extent, +extent]` centred at zero, with the
    /// boundary semantics of the concrete implementing type.
    ///
    /// # Arguments
    ///
    /// - `extent`: the half-length of the interval. Must be strictly positive (enforced by the
    ///   [`PositiveRealScalar`] wrapper).
    ///
    /// This is a convenience constructor equivalent to `Self::new(-extent, extent)`. It can never
    /// fail because `extent > 0` guarantees `-extent < extent`.
    ///
    /// ## Mathematical Properties
    ///
    /// | Property | Value |
    /// |----------|-------|
    /// | Lower bound | `−extent` |
    /// | Upper bound | `+extent` |
    /// | Midpoint | `0` |
    /// | Length | `2 · extent` |
    /// | [`is_symmetric`](IntervalFinitePositiveLengthTrait::is_symmetric) | `true` |
    ///
    /// The boundary type (open, closed, half-open) is determined by the concrete implementing type:
    ///
    /// | Type | Result |
    /// |------|--------|
    /// | [`IntervalClosed`] | `[−extent, extent]` |
    /// | [`IntervalOpen`] | `(−extent, extent)` |
    /// | [`IntervalLowerClosedUpperOpen`] | `[−extent, extent)` |
    /// | [`IntervalLowerOpenUpperClosed`] | `(−extent, extent]` |
    ///
    /// # Examples
    ///
    /// ```
    /// use grid1d::intervals::*;
    /// use num_valid::scalars::PositiveRealScalar;
    /// use try_create::TryNew;
    ///
    /// let extent = PositiveRealScalar::try_new(3.0_f64).unwrap();
    ///
    /// let sym: IntervalClosed<f64> = IntervalClosed::new_symmetric_interval(&extent);
    /// assert_eq!(sym.lower_bound_value(), &-3.0);
    /// assert_eq!(sym.upper_bound_value(), &3.0);
    /// assert_eq!(sym.midpoint(), 0.0);
    /// assert_eq!(sym.length().into_inner(), 6.0);
    /// assert!(sym.is_symmetric());
    /// ```
    fn new_symmetric_interval(extent: &PositiveRealScalar<Self::RealType>) -> Self {
        let extent = extent.as_ref();
        Self::new(extent.clone().neg(), extent.clone())
    }
}

impl<RealType: RealScalar, LowerBoundType: BoundType, UpperBoundType: BoundType> IntervalFromBounds
    for IntervalBounded<RealType, LowerBoundType, UpperBoundType>
where
    Self: IntervalBoundsRuntime<RealType = RealType>,
    LowerBound<RealType, LowerBoundType>: ValueWithinBound<RealType = RealType>,
    UpperBound<RealType, UpperBoundType>: ValueWithinBound<RealType = RealType>,
{
    /// Build and return a new instance of the interval from its lower and upped bound.
    ///
    /// # Arguments
    ///
    /// - `lower_bound`: The lower bound of the interval.
    /// - `upper_bound`: The upper bound of the interval.
    ///
    /// # Errors
    ///
    /// If the lower bound is greater than or equal to the upper bound, this function returns an error
    /// (wrapped by the [`Err`] type).
    /// An error is also returned if any of the bounds is not a finite floating-point number.
    fn try_new(
        lower_bound: RealType,
        upper_bound: RealType,
    ) -> Result<Self, ErrorsIntervalConstruction<RealType>> {
        if lower_bound < upper_bound {
            let lower_bound = LowerBound::<RealType, LowerBoundType>::new(lower_bound);
            let upper_bound = UpperBound::<RealType, UpperBoundType>::new(upper_bound);

            Ok(Self {
                lower_bound,
                upper_bound,
            })
        } else {
            Err(
                ErrorsIntervalConstruction::LowerBoundGreaterOrEqualThanUpperBound {
                    lower_bound,
                    upper_bound,
                    backtrace: capture_backtrace(),
                },
            )
        }
    }
    fn new(lower_bound: Self::RealType, upper_bound: Self::RealType) -> Self {
        #[cfg(debug_assertions)]
        {
            Self::try_new(lower_bound, upper_bound)
                .expect("Invalid interval bounds for the closed interval!")
        }
        #[cfg(not(debug_assertions))]
        {
            Self {
                lower_bound: LowerBound::<Self::RealType, LowerBoundType>::new(lower_bound),
                upper_bound: UpperBound::<Self::RealType, UpperBoundType>::new(upper_bound),
            }
        }
    }
}
//--------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------------
///  Container for all intervals with finite, measurable length.
///
/// The [`IntervalFiniteLength`] enum represents the fundamental mathematical distinction
/// between intervals that have positive length (contain infinitely many points) and
/// those with zero length (contain exactly one point). This categorization is essential
/// for mathematical analysis, numerical integration, and measure theory applications.
///
/// ## Mathematical Foundation
///
/// In mathematical analysis, finite intervals fall into two distinct categories:
/// - **Positive measure**: Intervals like `[a,b]`, `(a,b)`, `[a,b)`, `(a,b]` where `a < b`
/// - **Zero measure**: Singleton sets `{a}` or `[a]` containing exactly one point
///
/// This distinction is crucial because:
/// - Positive-length intervals have **non-zero measure** in Lebesgue measure theory
/// - Zero-length intervals (singletons) have **zero measure** but are still measurable sets
/// - Integration over zero-length intervals always yields zero
/// - Positive-length intervals can support non-trivial probability distributions
///
/// ## Generic Over Any [`num_valid::RealScalar`] Type
///
/// **The [`IntervalFiniteLength`] enum works seamlessly with any scalar type implementing [`num_valid::RealScalar`]:**
///
/// | Scalar Type | Performance | Validation | Best For |
/// |-------------|-------------|------------|----------|
/// | [`f64`] | ⚡⚡⚡ Maximum | ❌ None | Trusted input, maximum speed |
/// | [`RealNative64StrictFiniteInDebug`](num_valid::RealNative64StrictFiniteInDebug) | ⚡⚡⚡ **Same as f64** | ✅ **Debug only** | **Recommended for most uses** |
/// | [`RealNative64StrictFinite`](num_valid::RealNative64StrictFinite) | ⚡⚡ Small overhead | ✅ Always | Safety-critical applications |
/// | `RealRugStrictFinite` | ⚡ Precision-dependent | ✅ Always | Arbitrary precision needs (available from the [num-valid](https://crates.io/crates/num-valid) crate when compiled with `--features=rug`)|
///
/// ## Enum Variants
///
/// ### [`IntervalFiniteLength::PositiveLength`]
/// Contains intervals where the upper bound is strictly greater than the lower bound:
/// - **Closed**: `[a, b]` where `a < b` - includes both endpoints
/// - **Open**: `(a, b)` where `a < b` - excludes both endpoints  
/// - **Half-open**: `[a, b)` or `(a, b]` where `a < b` - includes one endpoint
/// - **Measure**: Always `> 0` (specifically `|b - a|`)
/// - **Cardinality**: Uncountably infinite points
///
/// ### [`IntervalFiniteLength::ZeroLength`]
/// Contains singleton intervals with exactly one point:
/// - **Notation**: `[a]` or `{a}` - a single point
/// - **Measure**: Always `0`
/// - **Cardinality**: Exactly one point
/// - **Use cases**: Point masses, discrete events, boundary conditions
///
/// ## Construction Patterns
///
/// ### From Concrete Interval Types (Recommended)
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::{New, TryNew};
///
/// // Use the recommended performance-optimal type
/// type Real = RealNative64StrictFiniteInDebug;
///
/// // Create positive-length intervals
/// let closed = IntervalClosed::new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// let finite_positive: IntervalFiniteLength<Real> = closed.into();
///
/// // Create zero-length intervals  
/// let singleton = IntervalSingleton::new(Real::try_new(0.5).unwrap());
/// let finite_zero: IntervalFiniteLength<Real> = singleton.into();
/// ```
///
/// ### Direct Construction
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// // Build positive-length interval directly
/// let positive = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(
///         IntervalClosed::try_new(0.0, 1.0).unwrap()
///     )
/// );
///
/// // Build zero-length interval directly
/// let zero = IntervalFiniteLength::ZeroLength(
///     IntervalSingleton::new(42.0)
/// );
/// ```
///
/// ## Core Operations
///
/// All [`IntervalFiniteLength`] instances support the complete [`IntervalTrait`] interface:
///
/// ### Point Containment Testing
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let positive = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(
///         IntervalClosed::try_new(0.0, 1.0).unwrap())
/// );
/// let zero = IntervalFiniteLength::ZeroLength(IntervalSingleton::new(0.5));
///
/// // Positive-length interval contains many points
/// assert!(positive.contains_point(&0.0));    // Lower bound
/// assert!(positive.contains_point(&0.5));    // Interior point  
/// assert!(positive.contains_point(&1.0));    // Upper bound
/// assert!(!positive.contains_point(&2.0));   // Outside interval
///
/// // Zero-length interval contains only one specific point
/// assert!(zero.contains_point(&0.5));        // Exact match
/// assert!(!zero.contains_point(&0.0));       // Any other point
/// assert!(!zero.contains_point(&1.0));       // Any other point
/// ```
///
/// ### Interval Containment Testing
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let outer = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(
///         IntervalClosed::try_new(0.0, 2.0).unwrap())
/// );
/// let inner = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Open(
///         IntervalOpen::try_new(0.5, 1.5).unwrap())
/// );
/// let singleton = IntervalFiniteLength::ZeroLength(IntervalSingleton::new(1.0));
///
/// assert!(outer.contains_interval(&inner));           // [0,2] contains (0.5,1.5)
/// assert!(outer.contains_interval(&singleton));       // [0,2] contains {1}
/// assert!(inner.contains_interval(&singleton));       // (0.5,1.5) contains {1}
/// assert!(!inner.contains_interval(&outer));          // (0.5,1.5) doesn't contain [0,2]
/// assert!(!singleton.contains_interval(&outer));      // {1} doesn't contain [0,2]
/// ```
///
/// ### Intersection Operations
/// ```rust
/// use grid1d::intervals::*;
///
/// let a = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 2.0))
/// );
/// let b = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(1.0, 3.0))
/// );
///
/// if let Some(intersection) = a.intersection(&b) {
///     // Result: [1.0, 2.0] as general Interval enum
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::PositiveLength(positive)) => {
///             println!("Intersection has positive length: {}", positive.length());
///         }
///         Interval::FiniteLength(IntervalFiniteLength::ZeroLength(singleton)) => {
///             println!("Intersection is a single point: {}", singleton.value());
///         }
///         _ => unreachable!("Finite intervals always have finite intersections"),
///     }
/// }
///
/// // Intersection creating a singleton
/// let c = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 1.0))
/// );
/// let d = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(1.0, 2.0))
/// );
///
/// if let Some(intersection) = c.intersection(&d) {
///     // Result: singleton at point 1.0
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::ZeroLength(singleton)) => {
///             assert_eq!(singleton.value(), &1.0);
///         }
///         _ => panic!("Expected singleton intersection"),
///     }
/// }
/// ```
///
/// ## Pattern Matching and Type Analysis
///
/// ### Distinguishing Between Positive and Zero Length
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// fn analyze_finite_interval(interval: &IntervalFiniteLength<f64>) -> String {
///     match interval {
///         IntervalFiniteLength::PositiveLength(positive) => {
///             format!(
///                 "Positive-length interval: [{}, {}], length = {}, midpoint = {}",
///                 positive.lower_bound_value(),
///                 positive.upper_bound_value(),
///                 positive.length(),
///                 positive.midpoint()
///             )
///         }
///         IntervalFiniteLength::ZeroLength(singleton) => {
///             format!(
///                 "Zero-length interval (singleton): [{}], measure = 0",
///                 singleton.value()
///             )
///         }
///     }
/// }
///
/// let positive = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(1.0, 3.0))
/// );
/// let zero = IntervalFiniteLength::ZeroLength(IntervalSingleton::new(2.0));
///
/// println!("{}", analyze_finite_interval(&positive));
/// // Output: "Positive-length interval: [1, 3], length = 2, midpoint = 2"
///
/// println!("{}", analyze_finite_interval(&zero));  
/// // Output: "Zero-length interval (singleton): [2], measure = 0"
/// ```
///
/// ### Integration and Measure Theory Applications
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
/// use try_create::New;
///
/// /// Compute the measure (length) of any finite interval
/// fn measure<T: RealScalar>(interval: &IntervalFiniteLength<T>) -> T {
///     match interval {
///         IntervalFiniteLength::PositiveLength(positive) => positive.length().into_inner(),
///         IntervalFiniteLength::ZeroLength(_) => T::zero(), // Measure is always 0
///     }
/// }
///
/// /// Integrate a constant function over any finite interval
/// fn integrate_constant<T: RealScalar + Clone>(
///     interval: &IntervalFiniteLength<T>,
///     constant_value: T
/// ) -> T {
///     // Integral = constant × measure of interval
///     constant_value * measure(interval)
/// }
///
/// let positive = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 2.0))
/// );
/// let zero = IntervalFiniteLength::ZeroLength(IntervalSingleton::new(1.0));
///
/// assert_eq!(measure(&positive), 2.0);        // Length of [0,2] is 2
/// assert_eq!(measure(&zero), 0.0);            // Length of {1} is 0
///
/// assert_eq!(integrate_constant(&positive, 5.0), 10.0);  // 5 × 2 = 10
/// assert_eq!(integrate_constant(&zero, 5.0), 0.0);       // 5 × 0 = 0
/// ```
///
/// ## Type Conversion and Recovery
///
/// ### Converting to Specific Types
/// ```rust
/// use grid1d::intervals::*;
///
/// let finite = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 1.0))
/// );
///
/// // Convert to general interval enum
/// let general: Interval<f64> = finite.clone().into();
///
/// // Try to recover positive-length interval
/// match finite {
///     IntervalFiniteLength::PositiveLength(positive) => {
///         println!("Successfully extracted positive-length interval");
///         // Can access all positive-length specific methods
///         println!("Length: {}", positive.length());
///         println!("Midpoint: {}", positive.midpoint());
///     }
///     IntervalFiniteLength::ZeroLength(_) => {
///         println!("This is a singleton, not positive-length");
///     }
/// }
/// ```
///
/// ### Working with Results from Operations
/// ```rust
/// use grid1d::intervals::*;
///
/// fn process_intersection_result(
///     intersection: Option<Interval<f64>>
/// ) -> String {
///     match intersection {
///         Some(Interval::FiniteLength(finite_length)) => {
///             match finite_length {
///                 IntervalFiniteLength::PositiveLength(positive) => {
///                     format!("Non-trivial intersection with length {}", positive.length())
///                 }
///                 IntervalFiniteLength::ZeroLength(singleton) => {
///                     format!("Intervals meet at single point: {}", singleton.value())
///                 }
///             }
///         }
///         Some(Interval::InfiniteLength(_)) => {
///             "Infinite intersection (shouldn't happen with finite inputs)".to_string()
///         }
///         None => "No intersection (disjoint intervals)".to_string(),
///     }
/// }
/// ```
///
/// ## Performance Characteristics
///
/// ### Memory Layout
/// - **Positive-length variants**: Two scalar values + boundary type information (16-24 bytes typical)
/// - **Zero-length variants**: One scalar value (8 bytes typical for f64)
/// - **Enum overhead**: Small discriminant tag (1-8 bytes depending on alignment)
/// - **Total size**: Typically 24-32 bytes depending on scalar type and alignment
///
/// ### Operation Complexity
/// | Operation | Positive Length | Zero Length | Notes |
/// |-----------|----------------|-------------|-------|
/// | **Point queries** | O(1) - 2 comparisons | O(1) - 1 comparison | Constant time regardless of variant |
/// | **Containment tests** | O(1) - boundary logic | O(1) - equality check | No significant difference |
/// | **Intersections** | O(1) - bound arithmetic | O(1) - equality/containment | May allocate result |
/// | **Length calculation** | O(1) - subtraction | O(1) - returns zero | Zero-length always returns 0 |
/// | **Pattern matching** | O(1) - compile-time optimized | O(1) - compile-time optimized | No runtime dispatch cost |
///
/// ### Scalar Type Performance Impact
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::{RealNative64StrictFiniteInDebug, RealNative64StrictFinite, RealScalar};
///
/// // These have identical performance in release builds:
/// type FastFiniteInterval = IntervalFiniteLength<f64>;
/// type OptimalFiniteInterval = IntervalFiniteLength<RealNative64StrictFiniteInDebug>;
///
/// // This has small validation overhead:
/// type SafeFiniteInterval = IntervalFiniteLength<RealNative64StrictFinite>;
///
/// // Performance test function (generic over scalar type)
/// fn benchmark_finite_operations<T: RealScalar + Clone>(
///     interval1: &IntervalFiniteLength<T>,
///     interval2: &IntervalFiniteLength<T>
/// ) {
///     // All operations compile to identical assembly for f64 and RealNative64StrictFiniteInDebug
///     let _contains = interval1.contains_interval(interval2);
///     let _intersection = interval1.intersection(interval2);
///     // Pattern matching is zero-cost in all cases
///     match interval1 {
///         IntervalFiniteLength::PositiveLength(positive) => {
///             let _length = positive.length().into_inner(); // O(1) subtraction
///         }
///         IntervalFiniteLength::ZeroLength(_) => {
///             let _length = T::zero(); // O(1) constant
///         }
///     }
/// }
/// ```
///
/// ## Mathematical Properties and Guarantees
///
/// ### Measure Theory Properties
/// - **Positive-length intervals** always have **positive measure**: `μ([a,b]) = b - a > 0`
/// - **Zero-length intervals** always have **zero measure**: `μ({a}) = 0`
/// - **Additivity**: For disjoint finite intervals, `μ(A ∪ B) = μ(A) + μ(B)`
/// - **Translation invariance**: `μ(A + c) = μ(A)` for any constant `c`
///
/// ### Set Theory Properties
/// - **Positive-length intervals** are **uncountably infinite** sets
/// - **Zero-length intervals** are **finite** sets (cardinality 1)
/// - **Closure**: Intersection of finite intervals is always finite (or empty)
/// - **Boundedness**: All finite intervals are bounded in the real line
///
/// ### Integration Properties
/// ```rust
/// use grid1d::intervals::*;
///
/// // Fundamental theorem: integral over zero-length interval is always zero
/// fn integral_over_singleton<F>(f: F, singleton: &IntervalSingleton<f64>) -> f64
/// where F: Fn(f64) -> f64
/// {
///     0.0 // Always zero regardless of function f
/// }
///
/// // For positive-length intervals, integral depends on function and interval length
/// fn can_have_nonzero_integral<F>(
///     f: F,
///     positive: &IntervalFinitePositiveLength<f64>
/// ) -> bool
/// where F: Fn(f64) -> f64
/// {
///     positive.length().into_inner() > 0.0 // Can be non-zero if function is non-zero somewhere
/// }
/// ```
///
/// ## Integration with Library Ecosystem
///
/// ### With Numerical Integration
/// ```rust
/// use grid1d::intervals::*;
///
/// fn adaptive_integrate(
///     f: impl Fn(f64) -> f64,
///     domain: IntervalFiniteLength<f64>
/// ) -> f64 {
///     match domain {
///         IntervalFiniteLength::PositiveLength(interval) => {
///             // Use sophisticated numerical integration
///             // (Gaussian quadrature, adaptive subdivision, etc.)
///             integrate_positive_length(f, &interval)
///         }
///         IntervalFiniteLength::ZeroLength(_) => {
///             // Integral over single point is always zero
///             0.0
///         }
///     }
/// }
///
/// fn integrate_positive_length(
///     f: impl Fn(f64) -> f64,
///     interval: &IntervalFinitePositiveLength<f64>
/// ) -> f64 {
///     // Placeholder for actual integration algorithm
///     let midpoint = interval.midpoint();
///     f(midpoint) * interval.length().into_inner() // Simple midpoint rule
/// }
/// ```
///
/// ### With Probability Theory
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Represents a probability distribution support
/// struct ProbabilitySupport {
///     support: IntervalFiniteLength<f64>
/// }
///
/// impl ProbabilitySupport {
///     fn new(support: IntervalFiniteLength<f64>) -> Self {
///         Self { support }
///     }
///     
///     fn is_discrete(&self) -> bool {
///         matches!(self.support, IntervalFiniteLength::ZeroLength(_))
///     }
///     
///     fn is_continuous(&self) -> bool {
///         matches!(self.support, IntervalFiniteLength::PositiveLength(_))
///     }
///     
///     fn measure(&self) -> f64 {
///         match &self.support {
///             IntervalFiniteLength::PositiveLength(interval) => interval.length().into_inner(),
///             IntervalFiniteLength::ZeroLength(_) => 0.0,
///         }
///     }
/// }
/// ```
///
/// ## Common Use Cases and Examples
///
/// ### Computational Geometry
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// /// Project a point onto a finite interval
/// fn project_point_onto_interval(
///     point: f64,
///     interval: &IntervalFiniteLength<f64>
/// ) -> f64 {
///     match interval {
///         IntervalFiniteLength::PositiveLength(positive) => {
///             // Clamp point to interval bounds
///             point.max(*positive.lower_bound_value())
///                  .min(*positive.upper_bound_value())
///         }
///         IntervalFiniteLength::ZeroLength(singleton) => {
///             // Always project to the single point
///             *singleton.value()
///         }
///     }
/// }
///
/// let interval = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 1.0))
/// );
/// let singleton = IntervalFiniteLength::ZeroLength(IntervalSingleton::new(0.5));
///
/// assert_eq!(project_point_onto_interval(-0.5, &interval), 0.0);  // Clamp to lower bound
/// assert_eq!(project_point_onto_interval(0.7, &interval), 0.7);   // Inside interval
/// assert_eq!(project_point_onto_interval(1.5, &interval), 1.0);   // Clamp to upper bound
///
/// assert_eq!(project_point_onto_interval(-100.0, &singleton), 0.5); // Always singleton value
/// assert_eq!(project_point_onto_interval(100.0, &singleton), 0.5);  // Always singleton value
/// ```
///
/// ### Scientific Computing
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// /// Compute the uniform grid points within a finite interval
/// fn uniform_grid(interval: &IntervalFiniteLength<f64>, num_points: usize) -> Vec<f64> {
///     match interval {
///         IntervalFiniteLength::PositiveLength(positive) => {
///             if num_points <= 1 {
///                 vec![positive.midpoint()]
///             } else {
///                 let lower = *positive.lower_bound_value();
///                 let upper = *positive.upper_bound_value();
///                 let step = (upper - lower) / (num_points - 1) as f64;
///                 (0..num_points)
///                     .map(|i| lower + i as f64 * step)
///                     .collect()
///             }
///         }
///         IntervalFiniteLength::ZeroLength(singleton) => {
///             // Grid of a singleton is just the point itself
///             vec![*singleton.value(); num_points.max(1)]
///         }
///     }
/// }
///
/// let interval = IntervalFiniteLength::PositiveLength(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 10.0))
/// );
/// let grid = uniform_grid(&interval, 5);
/// assert_eq!(grid, vec![0.0, 2.5, 5.0, 7.5, 10.0]);
///
/// let singleton = IntervalFiniteLength::ZeroLength(IntervalSingleton::new(42.0));
/// let singleton_grid = uniform_grid(&singleton, 3);
/// assert_eq!(singleton_grid, vec![42.0, 42.0, 42.0]);
/// ```
///
/// ## Best Practices and Recommendations
///
/// ### When to Use [`IntervalFiniteLength`]
/// - **API Design**: When you need to accept any finite interval but want to exclude infinite ones
/// - **Numerical Integration**: Finite intervals have well-defined integrals
/// - **Measure Theory**: When you need to distinguish between zero and positive measure
/// - **Optimization**: When working with bounded feasible regions
///
/// ### When to Use Specific Variants
/// - **PositiveLength**: For continuous domains, integration regions, probability supports
/// - **ZeroLength**: For discrete events, point constraints, boundary conditions
///
/// ### Recommended Patterns
/// ```rust
/// use grid1d::intervals::*;
/// use num::Zero;
/// use num_valid::RealNative64StrictFiniteInDebug;
///
/// // Define type aliases for your application domain
/// type Real = RealNative64StrictFiniteInDebug;
/// type FiniteInterval = IntervalFiniteLength<Real>;
/// type PositiveInterval = IntervalFinitePositiveLength<Real>;
/// type Singleton = IntervalSingleton<Real>;
///
/// // Pattern: Handle both cases explicitly
/// fn compute_weighted_measure(
///     interval: &FiniteInterval,
///     weight: Real
/// ) -> Real {
///     match interval {
///         IntervalFiniteLength::PositiveLength(positive) => {
///             weight * positive.length().into_inner() // Non-zero contribution possible
///         }
///         IntervalFiniteLength::ZeroLength(_) => {
///             Real::zero() // Always zero regardless of weight
///         }
///     }
/// }
///
/// // Pattern: Convert to most specific type when needed
/// fn extract_bounds(interval: FiniteInterval) -> Result<(Real, Real), String> {
///     match interval {
///         IntervalFiniteLength::PositiveLength(positive) => {
///             Ok(positive.into_bounds_pair()) // Get (lower, upper) bounds
///         }
///         IntervalFiniteLength::ZeroLength(singleton) => {
///             let value = singleton.into_inner();
///             Ok((value.clone(), value)) // Lower and upper are the same
///         }
///     }
/// }
/// ```
///
/// ## Error Handling and Edge Cases
///
/// ### Common Pitfalls and Solutions
/// ```rust
/// use grid1d::intervals::*;
///
/// // WRONG: Assuming all finite intervals have positive length
/// fn naive_midpoint(interval: &IntervalFiniteLength<f64>) -> f64 {
///     // This panics for singletons!
///     // interval.lower_bound_value() + interval.upper_bound_value()) / 2.0
///     unimplemented!("This approach is incorrect")
/// }
///
/// // CORRECT: Handle both cases appropriately  
/// fn robust_midpoint(interval: &IntervalFiniteLength<f64>) -> f64 {
///     match interval {
///         IntervalFiniteLength::PositiveLength(positive) => {
///             positive.midpoint() // Proper midpoint calculation
///         }
///         IntervalFiniteLength::ZeroLength(singleton) => {
///             *singleton.value() // The single point is the "midpoint"
///         }
///     }
/// }
///
/// // WRONG: Dividing by length without checking for zero
/// fn naive_normalize(interval: &IntervalFiniteLength<f64>, value: f64) -> f64 {
///     // This can divide by zero for singletons!
///     // value / interval.length()
///     unimplemented!("This approach is incorrect")
/// }
///
/// // CORRECT: Handle zero-length case explicitly
/// fn robust_normalize(
///     interval: &IntervalFiniteLength<f64>,
///     value: f64
/// ) -> Result<f64, &'static str> {
///     match interval {
///         IntervalFiniteLength::PositiveLength(positive) => {
///             Ok(value / positive.length().into_inner())
///         }
///         IntervalFiniteLength::ZeroLength(_) => {
///             if value == 0.0 {
///                 Ok(0.0) // 0/0 case - define as 0
///             } else {
///                 Err("Cannot normalize non-zero value over zero-length interval")
///             }
///         }
///     }
/// }
/// ```
///
/// ## Mathematical Correctness Guarantees
///
/// The [`IntervalFiniteLength`] enum maintains all essential mathematical properties:
///
/// - **Measure consistency**: The measure is always non-negative and finite
/// - **Containment transitivity**: If A ⊆ B and B ⊆ C, then A ⊆ C  
/// - **Intersection commutativity**: A ∩ B = B ∩ A
/// - **Intersection associativity**: (A ∩ B) ∩ C = A ∩ (B ∩ C)
/// - **Monotonicity**: If A ⊆ B, then μ(A) ≤ μ(B)
/// - **Finite additivity**: For disjoint A and B, μ(A ∪ B) = μ(A) + μ(B)
///
/// These properties are preserved regardless of the scalar type used and are guaranteed
/// by the underlying implementations of the [`IntervalTrait`] and associated methods.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound(deserialize = "RealType: for<'a> Deserialize<'a>"))]
pub enum IntervalFiniteLength<RealType: RealScalar> {
    /// An interval of ***finite*** and ***positive length***.
    ///
    /// This variant represents intervals where the upper bound is strictly greater than
    /// the lower bound, resulting in a set with uncountably infinite points and positive
    /// measure. Examples include `[a,b]`, `(a,b)`, `[a,b)`, and `(a,b]` where `a < b`.
    ///
    /// **Properties:**
    /// - **Measure**: `> 0` (specifically `|upper - lower|`)
    /// - **Cardinality**: Uncountably infinite
    /// - **Topology**: Connected set with non-empty interior
    /// - **Integration**: Can support non-trivial integrals
    PositiveLength(IntervalFinitePositiveLength<RealType>),

    /// An interval of ***finite*** and ***zero length***.
    ///
    /// This variant represents singleton intervals containing exactly one point.
    /// These are degenerate intervals denoted as `[a]` or `{a}` in mathematical notation.
    ///
    /// **Properties:**
    /// - **Measure**: Always `0`
    /// - **Cardinality**: Exactly `1`
    /// - **Topology**: Isolated point with empty interior
    /// - **Integration**: All integrals evaluate to `0`
    ZeroLength(IntervalSingleton<RealType>),
}

impl<RealType: RealScalar> IntervalFiniteLength<RealType> {
    /// Constructs a finite-length interval from runtime-typed bounds.
    ///
    /// This function handles all combinations of open and closed bounds for finite intervals,
    /// automatically selecting the appropriate concrete interval type. It also handles the special
    /// case of singleton intervals (when both bounds are closed and equal).
    ///
    /// # Arguments
    ///
    /// * `lower_bound` - Runtime-typed lower bound (closed or open)
    /// * `upper_bound` - Runtime-typed upper bound (closed or open)
    ///
    /// # Bound Type Selection
    ///
    /// | Lower | Upper | Result Type | Notation |
    /// |-------|-------|-------------|----------|
    /// | Closed | Closed | [`IntervalClosed`] or [`IntervalSingleton`] | `[a, b]` or `{a}` |
    /// | Closed | Open | [`IntervalLowerClosedUpperOpen`] | `[a, b)` |
    /// | Open | Closed | [`IntervalLowerOpenUpperClosed`] | `(a, b]` |
    /// | Open | Open | [`IntervalOpen`] | `(a, b)` |
    ///
    /// # Returns
    ///
    /// * `Ok(IntervalFiniteLength)` - Successfully constructed interval
    /// * `Err(ErrorsIntervalConstruction)` - If `lower_bound ≥ upper_bound` (except for singleton case)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Note: This is a private function used internally
    /// use grid1d::intervals::*;
    /// use grid1d::bounds::*;
    /// use try_create::New;
    ///
    /// // Closed interval [0, 1]
    /// let lower: LowerBoundRuntime<f64> = LowerBoundClosed::new(0.0).into();
    /// let upper: UpperBoundRuntime<f64> = UpperBoundClosed::new(1.0).into();
    /// let interval = IntervalFiniteLength::try_from_runtime_bounds(lower, upper).unwrap();
    /// ```
    ///
    /// # Singleton Detection
    ///
    /// When both bounds are closed and have equal values, automatically creates an
    /// [`IntervalSingleton`] instead of a zero-length [`IntervalClosed`].
    ///
    /// # Design Notes
    ///
    /// This function is marked `#[allow(dead_code)]` as it serves as infrastructure for
    /// the universal `Interval::try_new` constructor. It may be promoted to `pub(crate)`
    /// if needed elsewhere in the codebase.
    #[allow(dead_code)]
    pub(crate) fn try_from_runtime_bounds(
        lower_bound: LowerBoundRuntime<RealType>,
        upper_bound: UpperBoundRuntime<RealType>,
    ) -> Result<Self, ErrorsIntervalConstruction<RealType>> {
        // Delegate to the appropriate concrete interval type's try_new() method
        // This ensures consistent validation and maintains a single source of truth
        match (lower_bound, upper_bound) {
            (LowerBoundRuntime::Closed(lower_bound), UpperBoundRuntime::Closed(upper_bound)) => {
                if lower_bound.as_ref() == upper_bound.as_ref() {
                    Ok(IntervalSingleton::new(lower_bound.into_inner()).into())
                } else {
                    Ok(IntervalClosed::try_from_static_bounds(lower_bound, upper_bound)?.into())
                }
            }
            (LowerBoundRuntime::Closed(lower_bound), UpperBoundRuntime::Open(upper_bound)) => Ok(
                IntervalLowerClosedUpperOpen::try_from_static_bounds(lower_bound, upper_bound)?
                    .into(),
            ),
            (LowerBoundRuntime::Open(lower_bound), UpperBoundRuntime::Closed(upper_bound)) => Ok(
                IntervalLowerOpenUpperClosed::try_from_static_bounds(lower_bound, upper_bound)?
                    .into(),
            ),
            (LowerBoundRuntime::Open(lower_bound), UpperBoundRuntime::Open(upper_bound)) => {
                Ok(IntervalOpen::try_from_static_bounds(lower_bound, upper_bound)?.into())
            }
        }
    }
}

impl<RealType: RealScalar> IntervalOperations for IntervalFiniteLength<RealType> {}

impl<RealType: RealScalar> IntervalBoundsRuntime for IntervalFiniteLength<RealType> {
    type RealType = RealType;

    #[inline]
    fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<RealType>> {
        match self {
            IntervalFiniteLength::PositiveLength(interval) => interval.lower_bound_runtime(),
            IntervalFiniteLength::ZeroLength(interval) => interval.lower_bound_runtime(),
        }
    }

    #[inline]
    fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<RealType>> {
        match self {
            IntervalFiniteLength::PositiveLength(interval) => interval.upper_bound_runtime(),
            IntervalFiniteLength::ZeroLength(interval) => interval.upper_bound_runtime(),
        }
    }
}

impl<RealType: RealScalar> Contains for IntervalFiniteLength<RealType> {
    /// Returns `true` if the 1D point/coordinate `x` is contained in `self`.
    #[inline(always)]
    fn contains_point(&self, x: &RealType) -> bool {
        match self {
            IntervalFiniteLength::PositiveLength(interval) => interval.contains_point(x),
            IntervalFiniteLength::ZeroLength(interval) => interval.contains_point(x),
        }
    }
}

impl<RealType: RealScalar> IntervalTrait for IntervalFiniteLength<RealType> {}
//--------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------------
/// Generic bounded interval structure for intervals with two finite endpoints.
///
/// The [`IntervalBounded`] struct represents the most general form of finite intervals,
/// where both the lower and upper bounds are finite real numbers. This generic structure
/// can represent all possible boundary combinations (open/closed) through its type parameters,
/// providing maximum flexibility while maintaining type safety.
///
/// ## Generic Parameters
///
/// - `RealType`: Must implement [`RealScalar`] for mathematical operations and comparisons
/// - `LowerBoundType`: Either [`Closed`] or [`Open`] to specify lower boundary inclusion
/// - `UpperBoundType`: Either [`Closed`] or [`Open`] to specify upper boundary inclusion
///
/// ## Boundary Type Combinations
///
/// The type parameters allow representing all possible finite interval types:
///
/// | Lower | Upper | Notation | Mathematical Set |
/// |-------|-------|----------|------------------|
/// | `Closed` | `Closed` | `[a, b]` | `{x : a ≤ x ≤ b}` |
/// | `Open` | `Open` | `(a, b)` | `{x : a < x < b}` |
/// | `Closed` | `Open` | `[a, b)` | `{x : a ≤ x < b}` |
/// | `Open` | `Closed` | `(a, b]` | `{x : a < x ≤ b}` |
///
/// ## Mathematical Properties
///
/// All bounded intervals share these fundamental properties:
/// - **Finite measure**: `μ([a,b]) = b - a > 0` (for valid intervals)
/// - **Compactness**: Only closed intervals `[a,b]` are compact
/// - **Connectedness**: All bounded intervals are connected sets
/// - **Boundedness**: Both bounds are finite real numbers
///
/// ## Type Aliases
///
/// The library provides convenient type aliases for common cases:
/// - [`IntervalClosed`] = `IntervalBounded<RealType, Closed, Closed>`
/// - [`IntervalOpen`] = `IntervalBounded<RealType, Open, Open>`
/// - [`IntervalLowerClosedUpperOpen`] = `IntervalBounded<RealType, Closed, Open>`
/// - [`IntervalLowerOpenUpperClosed`] = `IntervalBounded<RealType, Open, Closed>`
///
/// ## Construction
///
/// ```rust
/// use grid1d::{
///     bounds::{Closed, Open},
///     intervals::bounded::*,
/// };
///
/// // Direct construction (requires explicit type parameters)
/// let closed: IntervalBounded<f64, Closed, Closed> =
///     IntervalBounded::try_new(0.0, 1.0).unwrap();
///
/// // Preferred: use type aliases
/// let closed = IntervalClosed::try_new(0.0, 1.0).unwrap();
/// let open = IntervalOpen::try_new(0.0, 1.0).unwrap();
/// ```
///
/// ## Performance Characteristics
///
/// - **Memory**: Two scalar values + bound type information (compile-time)
/// - **Operations**: O(1) for all basic operations (point queries, intersections)
/// - **Type safety**: Boundary semantics encoded at compile time
/// - **Zero-cost abstractions**: Boundary types have no runtime overhead
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Getters)]
#[serde(bound(deserialize = "RealType: for<'a> Deserialize<'a>"))]
pub struct IntervalBounded<
    RealType: RealScalar,
    LowerBoundType: BoundType,
    UpperBoundType: BoundType,
> {
    /// The lower bound of the interval, included in the interval.
    ///
    /// This value represents the smallest point contained in the interval.
    /// For a closed lower bound `[a`, any point `x` in the interval satisfies `x ≥ a`.
    /// For an open lower bound `(a`, any point `x` in the interval satisfies `x > a`.
    #[getset(get = "pub")]
    lower_bound: LowerBound<RealType, LowerBoundType>,

    /// The upper bound of the interval, included in the interval.
    ///
    /// This value represents the largest point contained in the interval.
    /// For a closed upper bound `b]`, any point `x` in the interval satisfies `x ≤ b`.
    /// For an open upper bound `b)`, any point `x` in the interval satisfies `x < b`.
    #[getset(get = "pub")]
    upper_bound: UpperBound<RealType, UpperBoundType>,
}

impl<RealType: RealScalar, LowerBoundType: BoundType, UpperBoundType: BoundType> GetLowerBoundValue
    for IntervalBounded<RealType, LowerBoundType, UpperBoundType>
{
    type LowerBoundValue = RealType;

    #[inline(always)]
    fn lower_bound_value(&self) -> &RealType {
        &self.lower_bound.value
    }

    #[inline(always)]
    fn is_lower_bound_closed(&self) -> bool {
        LowerBoundType::is_closed()
    }
}

impl<RealType: RealScalar, LowerBoundType: BoundType, UpperBoundType: BoundType> GetUpperBoundValue
    for IntervalBounded<RealType, LowerBoundType, UpperBoundType>
{
    type UpperBoundValue = RealType;

    #[inline(always)]
    fn upper_bound_value(&self) -> &RealType {
        &self.upper_bound.value
    }

    #[inline(always)]
    fn is_upper_bound_closed(&self) -> bool {
        UpperBoundType::is_closed()
    }
}

impl<RealType: RealScalar, LowerBoundType: BoundType, UpperBoundType: BoundType>
    IntervalFinitePositiveLengthTrait for IntervalBounded<RealType, LowerBoundType, UpperBoundType>
where
    Self: IntervalBoundsRuntime<RealType = RealType>,
    LowerBound<RealType, LowerBoundType>: ValueWithinBound<RealType = RealType>,
    UpperBound<RealType, UpperBoundType>: ValueWithinBound<RealType = RealType>,
{
    /// Return the inner bounds of the interval as a pair in which the first entry of the pair
    /// is the lower bound and the second entry of the pair is the upper bound.
    ///
    /// # Note
    /// This function consumes `Self` (no cloning of the bounds is needed).
    #[inline(always)]
    fn into_bounds_pair(self) -> (Self::RealType, Self::RealType) {
        (self.lower_bound.into_inner(), self.upper_bound.into_inner())
    }

    fn translate(&self, amount: Self::RealType) -> Self {
        let lower_bound = self.lower_bound_value().clone() + amount.clone();
        let upper_bound = self.upper_bound_value().clone() + amount;
        Self::new(lower_bound, upper_bound)
    }

    fn scale(&self, factor: &PositiveRealScalar<Self::RealType>) -> Self {
        let center = self.midpoint();
        let half_len = Self::RealType::one_div_2() * self.length().as_ref() * factor.as_ref();
        Self::new(center.clone() - &half_len, center.clone() + half_len)
    }

    fn expand(&self, amount: &PositiveRealScalar<Self::RealType>) -> Self {
        let lower_bound = self.lower_bound_value().clone() - amount.as_ref();
        let upper_bound = self.upper_bound_value().clone() + amount.as_ref();
        Self::new(lower_bound, upper_bound)
    }
}

impl<RealType: RealScalar> GetLowerBoundValue for IntervalFinitePositiveLength<RealType> {
    type LowerBoundValue = RealType;

    #[inline(always)]
    fn lower_bound_value(&self) -> &RealType {
        match self {
            IntervalFinitePositiveLength::Closed(interval) => interval.lower_bound_value(),
            IntervalFinitePositiveLength::Open(interval) => interval.lower_bound_value(),
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.lower_bound_value()
            }
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.lower_bound_value()
            }
        }
    }

    #[inline(always)]
    fn is_lower_bound_closed(&self) -> bool {
        match self {
            IntervalFinitePositiveLength::Closed(interval) => interval.is_lower_bound_closed(),
            IntervalFinitePositiveLength::Open(interval) => interval.is_lower_bound_closed(),
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.is_lower_bound_closed()
            }
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.is_lower_bound_closed()
            }
        }
    }
}

impl<RealType: RealScalar> GetUpperBoundValue for IntervalFinitePositiveLength<RealType> {
    type UpperBoundValue = RealType;

    #[inline(always)]
    fn upper_bound_value(&self) -> &RealType {
        match self {
            IntervalFinitePositiveLength::Closed(interval) => interval.upper_bound_value(),
            IntervalFinitePositiveLength::Open(interval) => interval.upper_bound_value(),
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.upper_bound_value()
            }
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.upper_bound_value()
            }
        }
    }

    #[inline(always)]
    fn is_upper_bound_closed(&self) -> bool {
        match self {
            IntervalFinitePositiveLength::Closed(interval) => interval.is_upper_bound_closed(),
            IntervalFinitePositiveLength::Open(interval) => interval.is_upper_bound_closed(),
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.is_upper_bound_closed()
            }
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.is_upper_bound_closed()
            }
        }
    }
}

impl<RealType: RealScalar> IntervalFinitePositiveLengthTrait
    for IntervalFinitePositiveLength<RealType>
{
    /// Return the inner bounds of the interval as a pair in which the first entry of the pair
    /// is the lower bound and the second entry of the pair is the upper bound.
    ///
    /// # Note
    /// This function consumes `Self` (no cloning of the bounds is needed).
    #[inline(always)]
    fn into_bounds_pair(self) -> (Self::RealType, Self::RealType) {
        match self {
            IntervalFinitePositiveLength::Closed(interval) => interval.into_bounds_pair(),
            IntervalFinitePositiveLength::Open(interval) => interval.into_bounds_pair(),
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.into_bounds_pair()
            }
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.into_bounds_pair()
            }
        }
    }

    fn translate(&self, amount: Self::RealType) -> Self {
        match self {
            IntervalFinitePositiveLength::Closed(interval) => {
                interval.translate(amount.clone()).into()
            }
            IntervalFinitePositiveLength::Open(interval) => {
                interval.translate(amount.clone()).into()
            }
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.translate(amount.clone()).into()
            }
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.translate(amount.clone()).into()
            }
        }
    }

    fn scale(&self, factor: &PositiveRealScalar<Self::RealType>) -> Self {
        match self {
            IntervalFinitePositiveLength::Closed(interval) => interval.scale(factor).into(),
            IntervalFinitePositiveLength::Open(interval) => interval.scale(factor).into(),
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.scale(factor).into()
            }
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.scale(factor).into()
            }
        }
    }
    fn expand(&self, amount: &PositiveRealScalar<Self::RealType>) -> Self {
        match self {
            IntervalFinitePositiveLength::Closed(interval) => interval.expand(amount).into(),
            IntervalFinitePositiveLength::Open(interval) => interval.expand(amount).into(),
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.expand(amount).into()
            }
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.expand(amount).into()
            }
        }
    }
}

#[duplicate_item(
    interval_type                  lower_bound_type upper_bound_type;
    [IntervalClosed]               [Closed]         [Closed];
    [IntervalOpen]                 [Open]           [Open];
    [IntervalLowerClosedUpperOpen] [Closed]         [Open];
    [IntervalLowerOpenUpperClosed] [Open]           [Closed];
)]
impl<RealType: RealScalar> IntervalBoundsRuntime for interval_type<RealType> {
    type RealType = RealType;

    #[inline(always)]
    fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<RealType>> {
        Some(LowerBoundRuntime::lower_bound_type(
            self.lower_bound().clone(),
        ))
    }

    #[inline(always)]
    fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<RealType>> {
        Some(UpperBoundRuntime::upper_bound_type(
            self.upper_bound().clone(),
        ))
    }
}

impl<RealType: RealScalar, LowerBoundType: BoundType, UpperBoundType: BoundType> IntervalTrait
    for IntervalBounded<RealType, LowerBoundType, UpperBoundType>
where
    Self: IntervalBoundsRuntime<RealType = RealType>,
    LowerBound<RealType, LowerBoundType>: ValueWithinBound<RealType = RealType>,
    UpperBound<RealType, UpperBoundType>: ValueWithinBound<RealType = RealType>,
{
}

//--------------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
///  A closed interval `[a, b]` where both endpoints are included.
///
/// The [`IntervalClosed`] represents the most common type of interval in mathematics,
/// where both the lower bound `a` and upper bound `b` are part of the interval.
/// Every real number `x` satisfying `a ≤ x ≤ b` belongs to this interval.
///
/// ## Mathematical Properties
///
/// - **Notation**: `[a, b]`
/// - **Definition**: `{x ∈ ℝ : a ≤ x ≤ b}`
/// - **Endpoints**: Both included
/// - **Compactness**: Always compact (closed and bounded)
/// - **Connectedness**: Always connected (no gaps)
///
/// ## Use Cases
///
/// Closed intervals are ideal when:
/// - You need to include boundary values (e.g., `[0., 1.]` for probabilities)
/// - Working with integration bounds where endpoints matter
/// - Defining domains where the boundary is part of the solution
/// - Representing physical quantities with inclusive limits
///
/// ## Construction
///
/// ```rust
/// use grid1d::intervals::*;
///
/// // Infallible construction (panics in debug mode if invalid)
/// let interval = IntervalClosed::new(0.0, 1.0);
///
/// // Fallible construction (returns Result)
/// let result = IntervalClosed::try_new(0.0, 1.0).unwrap();
/// ```
///
/// ## Key Operations
///
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalClosed::new(-1.0, 1.0);
///
/// // Point containment (includes endpoints)
/// assert!(interval.contains_point(&-1.0));  // Lower bound included
/// assert!(interval.contains_point(&0.0));   // Interior point
/// assert!(interval.contains_point(&1.0));   // Upper bound included
/// assert!(!interval.contains_point(&2.0));  // Outside interval
///
/// // Geometric properties
/// assert_eq!(interval.length().into_inner(), 2.0);       // |b - a|
/// assert_eq!(interval.midpoint(), 0.0);    // (a + b) / 2
/// assert!(interval.is_symmetric());         // True when a = -b
///
/// // Clamping values to interval bounds
/// assert_eq!(interval.clamp(-2.0), -1.0);   // Below range
/// assert_eq!(interval.clamp(0.5), 0.5);     // Within range
/// assert_eq!(interval.clamp(2.0), 1.0);     // Above range
/// ```
///
/// ## Comparison with Other Interval Types
///
/// | Property | Closed `[a,b]` | Open `(a,b)` | Half-open `[a,b)` |
/// |----------|----------------|--------------|-------------------|
/// | Contains `a` | ✓ | ✗ | ✓ |
/// | Contains `b` | ✓ | ✗ | ✗ |
/// | Length | `b - a` | `b - a` | `b - a` |
/// | Compactness | Always | Never | Never |
/// | Supremum | `b` (achieved) | `b` (not achieved) | `b` (not achieved) |
/// | Infimum | `a` (achieved) | `a` (not achieved) | `a` (achieved) |
///
/// ## Performance Characteristics
///
/// - **Memory**: Two values of type `RealType` plus bound type information
/// - **Point queries**: O(1) - two comparisons
/// - **Intersection**: O(1) - bound arithmetic
/// - **Construction**: O(1) - single comparison in debug mode
///
/// ## Error Conditions
///
/// Construction fails when:
/// - `lower_bound > upper_bound` (invalid interval)
/// - Either bound is not finite (NaN or infinite)
///
/// ```rust
/// use grid1d::intervals::*;
///
/// // These will fail
/// assert!(IntervalClosed::try_new(1.0, 0.0).is_err());     // Inverted bounds
/// assert!(IntervalClosed::try_new(f64::NAN, 1.0).is_err()); // NaN bound
/// ```
///
/// ## Advanced Usage
///
/// ### Generic Programming
///
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// fn process_closed_interval<T: RealScalar>(interval: &IntervalClosed<T>) {
///     // Work with any numeric type that implements RealScalar
///     println!("Length: {}", interval.length());
/// }
/// ```
///
/// ### Conversion to Other Types
///
/// ```rust
/// use grid1d::intervals::*;
///
/// let closed = IntervalClosed::new(0.0, 1.0);
///
/// // Convert to general interval enum
/// let general: Interval<f64> = closed.clone().into();
///
/// // Convert to finite positive length category
/// let finite: IntervalFinitePositiveLength<f64> = closed.into();
/// ```
///
/// ## Mathematical Examples
///
/// ### Unit Interval
/// ```rust
/// use grid1d::intervals::*;
///
/// let unit = IntervalClosed::new(0.0, 1.0); // [0., 1.]
/// ```
///
/// ### Symmetric Interval
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::{RealNative64StrictFinite, Constants};
///
/// let pi = RealNative64StrictFinite::pi();
///
/// let symmetric = IntervalClosed::new(-pi.clone(), pi); // [-π, π]
/// assert!(symmetric.is_symmetric());
/// ```
pub type IntervalClosed<RealType> = IntervalBounded<RealType, Closed, Closed>;

impl<RealType: RealScalar, LowerBoundType: BoundType, UpperBoundType: BoundType>
    IntervalBounded<RealType, LowerBoundType, UpperBoundType>
{
    /// Build and return a new instance of the interval from two `IntervalBound` objects.
    ///
    /// This constructor accepts pre-constructed [`LowerBound`] and [`UpperBound`] objects,
    /// allowing for more flexible interval construction when bounds are already available
    /// in their typed form.
    ///
    /// # Arguments
    ///
    /// - `lower_bound`: A [`LowerBound`] object representing the interval's lower boundary.
    /// - `upper_bound`: An [`UpperBound`] object representing the interval's upper boundary.
    ///
    /// # Errors
    ///
    /// Returns an error if the lower bound value is greater than or equal to the upper bound value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use grid1d::bounds::*;
    /// use try_create::New;
    ///
    /// // Create bounds separately
    /// let lower = LowerBoundClosed::new(0.0);
    /// let upper = UpperBoundClosed::new(1.0);
    ///
    /// // Construct interval from bounds
    /// let interval = IntervalClosed::try_from_static_bounds(lower, upper).unwrap();
    /// assert_eq!(interval.lower_bound_value(), &0.0);
    /// assert_eq!(interval.upper_bound_value(), &1.0);
    /// ```
    ///
    /// ```rust
    /// use grid1d::{*, intervals::*, bounds::*};
    /// use try_create::New;
    ///
    /// // Create half-open interval [0, 1) from bounds
    /// let lower = LowerBoundClosed::new(0.0);
    /// let upper = UpperBoundOpen::new(1.0);
    ///
    /// let interval = IntervalLowerClosedUpperOpen::try_from_static_bounds(lower, upper).unwrap();
    /// assert!(interval.contains_point(&0.0));  // Lower bound included
    /// assert!(!interval.contains_point(&1.0)); // Upper bound excluded
    /// ```
    ///
    /// # Type Safety
    ///
    /// This method maintains type safety by requiring that the bound types match the interval's
    /// generic parameters. For example, an [`IntervalClosed`] requires both bounds to be closed:
    ///
    /// ```compile_fail
    /// use grid1d::{*, bounds::*, intervals::*};
    /// use try_create::New;
    ///
    /// let lower = LowerBoundClosed::new(0.0);
    /// let upper = UpperBoundOpen::new(1.0);  // Wrong type!
    ///
    /// // This will not compile because IntervalClosed expects closed bounds
    /// let interval = IntervalClosed::try_from_static_bounds(lower, upper);
    /// ```
    pub fn try_from_static_bounds(
        lower_bound: LowerBound<RealType, LowerBoundType>,
        upper_bound: UpperBound<RealType, UpperBoundType>,
    ) -> Result<Self, ErrorsIntervalConstruction<RealType>> {
        if lower_bound.as_ref() < upper_bound.as_ref() {
            Ok(Self {
                lower_bound,
                upper_bound,
            })
        } else {
            Err(
                ErrorsIntervalConstruction::LowerBoundGreaterOrEqualThanUpperBound {
                    lower_bound: lower_bound.as_ref().clone(),
                    upper_bound: upper_bound.as_ref().clone(),
                    backtrace: capture_backtrace(),
                },
            )
        }
    }

    /// Build and return a new instance of the interval from two `IntervalBound` objects.
    ///
    /// This is the infallible version of [`Self::try_new`]. It constructs an interval
    /// from pre-existing bound objects without validation.
    ///
    /// # Arguments
    ///
    /// - `lower_bound`: A [`LowerBound`] object representing the interval's lower boundary.
    /// - `upper_bound`: An [`UpperBound`] object representing the interval's upper boundary.
    ///
    /// # Panics
    ///
    /// In debug mode, this function internally calls [`Self::try_new`] and will panic
    /// if that method returns an error. In release mode, the interval is constructed without
    /// any validation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use grid1d::intervals::*;
    /// use grid1d::bounds::*;
    /// use try_create::New;
    ///
    /// let lower = LowerBoundOpen::new(0.0);
    /// let upper = UpperBoundOpen::new(1.0);
    ///
    /// let interval = IntervalOpen::from_static_bounds(lower, upper);
    /// assert!(!interval.contains_point(&0.0)); // Both bounds excluded
    /// assert!(!interval.contains_point(&1.0));
    /// assert!(interval.contains_point(&0.5));  // Interior point included
    /// ```
    #[inline(always)]
    pub fn from_static_bounds(
        lower_bound: LowerBound<RealType, LowerBoundType>,
        upper_bound: UpperBound<RealType, UpperBoundType>,
    ) -> Self {
        #[cfg(debug_assertions)]
        {
            Self::try_from_static_bounds(lower_bound, upper_bound)
                .expect("Invalid interval bounds!")
        }
        #[cfg(not(debug_assertions))]
        {
            Self {
                lower_bound,
                upper_bound,
            }
        }
    }
}

impl<RealType: RealScalar, LowerBoundType: BoundType, UpperBoundType: BoundType> IntervalOperations
    for IntervalBounded<RealType, LowerBoundType, UpperBoundType>
where
    Self: IntervalBoundsRuntime<RealType = RealType>,
    LowerBound<RealType, LowerBoundType>: ValueWithinBound<RealType = RealType>,
    UpperBound<RealType, UpperBoundType>: ValueWithinBound<RealType = RealType>,
{
}

impl<RealType: RealScalar, LowerBoundType: BoundType, UpperBoundType: BoundType> Contains
    for IntervalBounded<RealType, LowerBoundType, UpperBoundType>
where
    Self: IntervalBoundsRuntime<RealType = RealType>,
    LowerBound<RealType, LowerBoundType>: ValueWithinBound<RealType = RealType>,
    UpperBound<RealType, UpperBoundType>: ValueWithinBound<RealType = RealType>,
{
    #[inline(always)]
    fn contains_point(&self, x: &RealType) -> bool {
        self.lower_bound.value_within_bound(x) && self.upper_bound.value_within_bound(x)
    }
}

//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
///  An open interval `(a, b)` where both endpoints are excluded.
///
/// The [`IntervalOpen`] represents intervals where neither the lower bound `a` nor
/// the upper bound `b` are part of the interval. Every real number `x` satisfying
/// `a < x < b` belongs to this interval, but the boundary points themselves are excluded.
///
/// ## Mathematical Properties
///
/// - **Notation**: `(a, b)`
/// - **Definition**: `{x ∈ ℝ : a < x < b}`
/// - **Endpoints**: Both excluded
/// - **Topology**: Open set in the real line topology
/// - **Compactness**: Never compact (open sets are not compact)
/// - **Connectedness**: Always connected (no gaps)
/// - **Supremum/Infimum**: `sup = b` and `inf = a` (exist but not achieved)
///
/// ## Use Cases
///
/// Open intervals are ideal when:
/// - You need to exclude boundary values (e.g., `(0, 1)` for strict inequalities)
/// - Working with limit domains where endpoints represent asymptotic behavior
/// - Defining convergence regions where the limit points are approached but not reached
/// - Modeling strict constraints in optimization problems
/// - Representing neighborhoods in topological analysis
///
/// ## Comparison with Other Interval Types
///
/// | Property | Open `(a,b)` | Closed `[a,b]` | Half-open `[a,b)` |
/// |----------|--------------|----------------|-------------------|
/// | Contains `a` | ✗ | ✓ | ✓ |
/// | Contains `b` | ✗ | ✓ | ✗ |
/// | Length | `b - a` | `b - a` | `b - a` |
/// | Compactness | Never | Always | Never |
/// | Supremum | `b` (not achieved) | `b` (achieved) | `b` (not achieved) |
/// | Infimum | `a` (not achieved) | `a` (achieved) | `a` (achieved) |
/// | Closure | `[a, b]` | `[a, b]` | `[a, b]` |
/// | Interior | `(a, b)` | `(a, b)` | `(a, b)` |
///
/// ## Construction
///
/// ### Safe Construction (Recommended)
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// // Use the recommended performance-optimal type
/// type Real = RealNative64StrictFiniteInDebug;
///
/// // Fallible construction (returns Result)
/// let result = IntervalOpen::try_new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// let interval = result.unwrap();
///
/// // Infallible construction (panics in debug mode if invalid)
/// let interval = IntervalOpen::new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// ```
///
/// ### Raw Construction (Use with Caution)
/// ```rust
/// use grid1d::intervals::*;
///
/// // Direct construction with raw f64 - only when you trust your data
/// let interval = IntervalOpen::new(0.0, 1.0);
/// ```
///
/// ## Key Operations
///
/// ### Point Containment (Excludes Endpoints)
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalOpen::new(-1.0, 1.0);
///
/// // Boundary points are excluded
/// assert!(!interval.contains_point(&-1.0));  // Lower bound excluded
/// assert!(!interval.contains_point(&1.0));   // Upper bound excluded
///
/// // Interior points are included
/// assert!(interval.contains_point(&0.0));    // Interior point
/// assert!(interval.contains_point(&-0.5));   // Interior point
/// assert!(interval.contains_point(&0.999));  // Close to boundary but inside
///
/// // Points outside the interval
/// assert!(!interval.contains_point(&-2.0));  // Below interval
/// assert!(!interval.contains_point(&2.0));   // Above interval
/// ```
///
/// ### Geometric Properties
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalOpen::new(-2.0, 3.0);
///
/// // Length is the same as for closed intervals
/// assert_eq!(interval.length().into_inner(), 5.0);           // |b - a| = |3 - (-2)| = 5
/// assert_eq!(interval.midpoint(), 0.5);        // (a + b) / 2 = (-2 + 3) / 2 = 0.5
/// assert!(!interval.is_symmetric());            // a + b ≠ 0
///
/// // Bounds access
/// assert_eq!(interval.lower_bound_value(), &-2.0);
/// assert_eq!(interval.upper_bound_value(), &3.0);
///
/// // Consume to get bounds
/// let (lower, upper) = interval.into_bounds_pair();
/// assert_eq!((lower, upper), (-2.0, 3.0));
/// ```
///
/// ### Interval Containment Testing
/// ```rust
/// use grid1d::intervals::*;
///
/// let outer_open = IntervalOpen::new(0.0, 3.0);
/// let inner_open = IntervalOpen::new(0.5, 2.5);
/// let inner_closed = IntervalClosed::new(0.5, 2.5);
/// let boundary_closed = IntervalClosed::new(0.0, 3.0);
///
/// // Open intervals can contain smaller open intervals
/// assert!(outer_open.contains_interval(&inner_open));     // (0,3) ⊇ (0.5,2.5) ✓
///
/// // Open intervals can contain closed intervals (if boundaries don't touch)
/// assert!(outer_open.contains_interval(&inner_closed));   // (0,3) ⊇ [0.5,2.5] ✓
///
/// // Open intervals cannot contain intervals that include their excluded boundaries
/// assert!(!outer_open.contains_interval(&boundary_closed)); // (0,3) ⊉ [0,3] ✗
/// assert!(!inner_closed.contains_interval(&outer_open));    // [0.5,2.5] ⊉ (0,3) ✗
/// ```
///
/// ## Intersection Examples
///
/// ### Open with Open
/// ```rust
/// use grid1d::intervals::*;
///
/// let a = IntervalOpen::new(0.0, 3.0);    // (0, 3)
/// let b = IntervalOpen::new(1.0, 4.0);    // (1, 4)
///
/// if let Some(intersection) = a.intersection(&b) {
///     // Result: (1, 3) - intersection preserves open boundaries
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::PositiveLength(
///             IntervalFinitePositiveLength::Open(open_interval)
///         )) => {
///             assert_eq!(open_interval.lower_bound_value(), &1.0);
///             assert_eq!(open_interval.upper_bound_value(), &3.0);
///             assert_eq!(open_interval.length().into_inner(), 2.0);
///         }
///         _ => unreachable!("Expected open interval"),
///     }
/// }
/// ```
///
/// ### Open with Closed
/// ```rust
/// use grid1d::intervals::*;
///
/// let open = IntervalOpen::new(0.0, 3.0);      // (0, 3)
/// let closed = IntervalClosed::new(1.0, 4.0);  // [1, 4]
///
/// if let Some(intersection) = open.intersection(&closed) {
///     // Result: [1, 3) - takes most restrictive boundary combination
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::PositiveLength(
///             IntervalFinitePositiveLength::LowerClosedUpperOpen(half_open)
///         )) => {
///             assert_eq!(half_open.lower_bound_value(), &1.0);  // Closed from [1,4]
///             assert_eq!(half_open.upper_bound_value(), &3.0);  // Open from (0,3)
///         }
///         _ => unreachable!("Expected half-open interval"),
///     }
/// }
/// ```
///
/// ### Edge Cases: Touching Boundaries
/// ```rust
/// use grid1d::intervals::*;
///
/// let left_open = IntervalOpen::new(0.0, 2.0);   // (0, 2)
/// let right_open = IntervalOpen::new(2.0, 4.0);  // (2, 4)
///
/// // Open intervals that meet at a point have no intersection
/// assert!(left_open.intersection(&right_open).is_none()); // No overlap at excluded point 2
///
/// let left_open = IntervalOpen::new(0.0, 2.0);     // (0, 2)
/// let right_closed = IntervalClosed::new(2.0, 4.0); // [2, 4]
///
/// // Open and closed intervals meeting at boundary also have no intersection
/// assert!(left_open.intersection(&right_closed).is_none()); // Point 2 excluded from (0,2)
/// ```
///
/// ## Advanced Usage Patterns
///
/// ### Generic Programming with Different Scalar Types
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::{RealScalar, RealNative64StrictFinite};
/// use try_create::TryNew;
///
/// // Generic function works with any RealScalar type
/// fn analyze_open_interval<T: RealScalar + std::fmt::Display>(
///     interval: &IntervalOpen<T>
/// ) -> String {
///     format!(
///         "Open interval ({}, {}) with length {} and midpoint {}",
///         interval.lower_bound_value(),
///         interval.upper_bound_value(),
///         interval.length(),
///         interval.midpoint()
///     )
/// }
///
/// // Works with validated types
/// let safe_interval = IntervalOpen::new(
///     RealNative64StrictFinite::try_new(0.0).unwrap(),
///     RealNative64StrictFinite::try_new(1.0).unwrap()
/// );
/// println!("{}", analyze_open_interval(&safe_interval));
///
/// // Also works with raw f64
/// let raw_interval = IntervalOpen::new(0.0, 1.0);
/// println!("{}", analyze_open_interval(&raw_interval));
/// ```
///
/// ### Conversion to Other Interval Types
/// ```rust
/// use grid1d::intervals::*;
///
/// let open = IntervalOpen::new(0.0, 1.0);
///
/// // Convert to category enums
/// let finite_positive: IntervalFinitePositiveLength<f64> = open.clone().into();
/// let finite: IntervalFiniteLength<f64> = open.clone().into();
/// let general: Interval<f64> = open.into();
///
/// // Pattern match on the general enum
/// match general {
///     Interval::FiniteLength(IntervalFiniteLength::PositiveLength(
///         IntervalFinitePositiveLength::Open(recovered_open)
///     )) => {
///         assert_eq!(recovered_open.lower_bound_value(), &0.0);
///         assert_eq!(recovered_open.upper_bound_value(), &1.0);
///     }
///     _ => unreachable!("Should be open interval"),
/// }
/// ```
///
/// ## Mathematical Applications
///
/// ### Limit Analysis and Convergence
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Model a convergence neighborhood around a limit point
/// struct ConvergenceNeighborhood {
///     /// Punctured neighborhood: points near the limit but excluding the limit itself
///     neighborhood: IntervalOpen<f64>,
///     limit_point: f64,
/// }
///
/// impl ConvergenceNeighborhood {
///     fn new(limit_point: f64, epsilon: f64) -> Self {
///         Self {
///             neighborhood: IntervalOpen::new(
///                 limit_point - epsilon,
///                 limit_point + epsilon
///             ),
///             limit_point,
///         }
///     }
///     
///     /// Check if a point is in the punctured neighborhood
///     fn is_in_neighborhood(&self, x: f64) -> bool {
///         self.neighborhood.contains_point(&x) && x != self.limit_point
///     }
///     
///     /// Get the epsilon (half-width) of the neighborhood
///     fn epsilon(&self) -> f64 {
///         self.neighborhood.length().into_inner() / 2.0
///     }
/// }
///
/// let neighborhood = ConvergenceNeighborhood::new(2.0, 0.1);
///
/// assert!(neighborhood.is_in_neighborhood(1.95));  // Close to limit
/// assert!(neighborhood.is_in_neighborhood(2.05));  // Close to limit
/// assert!(!neighborhood.is_in_neighborhood(2.0));  // Limit point excluded
/// assert!(!neighborhood.is_in_neighborhood(1.8));  // Outside neighborhood
/// ```
///
/// ### Optimization with Strict Constraints
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Optimization problem with strict inequality constraints
/// struct StrictConstraint {
///     feasible_region: IntervalOpen<f64>
/// }
///
/// impl StrictConstraint {
///     /// Create constraint: a < x < b
///     fn new_strict_bounds(lower: f64, upper: f64) -> Self {
///         Self {
///             feasible_region: IntervalOpen::new(lower, upper)
///         }
///     }
///     
///     /// Check if a point satisfies the strict constraint
///     fn is_feasible(&self, x: f64) -> bool {
///         self.feasible_region.contains_point(&x)
///     }
///     
///     /// Find interior point (useful for interior-point methods)
///     fn interior_point(&self) -> f64 {
///         self.feasible_region.midpoint()
///     }
///     
///     /// Get constraint violation (positive = infeasible)
///     fn violation(&self, x: f64) -> f64 {
///         let lower = *self.feasible_region.lower_bound_value();
///         let upper = *self.feasible_region.upper_bound_value();
///         
///         if x <= lower {
///             lower - x + f64::EPSILON  // Add small epsilon for strict inequality
///         } else if x >= upper {
///             x - upper + f64::EPSILON  // Add small epsilon for strict inequality
///         } else {
///             0.0  // Feasible
///         }
///     }
/// }
///
/// let constraint = StrictConstraint::new_strict_bounds(0.0, 1.0);  // 0 < x < 1
///
/// assert!(constraint.is_feasible(0.5));     // Interior point
/// assert!(!constraint.is_feasible(0.0));    // Boundary excluded
/// assert!(!constraint.is_feasible(1.0));    // Boundary excluded
/// assert!(!constraint.is_feasible(-0.1));   // Outside region
///
/// assert_eq!(constraint.interior_point(), 0.5);
/// assert!(constraint.violation(0.5) == 0.0);
/// assert!(constraint.violation(0.0) > 0.0);
/// assert!(constraint.violation(1.0) > 0.0);
/// ```
///
/// ### Numerical Integration (Special Handling Required)
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Integrate over open interval using transformation
/// fn integrate_over_open_interval(
///     f: impl Fn(f64) -> f64,
///     domain: &IntervalOpen<f64>,
///     num_points: usize
/// ) -> f64 {
///     let a = *domain.lower_bound_value();
///     let b = *domain.upper_bound_value();
///     
///     // Use Gauss-Legendre quadrature which naturally avoids endpoints
///     // Transform from [-1,1] to (a,b)
///     let transform = |t: f64| (a + b) / 2.0 + (b - a) / 2.0 * t;
///     let jacobian = (b - a) / 2.0;
///     
///     // Gauss-Legendre nodes and weights (simplified for 2 points)
///     let nodes = [-1.0 / f64::sqrt(3.0), 1.0 / f64::sqrt(3.0)];
///     let weights = [1.0, 1.0];
///     
///     let mut integral = 0.0;
///     for i in 0..nodes.len() {
///         let x = transform(nodes[i]);
///         integral += weights[i] * f(x);
///     }
///     
///     integral * jacobian
/// }
///
/// // Example: integrate x^2 over (0, 1)
/// let domain = IntervalOpen::new(0.0, 1.0);
/// let integral = integrate_over_open_interval(|x| x * x, &domain, 2);
///
/// // Should approximate ∫₀¹ x² dx = 1/3 ≈ 0.333...
/// // (Note: for open interval, the result is the same as for closed interval
/// //  since the boundary has measure zero)
/// assert!((integral - 1.0/3.0).abs() < 0.01);
/// ```
///
/// ## Performance Characteristics
///
/// ### Memory Layout
/// - **Storage**: Two scalar values plus boundary type information
/// - **Size**: Identical to [`IntervalClosed`] (typically 16-24 bytes for f64)
/// - **Alignment**: Natural alignment of the scalar type
/// - **No heap allocation**: All data stored inline
///
/// ### Operation Complexity
/// | Operation | Time Complexity | Notes |
/// |-----------|-----------------|-------|
/// | **Point queries** | O(1) | Two strict comparisons (`a < x < b`) |
/// | **Containment tests** | O(1) | Boundary logic comparison |
/// | **Intersections** | O(1) | Pure computation, may allocate result |
/// | **Geometric calculations** | O(1) | Length, midpoint, symmetry |
/// | **Construction** | O(1) | Single validation check in debug mode |
///
/// ### Comparison with Closed Intervals
/// ```rust
/// use grid1d::intervals::*;
///
/// // Both have identical computational complexity
/// let open = IntervalOpen::new(0.0, 1.0);
/// let closed = IntervalClosed::new(0.0, 1.0);
///
/// // Same geometric properties
/// assert_eq!(open.length(), closed.length());
/// assert_eq!(open.midpoint(), closed.midpoint());
/// assert_eq!(open.is_symmetric(), closed.is_symmetric());
///
/// // Different boundary behavior
/// assert!(!open.contains_point(&0.0));     // Open excludes boundaries
/// assert!(closed.contains_point(&0.0));    // Closed includes boundaries
///
/// // Same performance characteristics
/// let start = std::time::Instant::now();
/// for i in 0..1000000 {
///     let x = i as f64 / 1000000.0;
///     let _ = open.contains_point(&x);
/// }
/// let open_time = start.elapsed();
///
/// let start = std::time::Instant::now();
/// for i in 0..1000000 {
///     let x = i as f64 / 1000000.0;
///     let _ = closed.contains_point(&x);
/// }
/// let closed_time = start.elapsed();
///
/// // Performance should be virtually identical
/// // (The difference is just `<` vs `<=` comparisons)
/// ```
///
/// ## Error Handling and Edge Cases
///
/// ### Construction Validation
/// ```rust,ignore
/// use grid1d::intervals::*;
///
/// // Same validation as other interval types
/// assert!(IntervalOpen::try_new(1.0, 0.0).is_err());  // Invalid bounds
/// assert!(IntervalOpen::try_new(1.0, 1.0).is_err());  // Zero length
/// assert!(IntervalOpen::try_new(f64::NAN, 1.0).is_err()); // NaN bound
///
/// // Valid construction
/// assert!(IntervalOpen::try_new(0.0, 1.0).is_ok());
///
/// #[cfg(debug_assertions)]
/// {
///     // Panics in debug mode with invalid bounds
///     std::panic::catch_unwind(|| {
///         IntervalOpen::new(1.0, 0.0);
///     }).expect_err("Should panic on invalid bounds");
/// }
/// ```
///
/// ### Numerical Precision Considerations
/// ```rust
/// use grid1d::intervals::*;
///
/// // Very small open intervals
/// let tiny = IntervalOpen::new(1.0, 1.0 + f64::EPSILON);
/// let length = tiny.length().into_inner();
/// assert!(length > 0.0);
/// assert!(length < 1e-15);
/// assert_eq!(length, f64::EPSILON);
///
/// // Points very close to boundary
/// let interval = IntervalOpen::new(0.0, 1.0);
/// assert!(!interval.contains_point(&0.0));           // Exact boundary
/// assert!(interval.contains_point(&f64::EPSILON));   // Just inside
/// assert!(!interval.contains_point(&1.0));           // Exact boundary
/// assert!(interval.contains_point(&(1.0 - f64::EPSILON))); // Just inside
///
/// // Midpoint is always strictly inside
/// let midpoint = interval.midpoint();
/// assert!(interval.contains_point(&midpoint));
/// ```
///
/// ### Common Pitfalls and Solutions
/// ```rust
/// use grid1d::intervals::*;
///
/// // WRONG: Assuming open intervals behave like closed intervals at boundaries
/// fn naive_boundary_check(interval: &IntervalOpen<f64>) -> bool {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     // This is incorrect for open intervals!
///     interval.contains_point(&lower) && interval.contains_point(&upper)
/// }
///
/// // CORRECT: Understanding that open intervals exclude boundaries
/// fn correct_boundary_check(interval: &IntervalOpen<f64>) -> bool {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     // Open intervals never contain their boundaries
///     !interval.contains_point(&lower) && !interval.contains_point(&upper)
/// }
///
/// let open = IntervalOpen::new(0.0, 1.0);
/// assert!(!naive_boundary_check(&open));     // Always false for open intervals
/// assert!(correct_boundary_check(&open));    // Always true for open intervals
///
/// // WRONG: Trying to find points at the exact boundary
/// fn naive_sample_endpoints(interval: &IntervalOpen<f64>) -> Vec<f64> {
///     vec![
///         *interval.lower_bound_value(),  // Not in the interval!
///         *interval.upper_bound_value(),  // Not in the interval!
///     ]
/// }
///
/// // CORRECT: Sample points strictly inside the interval
/// fn correct_sample_interior(interval: &IntervalOpen<f64>, count: usize) -> Vec<f64> {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     let length = interval.length().into_inner();
///     
///     (0..count)
///         .map(|i| {
///             let t = (i + 1) as f64 / (count + 1) as f64;  // Avoid 0 and 1
///             lower + t * length
///         })
///         .collect()
/// }
///
/// let samples = correct_sample_interior(&open, 3);
/// for point in &samples {
///     assert!(open.contains_point(point));  // All points are valid
/// }
/// ```
///
/// ## Best Practices and Recommendations
///
/// ### When to Use [`IntervalOpen`]
/// - **Strict inequalities**: When boundary points must be excluded
/// - **Limit analysis**: For punctured neighborhoods and convergence studies
/// - **Optimization**: Interior-point methods and strict constraints
/// - **Topology**: When you need open sets for topological properties
/// - **Numerical analysis**: When boundary behavior is singular or undefined
///
/// ### When NOT to Use [`IntervalOpen`]
/// - **Integration bounds**: Usually want closed intervals for definite integrals
/// - **Physical measurements**: Real-world ranges typically include boundaries
/// - **Probability ranges**: Cumulative distributions usually include endpoints
/// - **Array indexing**: Discrete domains need inclusive bounds
///
/// ### Recommended Patterns
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// // Define type aliases for your application
/// type Real = RealNative64StrictFiniteInDebug;
/// type OpenInterval = IntervalOpen<Real>;
///
/// // Pattern: Always check containment instead of assuming boundary behavior
/// fn safe_evaluate_over_interval<F>(
///     f: F,
///     domain: &OpenInterval,
///     x: Real
/// ) -> Option<Real>
/// where
///     F: Fn(Real) -> Real,
/// {
///     if domain.contains_point(&x) {
///         Some(f(x))
///     } else {
///         None  // Point not in domain
///     }
/// }
///
/// // Pattern: Use midpoint for guaranteed interior point
/// fn get_safe_interior_point(interval: &OpenInterval) -> Real {
///     interval.midpoint()  // Always strictly inside for positive-length intervals
/// }
///
/// // Pattern: Convert to closed interval when you need inclusive boundaries
/// fn extend_to_closure(interval: OpenInterval) -> IntervalClosed<Real> {
///     let (lower, upper) = interval.into_bounds_pair();
///     IntervalClosed::new(lower, upper)
/// }
/// ```
///
/// ## Mathematical Correctness Guarantees
///
/// The [`IntervalOpen`] struct maintains all essential mathematical properties:
///
/// - **Open set property**: Never contains its boundary points
/// - **Connectedness**: Always connected (no gaps) for positive-length intervals  
/// - **Length invariance**: `length() = upper - lower` regardless of boundary type
/// - **Intersection correctness**: Results follow standard interval arithmetic
/// - **Containment transitivity**: If A ⊆ B and B ⊆ C, then A ⊆ C
/// - **Supremum/Infimum**: Upper and lower bounds are supremum and infimum respectively
/// - **Interior**: The interval equals its own interior
/// - **Closure**: The closure is the corresponding closed interval `[a, b]`
///
/// These properties are preserved regardless of the scalar type used and are guaranteed
/// by the underlying implementations of the [`IntervalTrait`] and [`IntervalFinitePositiveLengthTrait`].
pub type IntervalOpen<RealType> = IntervalBounded<RealType, Open, Open>;
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
///  A left half-open interval `(a, b]` where the lower endpoint is excluded and the upper endpoint is included.
///
/// The [`IntervalLowerOpenUpperClosed`] represents intervals of the form `(a, b]` where the lower bound `a`
/// is not part of the interval but the upper bound `b` is included. This type of interval is fundamental
/// in mathematical analysis, particularly for right-continuous functions, cumulative distribution functions,
/// and mathematical constructions where you need to exclude the starting point but include the ending point.
///
/// ## Mathematical Properties
///
/// - **Notation**: `(a, b]` or `]a, b]`
/// - **Definition**: `{x ∈ ℝ : a < x ≤ b}` where `a < b`
/// - **Lower boundary**: Excluded (open)
/// - **Upper boundary**: Included (closed)
/// - **Measure**: `|b - a|` (positive length)
/// - **Topology**: Neither open nor closed (half-open set)
/// - **Cardinality**: Uncountably infinite points
/// - **Compactness**: Never compact (not closed)
///
/// ## Use Cases
///
/// Left half-open intervals are ideal when:
/// - **Right-continuous functions**: Domains where functions are continuous from the right
/// - **Cumulative distributions**: CDF values where the upper bound represents an inclusive threshold
/// - **Interval unions**: Creating continuous coverage without overlaps when combined with `[a,b)` intervals
/// - **Limit processes**: Where the target value is achieved but the starting point represents a limit
/// - **Probability theory**: Events where the maximum value is included but minimum is approached
/// - **Numerical analysis**: Discretization schemes requiring upper boundary inclusion
///
/// ## Comparison with Other Interval Types
///
/// | Property | `(a,b]` | `[a,b]` | `(a,b)` | `[a,b)` |
/// |----------|---------|---------|---------|---------|
/// | Contains `a` | ✗ | ✓ | ✗ | ✓ |
/// | Contains `b` | ✓ | ✓ | ✗ | ✗ |
/// | Length | `b - a` | `b - a` | `b - a` | `b - a` |
/// | Compactness | Never | Always | Never | Never |
/// | Supremum | `b` (achieved) | `b` (achieved) | `b` (not achieved) | `b` (not achieved) |
/// | Infimum | `a` (not achieved) | `a` (achieved) | `a` (not achieved) | `a` (achieved) |
/// | Closure | `[a, b]` | `[a, b]` | `[a, b]` | `[a, b]` |
/// | Interior | `(a, b)` | `(a, b)` | `(a, b)` | `(a, b)` |
///
/// ## Construction
///
/// ### Safe Construction (Recommended)
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// // Use the recommended performance-optimal type
/// type Real = RealNative64StrictFiniteInDebug;
///
/// // Fallible construction (returns Result)
/// let result = IntervalLowerOpenUpperClosed::try_new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// let interval = result.unwrap();
///
/// // Infallible construction (panics in debug mode if invalid)
/// let interval = IntervalLowerOpenUpperClosed::new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// ```
///
/// ### Raw Construction (Use with Caution)
/// ```rust
/// use grid1d::intervals::*;
///
/// // Direct construction with raw f64 - only when you trust your data
/// let interval = IntervalLowerOpenUpperClosed::new(0.0, 1.0);
/// ```
///
/// ## Key Operations
///
/// ### Point Containment (Lower Excluded, Upper Included)
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalLowerOpenUpperClosed::new(-1.0, 1.0);  // (-1, 1]
///
/// // Lower boundary is excluded
/// assert!(!interval.contains_point(&-1.0));  // Lower bound excluded
///
/// // Upper boundary is included
/// assert!(interval.contains_point(&1.0));    // Upper bound included
///
/// // Interior points are included
/// assert!(interval.contains_point(&0.0));    // Interior point
/// assert!(interval.contains_point(&0.5));    // Interior point
/// assert!(interval.contains_point(&0.999));  // Close to upper boundary but inside
///
/// // Points outside the interval
/// assert!(!interval.contains_point(&-2.0));  // Below interval
/// assert!(!interval.contains_point(&2.0));   // Above interval
/// ```
///
/// ### Geometric Properties
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalLowerOpenUpperClosed::new(-2.0, 3.0);
///
/// // Length is the same as for other interval types
/// assert_eq!(interval.length().into_inner(), 5.0);           // |b - a| = |3 - (-2)| = 5
/// assert_eq!(interval.midpoint(), 0.5);        // (a + b) / 2 = (-2 + 3) / 2 = 0.5
/// assert!(!interval.is_symmetric());            // a + b ≠ 0
///
/// // Bounds access
/// assert_eq!(interval.lower_bound_value(), &-2.0);
/// assert_eq!(interval.upper_bound_value(), &3.0);
///
/// // Consume to get bounds
/// let (lower, upper) = interval.into_bounds_pair();
/// assert_eq!((lower, upper), (-2.0, 3.0));
/// ```
///
/// ### Boundary Behavior Analysis
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalLowerOpenUpperClosed::new(0.0, 1.0);  // (0, 1]
///
/// // Test boundary inclusion
/// assert!(!interval.contains_point(&0.0));    // Lower: excluded
/// assert!(interval.contains_point(&1.0));     // Upper: included
///
/// // Test points near boundaries
/// assert!(interval.contains_point(&0.0001));  // Just above lower bound
/// assert!(interval.contains_point(&0.9999));  // Just below upper bound
/// assert!(!interval.contains_point(&-0.0001)); // Just below lower bound
/// assert!(!interval.contains_point(&1.0001));  // Just above upper bound
/// ```
///
/// ## Interval Containment and Set Operations
///
/// ### Containment Testing
/// ```rust
/// use grid1d::intervals::*;
///
/// let outer = IntervalLowerOpenUpperClosed::new(0.0, 3.0);  // (0, 3]
/// let inner = IntervalLowerOpenUpperClosed::new(0.5, 2.5);  // (0.5, 2.5]
/// let boundary = IntervalLowerOpenUpperClosed::new(1.0, 3.0); // (1, 3]
///
/// // Left half-open intervals can contain smaller left half-open intervals
/// assert!(outer.contains_interval(&inner));           // (0, 3] ⊇ (0.5, 2.5] ✓
/// assert!(outer.contains_interval(&boundary));        // (0, 3] ⊇ (1, 3] ✓
///
/// // Smaller intervals cannot contain larger ones
/// assert!(!inner.contains_interval(&outer));          // (0.5, 2.5] ⊉ (0, 3] ✗
/// assert!(!boundary.contains_interval(&outer));       // (1, 3] ⊉ (0, 3] ✗
///
/// // Cross-type containment
/// let closed = IntervalClosed::new(0.5, 2.5);               // [0.5, 2.5]
/// let open = IntervalOpen::new(0.5, 2.5);                   // (0.5, 2.5)
/// let other_half = IntervalLowerClosedUpperOpen::new(0.5, 2.5); // [0.5, 2.5)
///
/// assert!(outer.contains_interval(&closed));          // (0, 3] ⊇ [0.5, 2.5] ✓
/// assert!(outer.contains_interval(&open));            // (0, 3] ⊇ (0.5, 2.5) ✓
/// assert!(outer.contains_interval(&other_half));      // (0, 3] ⊇ [0.5, 2.5) ✓
/// ```
///
/// ## Intersection Examples
///
/// ### Left Half-Open with Left Half-Open
/// ```rust
/// use grid1d::intervals::*;
///
/// let a = IntervalLowerOpenUpperClosed::new(0.0, 3.0);  // (0, 3]
/// let b = IntervalLowerOpenUpperClosed::new(1.0, 4.0);  // (1, 4]
///
/// if let Some(intersection) = a.intersection(&b) {
///     // Result: (1, 3] - intersection preserves left half-open boundaries
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::PositiveLength(
///             IntervalFinitePositiveLength::LowerOpenUpperClosed(half_open)
///         )) => {
///             assert_eq!(half_open.lower_bound_value(), &1.0);
///             assert_eq!(half_open.upper_bound_value(), &3.0);
///             assert_eq!(half_open.length().into_inner(), 2.0);
///         }
///         _ => unreachable!("Expected left half-open interval"),
///     }
/// }
/// ```
///
/// ### Left Half-Open with Other Types
/// ```rust
/// use grid1d::intervals::*;
///
/// let half_open = IntervalLowerOpenUpperClosed::new(0.0, 3.0);  // (0, 3]
/// let closed = IntervalClosed::new(1.0, 4.0);                   // [1, 4]
/// let open = IntervalOpen::new(2.0, 5.0);                       // (2, 5)
/// let other_half = IntervalLowerClosedUpperOpen::new(1.5, 2.5); // [1.5, 2.5)
///
/// // Intersection of (0, 3] with [1, 4]
/// // Result: [1, 3]
/// let half_open_intersection_closed: IntervalClosed<_>
///     = half_open.intersection(&closed).unwrap().try_into().unwrap();
/// assert_eq!(half_open_intersection_closed.lower_bound_value(), &1.0); // Closed from [1, 4]
/// assert_eq!(half_open_intersection_closed.upper_bound_value(), &3.0); // Closed from (0, 3]
///
/// // Intersection of (0, 3] with (2, 5)
/// // Result: (2, 3]
/// let half_open_intersection_open: IntervalLowerOpenUpperClosed<_>
///     = half_open.intersection(&open).unwrap().try_into().unwrap();
/// assert_eq!(half_open_intersection_open.lower_bound_value(), &2.0); // Open from (2, 5)
/// assert_eq!(half_open_intersection_open.upper_bound_value(), &3.0); // Closed from (0, 3]
///
/// // Intersection of (0, 3] with [1.5, 2.5)
/// // Result: [1.5, 2.5)
/// let half_open_intersection_other_half: IntervalLowerClosedUpperOpen<_>
///     = half_open.intersection(&other_half).unwrap().try_into().unwrap();
/// assert_eq!(half_open_intersection_other_half.lower_bound_value(), &1.5); // Closed from [1.5, 2.5)
/// assert_eq!(half_open_intersection_other_half.upper_bound_value(), &2.5); // Open from [1.5, 2.5)
/// ```
///
/// ### Edge Cases: Touching Boundaries
/// ```rust
/// use grid1d::intervals::*;
///
/// let left = IntervalLowerClosedUpperOpen::new(0.0, 2.0);   // [0, 2)
/// let right = IntervalLowerOpenUpperClosed::new(2.0, 4.0);  // (2, 4]
///
/// // Intersection of [0, 2) with (2, 4]
/// // No intersection - gap at point 2
/// assert!(left.intersection(&right).is_none()); // No overlap
///
/// let left_closed = IntervalClosed::new(0.0, 2.0);                  // [0, 2]
/// let right_half = IntervalLowerOpenUpperClosed::new(2.0, 4.0);     // (2, 4]
///
/// // Intersection of [0, 2] with (2, 4]
/// // No intersection - only touching at excluded point 2
/// assert!(left_closed.intersection(&right_half).is_none()); // No overlap at excluded point 2
/// ```
///
/// ## Advanced Usage Patterns
///
/// ### Right-Continuous Function Domains
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Represents a right-continuous step function
/// struct RightContinuousFunction {
///     domain: IntervalLowerOpenUpperClosed<f64>,
///     value: f64,
/// }
///
/// impl RightContinuousFunction {
///     fn new(domain_start_exclusive: f64, domain_end_inclusive: f64, function_value: f64) -> Self {
///         Self {
///             domain: IntervalLowerOpenUpperClosed::new(domain_start_exclusive, domain_end_inclusive),
///             value: function_value,
///         }
///     }
///     
///     /// Evaluate the function at a point
///     fn evaluate(&self, x: f64) -> Option<f64> {
///         if self.domain.contains_point(&x) {
///             Some(self.value)
///         } else {
///             None
///         }
///     }
///     
///     /// Check if the function is defined at the right endpoint
///     fn is_right_continuous_at_endpoint(&self) -> bool {
///         let endpoint = *self.domain.upper_bound_value();
///         self.domain.contains_point(&endpoint)  // Should be true for (a,b]
///     }
///     
///     /// Get the domain bounds
///     fn domain_bounds(&self) -> (f64, f64) {
///         (*self.domain.lower_bound_value(), *self.domain.upper_bound_value())
///     }
/// }
///
/// /// Piecewise right-continuous function
/// struct PiecewiseRightContinuous {
///     pieces: Vec<RightContinuousFunction>
/// }
///
/// impl PiecewiseRightContinuous {
///     fn new(pieces: Vec<RightContinuousFunction>) -> Self {
///         Self { pieces }
///     }
///     
///     fn evaluate(&self, x: f64) -> Option<f64> {
///         for piece in &self.pieces {
///             if let Some(value) = piece.evaluate(x) {
///                 return Some(value);
///             }
///         }
///         None
///     }
/// }
///
/// let function = PiecewiseRightContinuous::new(vec![
///     RightContinuousFunction::new(0.0, 1.0, 2.0),    // f(x) = 2 for x ∈ (0, 1]
///     RightContinuousFunction::new(1.0, 2.0, 5.0),    // f(x) = 5 for x ∈ (1, 2]
///     RightContinuousFunction::new(2.0, 3.0, 1.0),    // f(x) = 1 for x ∈ (2, 3]
/// ]);
///
/// assert_eq!(function.evaluate(0.0), None);        // Not in domain
/// assert_eq!(function.evaluate(0.5), Some(2.0));   // In (0, 1]
/// assert_eq!(function.evaluate(1.0), Some(2.0));   // At right endpoint of (0, 1]
/// assert_eq!(function.evaluate(1.5), Some(5.0));   // In (1, 2]
/// assert_eq!(function.evaluate(2.0), Some(5.0));   // At right endpoint of (1, 2]
/// assert_eq!(function.evaluate(3.0), Some(1.0));   // At right endpoint of (2, 3]
/// ```
///
/// ### Numerical Integration with Right Endpoints
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Integrate a right-continuous function over (a,b] using right Riemann sums
/// fn integrate_right_continuous(
///     f: impl Fn(f64) -> f64,
///     domain: IntervalLowerOpenUpperClosed<f64>,
///     num_subdivisions: usize
/// ) -> f64 {
///     let start = *domain.lower_bound_value();
///     let end = *domain.upper_bound_value();
///     let step = domain.length().into_inner() / num_subdivisions as f64;
///     
///     let mut integral = 0.0;
///     
///     for i in 0..num_subdivisions {
///         // Use right endpoint for function evaluation (natural for right-continuous functions)
///         let sub_end = start + (i + 1) as f64 * step;
///         let subinterval_length = step;
///         
///         integral += f(sub_end) * subinterval_length;
///     }
///     
///     integral
/// }
///
/// // Example: integrate f(x) = x over (0, 2]
/// let domain = IntervalLowerOpenUpperClosed::new(0.0, 2.0);
/// let integral = integrate_right_continuous(|x| x, domain, 1000);
///
/// // Should approximate ∫₀² x dx = [x²/2]₀² = 2 (note: endpoint behavior doesn't affect continuous integrals significantly)
/// assert!((integral - 2.0).abs() < 0.01);
/// ```
///
/// ## Performance Characteristics
///
/// ### Memory Layout
/// - **Storage**: Two scalar values plus boundary type information
/// - **Size**: Identical to other bounded interval types (typically 16-24 bytes for f64)
/// - **Alignment**: Natural alignment of the scalar type
/// - **No heap allocation**: All data stored inline
///
/// ### Operation Complexity
/// | Operation | Time Complexity | Notes |
/// |-----------|-----------------|-------|
/// | **Point queries** | O(1) | Two comparisons: `a < x ≤ b` |
/// | **Containment tests** | O(1) | Boundary logic comparison |
/// | **Intersections** | O(1) | Pure computation, may allocate result |
/// | **Geometric calculations** | O(1) | Length, midpoint, symmetry |
/// | **Construction** | O(1) | Single validation check in debug mode |
///
/// ### Comparison with Other Interval Types
/// ```rust
/// use grid1d::intervals::*;
///
/// // All bounded interval types have identical computational complexity
/// let left_half_open = IntervalLowerOpenUpperClosed::new(0.0, 1.0);   // (0, 1]
/// let closed = IntervalClosed::new(0.0, 1.0);                         // [0, 1]
/// let open = IntervalOpen::new(0.0, 1.0);                             // (0, 1)
/// let right_half_open = IntervalLowerClosedUpperOpen::new(0.0, 1.0);  // [0, 1)
///
/// // Same geometric properties
/// assert_eq!(left_half_open.length(), closed.length());
/// assert_eq!(left_half_open.midpoint(), closed.midpoint());
/// assert_eq!(left_half_open.is_symmetric(), closed.is_symmetric());
///
/// // Different boundary behavior
/// assert!(!left_half_open.contains_point(&0.0));     // Excludes lower bound
/// assert!(left_half_open.contains_point(&1.0));      // Includes upper bound
/// assert!(closed.contains_point(&0.0));              // Includes both bounds
/// assert!(closed.contains_point(&1.0));              
/// assert!(!open.contains_point(&0.0));               // Excludes both bounds
/// assert!(!open.contains_point(&1.0));               
/// assert!(right_half_open.contains_point(&0.0));     // Includes lower bound
/// assert!(!right_half_open.contains_point(&1.0));    // Excludes upper bound
/// ```
///
/// ## Mathematical Correctness Guarantees
///
/// The [`IntervalLowerOpenUpperClosed`] struct maintains all essential mathematical properties:
///
/// - **Boundary semantics**: Lower bound always excluded, upper bound always included
/// - **Positive measure**: `length() = upper - lower > 0` for all valid instances
/// - **Set operations**: Containment and intersection follow standard interval arithmetic
/// - **Right-continuity**: Natural choice for right-continuous function domains
/// - **CDF compatibility**: Perfect fit for cumulative distribution step functions
/// - **Order preservation**: Respects the natural ordering of real numbers
/// - **Translation invariance**: Shifting preserves the half-open structure
///
/// These properties are preserved regardless of the scalar type used and are guaranteed
/// by the underlying implementations of the [`IntervalTrait`] and [`IntervalFinitePositiveLengthTrait`].
pub type IntervalLowerOpenUpperClosed<RealType> = IntervalBounded<RealType, Open, Closed>;
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
///  A right half-open interval `[a, b)` where the lower endpoint is included and the upper endpoint is excluded.
///
/// The [`IntervalLowerClosedUpperOpen`] represents intervals of the form `[a, b)` where the lower bound `a`
/// is part of the interval but the upper bound `b` is not included. This type of interval is fundamental
/// in mathematical analysis, particularly for partitions, left-continuous functions, and discrete-continuous
/// interfaces where you need to include the starting point but exclude the ending point.
///
/// ## Mathematical Properties
///
/// - **Notation**: `[a, b)` or `[a, b[`
/// - **Definition**: `{x ∈ ℝ : a ≤ x < b}` where `a < b`
/// - **Lower boundary**: Included (closed)
/// - **Upper boundary**: Excluded (open)
/// - **Measure**: `|b - a|` (positive length)
/// - **Topology**: Neither open nor closed (half-open set)
/// - **Cardinality**: Uncountably infinite points
/// - **Compactness**: Never compact (not closed)
///
/// ## Use Cases
///
/// Right half-open intervals are ideal when:
/// - **Array indexing**: Representing ranges like `[0, n)` for array indices
/// - **Left-continuous functions**: Domains where functions are continuous from the left
/// - **Interval partitions**: Non-overlapping subdivision of larger intervals
/// - **Time intervals**: Start time included, end time excluded (e.g., `[9:00, 10:00)`)
/// - **Discrete-continuous boundaries**: Transitioning from discrete to continuous domains
/// - **Cumulative processes**: Where the starting point is included but the endpoint represents a limit
///
/// ## Comparison with Other Interval Types
///
/// | Property | `[a,b)` | `[a,b]` | `(a,b)` | `(a,b]` |
/// |----------|---------|---------|---------|---------|
/// | Contains `a` | ✓ | ✓ | ✗ | ✗ |
/// | Contains `b` | ✗ | ✓ | ✗ | ✓ |
/// | Length | `b - a` | `b - a` | `b - a` | `b - a` |
/// | Compactness | Never | Always | Never | Never |
/// | Supremum | `b` (not achieved) | `b` (achieved) | `b` (not achieved) | `b` (achieved) |
/// | Infimum | `a` (achieved) | `a` (achieved) | `a` (not achieved) | `a` (not achieved) |
/// | Closure | `[a, b]` | `[a, b]` | `[a, b]` | `[a, b]` |
/// | Interior | `(a, b)` | `(a, b)` | `(a, b)` | `(a, b)` |
///
/// ## Construction
///
/// ### Safe Construction (Recommended)
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// // Use the recommended performance-optimal type
/// type Real = RealNative64StrictFiniteInDebug;
///
/// // Fallible construction (returns Result)
/// let result = IntervalLowerClosedUpperOpen::try_new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// let interval = result.unwrap();
///
/// // Infallible construction (panics in debug mode if invalid)
/// let interval = IntervalLowerClosedUpperOpen::new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// ```
///
/// ### Raw Construction (Use with Caution)
/// ```rust
/// use grid1d::intervals::*;
///
/// // Direct construction with raw f64 - only when you trust your data
/// let interval = IntervalLowerClosedUpperOpen::new(0.0, 1.0);
/// ```
///
/// ## Key Operations
///
/// ### Point Containment (Lower Included, Upper Excluded)
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalLowerClosedUpperOpen::new(-1.0, 1.0);  // [-1, 1)
///
/// // Lower boundary is included
/// assert!(interval.contains_point(&-1.0));   // Lower bound included
///
/// // Upper boundary is excluded
/// assert!(!interval.contains_point(&1.0));   // Upper bound excluded
///
/// // Interior points are included
/// assert!(interval.contains_point(&0.0));    // Interior point
/// assert!(interval.contains_point(&-0.5));   // Interior point
/// assert!(interval.contains_point(&0.999));  // Close to upper boundary but inside
///
/// // Points outside the interval
/// assert!(!interval.contains_point(&-2.0));  // Below interval
/// assert!(!interval.contains_point(&2.0));   // Above interval
/// ```
///
/// ### Geometric Properties
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalLowerClosedUpperOpen::new(-2.0, 3.0);
///
/// // Length is the same as for other interval types
/// assert_eq!(interval.length().into_inner(), 5.0);           // |b - a| = |3 - (-2)| = 5
/// assert_eq!(interval.midpoint(), 0.5);        // (a + b) / 2 = (-2 + 3) / 2 = 0.5
/// assert!(!interval.is_symmetric());            // a + b ≠ 0
///
/// // Bounds access
/// assert_eq!(interval.lower_bound_value(), &-2.0);
/// assert_eq!(interval.upper_bound_value(), &3.0);
///
/// // Consume to get bounds
/// let (lower, upper) = interval.into_bounds_pair();
/// assert_eq!((lower, upper), (-2.0, 3.0));
/// ```
///
/// ### Boundary Behavior Analysis
/// ```rust
/// use grid1d::intervals::*;
///
/// let interval = IntervalLowerClosedUpperOpen::new(0.0, 1.0);  // [0, 1)
///
/// // Test boundary inclusion
/// assert!(interval.contains_point(&0.0));     // Lower: included
/// assert!(!interval.contains_point(&1.0));    // Upper: excluded
///
/// // Test points near boundaries
/// assert!(interval.contains_point(&0.0001));  // Just above lower bound
/// assert!(interval.contains_point(&0.9999));  // Just below upper bound
/// assert!(!interval.contains_point(&-0.0001)); // Just below lower bound
/// assert!(!interval.contains_point(&1.0001));  // Just above upper bound
/// ```
///
/// ## Interval Containment and Set Operations
///
/// ### Containment Testing
/// ```rust
/// use grid1d::intervals::*;
///
/// let outer = IntervalLowerClosedUpperOpen::new(0.0, 3.0);  // [0, 3)
/// let inner = IntervalLowerClosedUpperOpen::new(0.5, 2.5);  // [0.5, 2.5)
/// let boundary = IntervalLowerClosedUpperOpen::new(0.0, 1.0); // [0, 1)
///
/// // Half-open intervals can contain smaller half-open intervals
/// assert!(outer.contains_interval(&inner));           // [0, 3) ⊇ [0.5, 2.5) ✓
/// assert!(outer.contains_interval(&boundary));        // [0, 3) ⊇ [0, 1) ✓
///
/// // Smaller intervals cannot contain larger ones
/// assert!(!inner.contains_interval(&outer));          // [0.5, 2.5) ⊉ [0, 3) ✗
/// assert!(!boundary.contains_interval(&outer));       // [0, 1) ⊉ [0, 3) ✗
///
/// // Cross-type containment
/// let closed = IntervalClosed::new(0.5, 2.0);           // [0.5, 2.0]
/// let open = IntervalOpen::new(0.5, 2.5);               // (0.5, 2.5)
/// let other_half = IntervalLowerOpenUpperClosed::new(0.5, 2.0); // (0.5, 2.0]
///
/// assert!(outer.contains_interval(&closed));          // [0, 3) ⊇ [0.5, 2.0] ✓
/// assert!(outer.contains_interval(&open));            // [0, 3) ⊇ (0.5, 2.5) ✓
/// assert!(outer.contains_interval(&other_half));      // [0, 3) ⊇ (0.5, 2.0] ✓
/// ```
///
/// ## Intersection Examples
///
/// ### Right Half-Open with Right Half-Open
/// ```rust
/// use grid1d::intervals::*;
///
/// let a = IntervalLowerClosedUpperOpen::new(0.0, 3.0);  // [0, 3)
/// let b = IntervalLowerClosedUpperOpen::new(1.0, 4.0);  // [1, 4)
///
/// if let Some(intersection) = a.intersection(&b) {
///     // Result: [1, 3) - intersection preserves right half-open boundaries
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::PositiveLength(
///             IntervalFinitePositiveLength::LowerClosedUpperOpen(half_open)
///         )) => {
///             assert_eq!(half_open.lower_bound_value(), &1.0);
///             assert_eq!(half_open.upper_bound_value(), &3.0);
///             assert_eq!(half_open.length().into_inner(), 2.0);
///         }
///         _ => unreachable!("Expected right half-open interval"),
///     }
/// }
/// ```
///
/// ### Right Half-Open with Other Types
/// ```rust
/// use grid1d::intervals::*;
///
/// let half_open = IntervalLowerClosedUpperOpen::new(0.0, 3.0);  // [0., 3.)
/// let closed = IntervalClosed::new(1.0, 4.0);                   // [1., 4.]
/// let open = IntervalOpen::new(2.0, 5.0);                       // (2., 5.)
/// let other_half = IntervalLowerOpenUpperClosed::new(1.5, 2.5); // (1.5, 2.5]
///
/// // Intersection of [0., 3.) with [1., 4.]
/// // Result: [1, 3)
/// let half_open_intersection_closed: IntervalLowerClosedUpperOpen<_>
///     = half_open.intersection(&closed).unwrap().try_into().unwrap();
/// assert_eq!(half_open_intersection_closed.lower_bound_value(), &1.0); // Closed from [1. ,4.]
/// assert_eq!(half_open_intersection_closed.upper_bound_value(), &3.0); // Open from [0., 3.)
///
/// // Intersection of [0., 3.) with (2., 5.)
/// // Result: (2, 3)
/// let half_open_intersection_open: IntervalOpen<_>
///     = half_open.intersection(&open).unwrap().try_into().unwrap();
/// assert_eq!(half_open_intersection_open.lower_bound_value(), &2.0); // Open from (2., 5.)
/// assert_eq!(half_open_intersection_open.upper_bound_value(), &3.0); // Open from [0., 3.]
///
/// // Intersection of [0., 3.) with (1.5, 2.5]
/// // Result: (1.5, 2.5]
/// let half_open_intersection_other_half: IntervalLowerOpenUpperClosed<_>
///     = half_open.intersection(&other_half).unwrap().try_into().unwrap();
/// assert_eq!(half_open_intersection_other_half.lower_bound_value(), &1.5); // Open from (1.5, 2.5]
/// assert_eq!(half_open_intersection_other_half.upper_bound_value(), &2.5); // Closed from (1.5, 2.5]
/// ```
///
/// ### Edge Cases: Touching Boundaries
/// ```rust
/// use grid1d::intervals::*;
///
/// let left = IntervalLowerOpenUpperClosed::new(0.0, 2.0);   // (0., 2.]
/// let right = IntervalLowerClosedUpperOpen::new(2.0, 4.0);  // [2., 4.)
///
/// /// // Intersection of (0., 2.] with [2., 4.]
/// // Result: [2.]
/// let singleton: IntervalSingleton<_>
///     = left.intersection(&right).unwrap().try_into().unwrap();
/// assert_eq!(singleton.value(), &2.0);
///
///
/// let left_open = IntervalOpen::new(0.0, 2.0);                  // (0., 2.)
/// let right_half = IntervalLowerClosedUpperOpen::new(2.0, 4.0); // [2., 4.)
///
/// // Open and right half-open meeting at boundary
/// assert!(left_open.intersection(&right_half).is_none()); // No overlap at excluded point 2
/// ```
///
/// ## Advanced Usage Patterns
///
///
/// ### Time Intervals and Scheduling
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Represents a time interval where start time is included but end time is excluded
/// #[derive(Debug)]
/// struct TimeSlot {
///     interval: IntervalLowerClosedUpperOpen<f64>  // Time in hours
/// }
///
/// impl TimeSlot {
///     fn new(start_hour: f64, end_hour: f64) -> Self {
///         Self {
///             interval: IntervalLowerClosedUpperOpen::new(start_hour, end_hour)
///         }
///     }
///     
///     /// Check if a specific time falls within this slot
///     fn contains_time(&self, time: f64) -> bool {
///         self.interval.contains_point(&time)
///     }
///     
///     /// Get duration in hours
///     fn duration(&self) -> f64 {
///         self.interval.length().into_inner()
///     }
///     
///     /// Check if this slot overlaps with another
///     fn overlaps_with(&self, other: &TimeSlot) -> bool {
///         self.interval.intersection(&other.interval).is_some()
///     }
///     
///     /// Get the overlap duration with another slot
///     fn overlap_duration(&self, other: &TimeSlot) -> f64 {
///         if let Some(intersection) = self.interval.intersection(&other.interval) {
///             match intersection {
///                 Interval::FiniteLength(IntervalFiniteLength::PositiveLength(positive)) => {
///                     positive.length().into_inner()
///                 }
///                 Interval::FiniteLength(IntervalFiniteLength::ZeroLength(_)) => 0.0,
///                 _ => 0.0,
///             }
///         } else {
///             0.0
///         }
///     }
/// }
///
/// let meeting1 = TimeSlot::new(9.0, 10.5);   // 9:00 to 10:30
/// let meeting2 = TimeSlot::new(10.0, 11.0);  // 10:00 to 11:00
/// let meeting3 = TimeSlot::new(10.5, 12.0);  // 10:30 to 12:00
///
/// assert!(meeting1.contains_time(9.0));      // Start time included
/// assert!(meeting1.contains_time(10.25));    // Time during meeting
/// assert!(!meeting1.contains_time(10.5));    // End time excluded
///
/// assert_eq!(meeting1.duration(), 1.5);      // 1.5 hours
/// assert_eq!(meeting2.duration(), 1.0);      // 1 hour
///
/// assert!(meeting1.overlaps_with(&meeting2)); // 9:00-10:30 overlaps 10:00-11:00
/// assert!(!meeting1.overlaps_with(&meeting3)); // 9:00-10:30 doesn't overlap 10:30-12:00 (boundary)
/// assert_eq!(meeting1.overlap_duration(&meeting2), 0.5); // 30 minutes overlap
/// ```
///
/// ### Interval Partitions and Subdivisions
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Create a partition of an interval into right half-open subintervals
/// fn create_partition(
///     start: f64,
///     end: f64,
///     num_parts: usize
/// ) -> Vec<IntervalLowerClosedUpperOpen<f64>> {
///     if num_parts == 0 {
///         return Vec::new();
///     }
///     
///     let step = (end - start) / num_parts as f64;
///     (0..num_parts)
///         .map(|i| {
///             let part_start = start + i as f64 * step;
///             let part_end = start + (i + 1) as f64 * step;
///             IntervalLowerClosedUpperOpen::new(part_start, part_end)
///         })
///         .collect()
/// }
///
/// /// Verify that a partition covers the original interval exactly
/// fn verify_partition_coverage(
///     original_start: f64,
///     original_end: f64,
///     partition: &[IntervalLowerClosedUpperOpen<f64>]
/// ) -> bool {
///     if partition.is_empty() {
///         return false;
///     }
///     
///     // Check that first interval starts at original start
///     if *partition[0].lower_bound_value() != original_start {
///         return false;
///     }
///     
///     // Check that last interval ends at original end
///     if *partition.last().unwrap().upper_bound_value() != original_end {
///         return false;
///     }
///     
///     // Check continuity: each interval starts where previous ends
///     for i in 1..partition.len() {
///         if *partition[i].lower_bound_value() != *partition[i-1].upper_bound_value() {
///             return false;
///         }
///     }
///     
///     // Check no overlaps (except at boundaries)
///     for i in 0..partition.len()-1 {
///         for j in i+1..partition.len() {
///             if let Some(intersection) = partition[i].intersection(&partition[j]) {
///                 // Only allow zero-length (singleton) intersections at boundaries
///                 match intersection {
///                     Interval::FiniteLength(IntervalFiniteLength::ZeroLength(_)) => continue,
///                     _ => return false,
///                 }
///             }
///         }
///     }
///     
///     true
/// }
///
/// let partition = create_partition(0.0, 10.0, 4);
/// assert_eq!(partition.len(), 4);
///
/// // Verify each part: [0,2.5), [2.5,5), [5,7.5), [7.5,10)
/// assert_eq!(partition[0].lower_bound_value(), &0.0);
/// assert_eq!(partition[0].upper_bound_value(), &2.5);
/// assert_eq!(partition[1].lower_bound_value(), &2.5);
/// assert_eq!(partition[1].upper_bound_value(), &5.0);
/// assert_eq!(partition[2].lower_bound_value(), &5.0);
/// assert_eq!(partition[2].upper_bound_value(), &7.5);
/// assert_eq!(partition[3].lower_bound_value(), &7.5);
/// assert_eq!(partition[3].upper_bound_value(), &10.0);
///
/// assert!(verify_partition_coverage(0.0, 10.0, &partition));
///
/// // Test point coverage - every point in [0,10) should be in exactly one partition interval
/// for test_point in [0.0, 1.0, 2.5, 4.0, 5.0, 7.5, 9.0] {
///     let containing_intervals: Vec<_> = partition.iter()
///         .enumerate()
///         .filter(|(_, interval)| interval.contains_point(&test_point))
///         .collect();
///     
///     assert_eq!(containing_intervals.len(), 1,
///                "Point {} should be in exactly one interval", test_point);
/// }
/// ```
///
/// ### Numerical Integration with Uniform Partitions
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Integrate a function over [a,b) using rectangular rule with right half-open subintervals
/// fn integrate_with_right_half_open_partition(
///     f: impl Fn(f64) -> f64,
///     domain: IntervalLowerClosedUpperOpen<f64>,
///     num_subdivisions: usize
/// ) -> f64 {
///     let start = *domain.lower_bound_value();
///     let end = *domain.upper_bound_value();
///     let step = domain.length().into_inner() / num_subdivisions as f64;
///     
///     let mut integral = 0.0;
///     
///     for i in 0..num_subdivisions {
///         let sub_start = start + i as f64 * step;
///         let sub_end = start + (i + 1) as f64 * step;
///         let subinterval = IntervalLowerClosedUpperOpen::new(sub_start, sub_end);
///         
///         // Use left endpoint for function evaluation (since it's included in [a,b))
///         let sample_point = *subinterval.lower_bound_value();
///         integral += f(sample_point) * subinterval.length().into_inner();
///     }
///     
///     integral
/// }
///
/// // Example: integrate f(x) = x² over [0, 3)
/// let domain = IntervalLowerClosedUpperOpen::new(0.0, 3.0);
/// let integral = integrate_with_right_half_open_partition(|x| x * x, domain, 1000);
///
/// // Should approximate ∫₀³ x² dx = [x³/3]₀³ = 9 (note: upper bound excluded doesn't affect continuous integrals significantly)
/// assert!((integral - 9.0).abs() < 0.1);
/// ```
///
/// ## Performance Characteristics
///
/// ### Memory Layout
/// - **Storage**: Two scalar values plus boundary type information
/// - **Size**: Identical to other bounded interval types (typically 16-24 bytes for f64)
/// - **Alignment**: Natural alignment of the scalar type
/// - **No heap allocation**: All data stored inline
///
/// ### Operation Complexity
/// | Operation | Time Complexity | Notes |
/// |-----------|-----------------|-------|
/// | **Point queries** | O(1) | Two comparisons: `a ≤ x < b` |
/// | **Containment tests** | O(1) | Boundary logic comparison |
/// | **Intersections** | O(1) | Pure computation, may allocate result |
/// | **Geometric calculations** | O(1) | Length, midpoint, symmetry |
/// | **Construction** | O(1) | Single validation check in debug mode |
///
/// ### Comparison with Other Interval Types
/// ```rust
/// use grid1d::intervals::*;
///
/// // All bounded interval types have identical computational complexity
/// let right_half_open = IntervalLowerClosedUpperOpen::new(0.0, 1.0);  // [0, 1)
/// let closed = IntervalClosed::new(0.0, 1.0);                         // [0, 1]
/// let open = IntervalOpen::new(0.0, 1.0);                             // (0, 1)
/// let left_half_open = IntervalLowerOpenUpperClosed::new(0.0, 1.0);   // (0, 1]
///
/// // Same geometric properties
/// assert_eq!(right_half_open.length(), closed.length());
/// assert_eq!(right_half_open.midpoint(), closed.midpoint());
/// assert_eq!(right_half_open.is_symmetric(), closed.is_symmetric());
///
/// // Different boundary behavior
/// assert!(right_half_open.contains_point(&0.0));     // Includes lower bound
/// assert!(!right_half_open.contains_point(&1.0));    // Excludes upper bound
/// assert!(closed.contains_point(&0.0));              // Includes both bounds
/// assert!(closed.contains_point(&1.0));              
/// assert!(!open.contains_point(&0.0));               // Excludes both bounds
/// assert!(!open.contains_point(&1.0));               
/// assert!(!left_half_open.contains_point(&0.0));     // Excludes lower bound
/// assert!(left_half_open.contains_point(&1.0));      // Includes upper bound
/// ```
///
/// ## Error Handling and Edge Cases
///
/// ### Construction Validation
/// ```rust,ignore
/// use grid1d::intervals::*;
///
/// // Valid construction
/// assert!(IntervalLowerClosedUpperOpen::try_new(0.0, 1.0).is_ok());
///
/// // Invalid construction
/// assert!(IntervalLowerClosedUpperOpen::try_new(1.0, 0.0).is_err());  // Inverted bounds
/// assert!(IntervalLowerClosedUpperOpen::try_new(1.0, 1.0).is_err());  // Zero length
/// assert!(IntervalLowerClosedUpperOpen::try_new(f64::NAN, 1.0).is_err()); // NaN bound
///
/// #[cfg(debug_assertions)]
/// {
///     // Panics in debug mode with invalid bounds
///     std::panic::catch_unwind(|| {
///         IntervalLowerClosedUpperOpen::new(1.0, 0.0);
///     }).expect_err("Should panic on invalid bounds");
/// }
/// ```
///
/// ### Boundary Precision Considerations
/// ```rust
/// use grid1d::intervals::*;
///
/// // Very small intervals near floating-point precision limits
/// let tiny_interval = IntervalLowerClosedUpperOpen::new(1.0, 1.0 + f64::EPSILON);
/// assert!(tiny_interval.length().into_inner() > 0.0);
/// assert!(tiny_interval.length().into_inner() < 1e-15);
///
/// // Points very close to boundaries
/// let interval = IntervalLowerClosedUpperOpen::new(0.0, 1.0);
/// assert!(interval.contains_point(&0.0));                    // Exact lower boundary
/// assert!(interval.contains_point(&f64::EPSILON));           // Just above lower bound
/// assert!(!interval.contains_point(&1.0));                   // Exact upper boundary
/// assert!(interval.contains_point(&(1.0 - f64::EPSILON)));   // Just below upper bound
/// ```
///
/// ### Common Pitfalls and Solutions
/// ```rust
/// use grid1d::intervals::*;
///
/// // WRONG: Assuming both boundaries are included
/// fn naive_boundary_check(interval: &IntervalLowerClosedUpperOpen<f64>) -> (bool, bool) {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     // This gives wrong results for the upper bound!
///     (
///         interval.contains_point(&lower),  // Correct: returns true
///         interval.contains_point(&upper)   // Wrong assumption: returns false
///     )
/// }
///
/// // CORRECT: Understanding the boundary semantics
/// fn correct_boundary_check(interval: &IntervalLowerClosedUpperOpen<f64>) -> (bool, bool) {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     (
///         interval.contains_point(&lower),  // Should be true (closed lower bound)
///         interval.contains_point(&upper)   // Should be false (open upper bound)
///     )
/// }
///
/// let interval = IntervalLowerClosedUpperOpen::new(0.0, 1.0);
/// assert_eq!(naive_boundary_check(&interval), (true, false));   // Correct by accident
/// assert_eq!(correct_boundary_check(&interval), (true, false)); // Correct by design
///
/// // WRONG: Creating ranges that don't partition correctly
/// fn naive_create_adjacent_ranges(start: f64, middle: f64, end: f64) ->
///     (IntervalLowerClosedUpperOpen<f64>, IntervalLowerClosedUpperOpen<f64>) {
///     // This creates a gap at the middle point!
///     (
///         IntervalLowerClosedUpperOpen::new(start, middle),    // [start, middle)
///         IntervalLowerClosedUpperOpen::new(middle + 0.001, end) // [middle+ε, end) - GAP!
///     )
/// }
///
/// // CORRECT: Ensuring proper adjacency
/// fn correct_create_adjacent_ranges(start: f64, middle: f64, end: f64) ->
///     (IntervalLowerClosedUpperOpen<f64>, IntervalLowerClosedUpperOpen<f64>) {
///     (
///         IntervalLowerClosedUpperOpen::new(start, middle),  // [start, middle)
///         IntervalLowerClosedUpperOpen::new(middle, end)     // [middle, end) - NO GAP
///     )
/// }
///
/// let (left, right) = correct_create_adjacent_ranges(0.0, 5.0, 10.0);
/// // Verify no gap: right interval starts exactly where left interval ends
/// assert_eq!(left.upper_bound_value(), right.lower_bound_value());
/// // Verify no overlap: intersection should be at most a single point
/// if let Some(intersection) = left.intersection(&right) {
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::ZeroLength(_)) => {
///             // This is fine - single point intersection at boundary
///         }
///         _ => panic!("Should not have positive-length intersection"),
///     }
/// }
/// ```
///
/// ## Best Practices and Recommendations
///
/// ### When to Use [`IntervalLowerClosedUpperOpen`]
/// - **Array indexing**: Representing index ranges like `[start, end)`
/// - **Time intervals**: Start time included, end time excluded
/// - **Partitions**: Creating non-overlapping subdivisions
/// - **Left-continuous functions**: Domains where functions are continuous from the left
/// - **Iteration ranges**: Programming constructs like `for i in start..end`
/// - **Histogram bins**: Where lower bound is included, upper bound excluded
///
/// ### When NOT to Use [`IntervalLowerClosedUpperOpen`]
/// - **Mathematical integration**: Usually want closed intervals `[a,b]` for definite integrals
/// - **Physical measurements**: Real-world ranges typically include both boundaries
/// - **Probability calculations**: Often need closed intervals for cumulative distributions
/// - **Optimization domains**: Constraint boundaries often need to be included
///
/// ### Recommended Patterns
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::{RealNative64StrictFiniteInDebug, RealScalar};
/// use try_create::TryNew;
///
/// // Define type aliases for your application
/// type Real = RealNative64StrictFiniteInDebug;
/// type RightHalfOpenInterval = IntervalLowerClosedUpperOpen<Real>;
///
/// // Pattern: Use for array-like indexing
/// fn create_index_range(start: usize, count: usize) -> RightHalfOpenInterval {
///     let end = start + count;
///     RightHalfOpenInterval::new(
///         Real::try_new(start as f64).unwrap(),
///         Real::try_new(end as f64).unwrap()
///     )
/// }
///
/// // Pattern: Verify boundary semantics explicitly
/// fn validate_range_boundaries(range: &RightHalfOpenInterval) -> bool {
///     let lower = range.lower_bound_value();
///     let upper = range.upper_bound_value();
///     
///     // Explicitly test the expected boundary behavior
///     range.contains_point(lower) && !range.contains_point(upper)
/// }
///
/// // Pattern: Create partitions with proper adjacency
/// fn create_uniform_partition(
///     total_range: RightHalfOpenInterval,
///     num_parts: usize
/// ) -> Vec<RightHalfOpenInterval> {
///     let start = total_range.lower_bound_value().clone();
///     let length = total_range.length().into_inner();
///     let part_length = length / Real::try_from_f64(num_parts as f64).unwrap();
///     
///     (0..num_parts)
///         .map(|i| {
///             let part_start = start.clone() + Real::try_from_f64(i as f64).unwrap() * part_length.clone();
///             let part_end = part_start.clone() + part_length.clone();
///             RightHalfOpenInterval::new(part_start, part_end)
///         })
///         .collect()
/// }
/// ```
///
/// ## Mathematical Correctness Guarantees
///
/// The [`IntervalLowerClosedUpperOpen`] struct maintains all essential mathematical properties:
///
/// - **Boundary semantics**: Lower bound always included, upper bound always excluded
/// - **Positive measure**: `length() = upper - lower > 0` for all valid instances
/// - **Set operations**: Containment and intersection follow standard interval arithmetic
/// - **Partition compatibility**: Adjacent right half-open intervals create proper partitions
/// - **Continuity properties**: Suitable for left-continuous function domains
/// - **Order preservation**: Respects the natural ordering of real numbers
/// - **Translation invariance**: Shifting preserves the half-open structure
///
/// These properties are preserved regardless of the scalar type used and are guaranteed
/// by the underlying implementations of the [`IntervalTrait`] and [`IntervalFinitePositiveLengthTrait`].
pub type IntervalLowerClosedUpperOpen<RealType> = IntervalBounded<RealType, Closed, Open>;
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
///  Container for all intervals with finite, positive, measurable length.
///
/// The [`IntervalFinitePositiveLength`] enum represents intervals where the upper bound
/// is strictly greater than the lower bound, resulting in a positive measure and
/// uncountably infinite cardinality. This enum encompasses all bounded intervals
/// with non-zero length, distinguished by their boundary inclusion behavior.
///
/// ## Mathematical Foundation
///
/// All variants represent intervals of the form `{x ∈ ℝ : a < x < b}` or similar,
/// where the specific boundary conditions depend on the variant. The fundamental
/// mathematical properties shared by all variants are:
///
/// - **Positive Measure**: `μ(I) = |b - a| > 0` for all variants
/// - **Non-empty Interior**: All intervals contain infinitely many interior points
/// - **Boundedness**: Both endpoints are finite real numbers
/// - **Connectedness**: All intervals are connected sets with no gaps
/// - **Uncountable Cardinality**: Each interval contains uncountably many points
///
/// ## Generic Over Any [`num_valid::RealScalar`] Type
///
/// **The [`IntervalFinitePositiveLength`] enum works seamlessly with any scalar type implementing [`num_valid::RealScalar`]:**
///
/// | Scalar Type | Performance | Validation | Best For |
/// |-------------|-------------|------------|----------|
/// | [`f64`] | ⚡⚡⚡ Maximum | ❌ None | Trusted input, maximum speed |
/// | [`RealNative64StrictFiniteInDebug`](num_valid::RealNative64StrictFiniteInDebug) | ⚡⚡⚡ **Same as f64** | ✅ **Debug only** | **Recommended for most uses** |
/// | [`RealNative64StrictFinite`](num_valid::RealNative64StrictFinite) | ⚡⚡ Small overhead | ✅ Always | Safety-critical applications |
/// | `RealRugStrictFinite` | ⚡ Precision-dependent | ✅ Always | Arbitrary precision needs (available from the [num-valid](https://crates.io/crates/num-valid) crate when compiled with `--features=rug`)|
///
/// ## Enum Variants and Boundary Semantics
///
/// The four variants differ only in their boundary inclusion behavior:
///
/// ### [`IntervalFinitePositiveLength::Closed`] - `[a, b]`
/// **Both endpoints included**
/// - **Mathematical notation**: `[a, b] = {x ∈ ℝ : a ≤ x ≤ b}`
/// - **Boundary behavior**: Contains both `a` and `b`
/// - **Topology**: Compact set (closed and bounded)
/// - **Supremum/Infimum**: Both achieved at the endpoints
/// - **Use cases**: Probability ranges, integration bounds, physical constraints
///
/// ### [`IntervalFinitePositiveLength::Open`] - `(a, b)`
/// **Both endpoints excluded**
/// - **Mathematical notation**: `(a, b) = {x ∈ ℝ : a < x < b}`
/// - **Boundary behavior**: Excludes both `a` and `b`
/// - **Topology**: Open set, not compact
/// - **Supremum/Infimum**: Exist but not achieved
/// - **Use cases**: Strict inequalities, limit domains, convergence regions
///
/// ### [`IntervalFinitePositiveLength::LowerOpenUpperClosed`] - `(a, b]`
/// **Lower endpoint excluded, upper endpoint included**
/// - **Mathematical notation**: `(a, b] = {x ∈ ℝ : a < x ≤ b}`
/// - **Boundary behavior**: Excludes `a`, includes `b`
/// - **Topology**: Neither open nor closed (half-open)
/// - **Use cases**: Right-continuous functions, cumulative distributions
///
/// ### [`IntervalFinitePositiveLength::LowerClosedUpperOpen`] - `[a, b)`
/// **Lower endpoint included, upper endpoint excluded**
/// - **Mathematical notation**: `[a, b) = {x ∈ ℝ : a ≤ x < b}`
/// - **Boundary behavior**: Includes `a`, excludes `b`
/// - **Topology**: Neither open nor closed (half-open)
/// - **Use cases**: Left-continuous functions, array indexing, partitions
///
/// ## Construction Patterns
///
/// ### From Concrete Interval Types (Recommended)
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// // Use the recommended performance-optimal type
/// type Real = RealNative64StrictFiniteInDebug;
///
/// // Create specific interval types, then convert
/// let closed = IntervalClosed::new(
///     Real::try_new(0.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// let positive: IntervalFinitePositiveLength<Real> = closed.into();
///
/// let open = IntervalOpen::new(
///     Real::try_new(-1.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// let positive: IntervalFinitePositiveLength<Real> = open.into();
/// ```
///
/// ### Direct Construction (Advanced)
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// // Build variants directly
/// let closed = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(0.0, 1.0)
/// );
///
/// let open = IntervalFinitePositiveLength::Open(
///     IntervalOpen::new(0.0, 1.0)
/// );
///
/// let half_open_left = IntervalFinitePositiveLength::LowerOpenUpperClosed(
///     IntervalLowerOpenUpperClosed::new(0.0, 1.0)
/// );
///
/// let half_open_right = IntervalFinitePositiveLength::LowerClosedUpperOpen(
///     IntervalLowerClosedUpperOpen::new(0.0, 1.0)
/// );
/// ```
///
/// ## Core Operations
///
/// All [`IntervalFinitePositiveLength`] instances support the complete [`IntervalTrait`] interface
/// plus specialized operations for positive-length intervals:
///
/// ### Point Containment Testing
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let closed = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(0.0, 1.0)
/// );
/// let open = IntervalFinitePositiveLength::Open(
///     IntervalOpen::new(0.0, 1.0)
/// );
///
/// // Closed interval includes endpoints
/// assert!(closed.contains_point(&0.0));    // Lower bound included
/// assert!(closed.contains_point(&0.5));    // Interior point
/// assert!(closed.contains_point(&1.0));    // Upper bound included
/// assert!(!closed.contains_point(&2.0));   // Outside interval
///
/// // Open interval excludes endpoints
/// assert!(!open.contains_point(&0.0));     // Lower bound excluded
/// assert!(open.contains_point(&0.5));      // Interior point
/// assert!(!open.contains_point(&1.0));     // Upper bound excluded
/// assert!(!open.contains_point(&2.0));     // Outside interval
/// ```
///
/// ### Geometric Properties
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let interval = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(-2.0, 3.0)
/// );
///
/// // All variants have identical geometric properties
/// assert_eq!(interval.length().into_inner(), 5.0);           // |b - a| = |3 - (-2)| = 5
/// assert_eq!(interval.midpoint(), 0.5);        // (a + b) / 2 = (-2 + 3) / 2 = 0.5
/// assert!(!interval.is_symmetric());            // a + b ≠ 0
///
/// // Bounds access
/// assert_eq!(interval.lower_bound_value(), &-2.0);
/// assert_eq!(interval.upper_bound_value(), &3.0);
///
/// // Consume to get bounds
/// let (lower, upper) = interval.into_bounds_pair();
/// assert_eq!((lower, upper), (-2.0, 3.0));
/// ```
///
/// ### Interval Containment Testing
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let outer_closed = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(0.0, 2.0)
/// );
/// let inner_open = IntervalFinitePositiveLength::Open(
///     IntervalOpen::new(0.5, 1.5)
/// );
/// let boundary_half_open = IntervalFinitePositiveLength::LowerClosedUpperOpen(
///     IntervalLowerClosedUpperOpen::new(0.0, 1.0)
/// );
///
/// // Closed intervals can contain open intervals
/// assert!(outer_closed.contains_interval(&inner_open));           // [0,2] ⊇ (0.5,1.5) ✓
/// assert!(outer_closed.contains_interval(&boundary_half_open));   // [0,2] ⊇ [0,1) ✓
///
/// // Open intervals cannot contain intervals that include excluded boundaries
/// assert!(!inner_open.contains_interval(&outer_closed));          // (0.5,1.5) ⊉ [0,2] ✗
/// assert!(!inner_open.contains_interval(&boundary_half_open));    // (0.5,1.5) ⊉ [0,1) ✗
/// ```
///
/// ### Intersection Operations
/// ```rust
/// use grid1d::intervals::*;
///
/// let closed = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(0.0, 2.0)
/// );
/// let open = IntervalFinitePositiveLength::Open(
///     IntervalOpen::new(1.0, 3.0)
/// );
///
/// if let Some(intersection) = closed.intersection(&open) {
///     // Result: (1.0, 2.0] - most restrictive boundary combination
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::PositiveLength(positive)) => {
///             println!("Intersection length: {}", positive.length()); // 1.0
///             
///             // Can extract specific type if needed
///             if let IntervalFinitePositiveLength::LowerOpenUpperClosed(half_open) = positive {
///                 assert_eq!(half_open.lower_bound_value(), &1.0);
///                 assert_eq!(half_open.upper_bound_value(), &2.0);
///             }
///         }
///         _ => unreachable!("Positive-length intervals always have positive-length intersections"),
///     }
/// }
///
/// // Edge case: intersection at single point becomes singleton
/// let touching_left = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(0.0, 1.0)
/// );
/// let touching_right = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(1.0, 2.0)
/// );
///
/// if let Some(intersection) = touching_left.intersection(&touching_right) {
///     // Result: singleton at point 1.0
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::ZeroLength(singleton)) => {
///             assert_eq!(singleton.value(), &1.0);
///         }
///         _ => panic!("Expected singleton intersection"),
///     }
/// }
/// ```
///
/// ## Pattern Matching and Variant Analysis
///
/// ### Distinguishing Between Boundary Types
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// fn analyze_boundary_behavior(interval: &IntervalFinitePositiveLength<f64>) -> String {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     match interval {
///         IntervalFinitePositiveLength::Closed(_) => {
///             format!("[{}, {}] - both endpoints included", lower, upper)
///         }
///         IntervalFinitePositiveLength::Open(_) => {
///             format!("({}, {}) - both endpoints excluded", lower, upper)
///         }
///         IntervalFinitePositiveLength::LowerOpenUpperClosed(_) => {
///             format!("({}, {}] - lower open, upper closed", lower, upper)
///         }
///         IntervalFinitePositiveLength::LowerClosedUpperOpen(_) => {
///             format!("[{}, {}) - lower closed, upper open", lower, upper)
///         }
///     }
/// }
///
/// let closed = IntervalFinitePositiveLength::Closed(IntervalClosed::new(1.0, 2.0));
/// let open = IntervalFinitePositiveLength::Open(IntervalOpen::new(1.0, 2.0));
/// let half_open_left = IntervalFinitePositiveLength::LowerOpenUpperClosed(
///     IntervalLowerOpenUpperClosed::new(1.0, 2.0)
/// );
/// let half_open_right = IntervalFinitePositiveLength::LowerClosedUpperOpen(
///     IntervalLowerClosedUpperOpen::new(1.0, 2.0)
/// );
///
/// println!("{}", analyze_boundary_behavior(&closed));       // "[1, 2] - both endpoints included"
/// println!("{}", analyze_boundary_behavior(&open));         // "(1, 2) - both endpoints excluded"
/// println!("{}", analyze_boundary_behavior(&half_open_left)); // "(1, 2] - lower open, upper closed"
/// println!("{}", analyze_boundary_behavior(&half_open_right)); // "[1, 2) - lower closed, upper open"
/// ```
///
/// ### Boundary Endpoint Testing
/// ```rust
/// use grid1d::intervals::*;
///
/// fn test_boundary_inclusion(interval: &IntervalFinitePositiveLength<f64>) -> (bool, bool) {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     let includes_lower = interval.contains_point(&lower);
///     let includes_upper = interval.contains_point(&upper);
///     
///     (includes_lower, includes_upper)
/// }
///
/// let closed = IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 1.0));
/// let open = IntervalFinitePositiveLength::Open(IntervalOpen::new(0.0, 1.0));
/// let left_open = IntervalFinitePositiveLength::LowerOpenUpperClosed(
///     IntervalLowerOpenUpperClosed::new(0.0, 1.0)
/// );
/// let right_open = IntervalFinitePositiveLength::LowerClosedUpperOpen(
///     IntervalLowerClosedUpperOpen::new(0.0, 1.0)
/// );
///
/// assert_eq!(test_boundary_inclusion(&closed), (true, true));     // [0,1]: both included
/// assert_eq!(test_boundary_inclusion(&open), (false, false));     // (0,1): both excluded
/// assert_eq!(test_boundary_inclusion(&left_open), (false, true)); // (0,1]: lower excluded, upper included
/// assert_eq!(test_boundary_inclusion(&right_open), (true, false)); // [0,1): lower included, upper excluded
/// ```
///
/// ## Mathematical Applications
///
/// ### Integration Domains
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealScalar;
///
/// /// Compute definite integral using midpoint rule (simplified example)
/// fn integrate_midpoint<T: RealScalar + Clone>(
///     f: impl Fn(T) -> T,
///     domain: &IntervalFinitePositiveLength<T>,
///     num_subdivisions: usize
/// ) -> T {
///     let length = domain.length().into_inner();
///     let step = length.clone() / T::try_from_f64(num_subdivisions as f64).unwrap();
///     let mut sum = T::zero();
///     
///     for i in 0..num_subdivisions {
///         let offset = T::try_from_f64(i as f64).unwrap() * step.clone() + step.clone() / T::try_from_f64(2.0).unwrap();
///         let x = domain.lower_bound_value().clone() + offset;
///         sum = sum + f(x);
///     }
///     
///     sum * step
/// }
///
/// // Works with any boundary type - the integral is the same
/// let closed_domain = IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 1.0));
/// let open_domain = IntervalFinitePositiveLength::Open(IntervalOpen::new(0.0, 1.0));
///
/// let f = |x: f64| x * x; // f(x) = x²
///
/// let integral_closed = integrate_midpoint(&f, &closed_domain, 1000);
/// let integral_open = integrate_midpoint(&f, &open_domain, 1000);
///
/// // Both should approximate ∫₀¹ x² dx = 1/3 ≈ 0.333...
/// assert!((integral_closed - 1.0/3.0).abs() < 0.01);
/// assert!((integral_open - 1.0/3.0).abs() < 0.01);
/// ```
///
/// ### Probability Theory and Measure
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Represents a continuous uniform distribution
/// struct UniformDistribution {
///     support: IntervalFinitePositiveLength<f64>
/// }
///
/// impl UniformDistribution {
///     fn new(support: IntervalFinitePositiveLength<f64>) -> Self {
///         Self { support }
///     }
///     
///     /// Probability density function
///     fn pdf(&self, x: f64) -> f64 {
///         if self.support.contains_point(&x) {
///             1.0 / self.support.length().into_inner() // Uniform density
///         } else {
///             0.0 // Outside support
///         }
///     }
///     
///     /// Cumulative distribution function  
///     fn cdf(&self, x: f64) -> f64 {
///         let lower = *self.support.lower_bound_value();
///         let upper = *self.support.upper_bound_value();
///         
///         if x <= lower {
///             0.0
///         } else if x >= upper {
///             1.0
///         } else {
///             (x - lower) / self.support.length().into_inner()
///         }
///     }
///     
///     /// Sample from the distribution (simplified)
///     fn sample(&self) -> f64 {
///         let lower = *self.support.lower_bound_value();
///         let upper = *self.support.upper_bound_value();
///         
///         // In real implementation, use proper random number generator
///         lower + (upper - lower) * 0.5 // Deterministic "sample" for testing
///     }
/// }
///
/// // Works with any interval type
/// let uniform_closed = UniformDistribution::new(
///     IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 2.0))
/// );
/// let uniform_open = UniformDistribution::new(
///     IntervalFinitePositiveLength::Open(IntervalOpen::new(0.0, 2.0))
/// );
///
/// // Same density and behavior regardless of boundary type
/// assert_eq!(uniform_closed.pdf(1.0), 0.5);  // 1 / (2 - 0) = 0.5
/// assert_eq!(uniform_open.pdf(1.0), 0.5);    // Same density
///
/// assert_eq!(uniform_closed.cdf(1.0), 0.5);  // (1 - 0) / (2 - 0) = 0.5
/// assert_eq!(uniform_open.cdf(1.0), 0.5);    // Same CDF for interior points
/// ```
///
/// ### Optimization and Root Finding
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Simple bisection method for root finding
/// fn bisection_method(
///     f: impl Fn(f64) -> f64,
///     mut interval: IntervalFinitePositiveLength<f64>,
///     tolerance: f64
/// ) -> Option<f64> {
///     let mut iterations = 0;
///     const MAX_ITERATIONS: usize = 100;
///     
///     // Check that function changes sign over interval
///     let f_lower = f(*interval.lower_bound_value());
///     let f_upper = f(*interval.upper_bound_value());
///     
///     if f_lower * f_upper > 0.0 {
///         return None; // No sign change, no root guaranteed
///     }
///     
///     while interval.length().into_inner() > tolerance && iterations < MAX_ITERATIONS {
///         let midpoint = interval.midpoint();
///         let f_mid = f(midpoint);
///         
///         if f_mid.abs() < tolerance {
///             return Some(midpoint);
///         }
///         
///         let lower = *interval.lower_bound_value();
///         let upper = *interval.upper_bound_value();
///         
///         // Update interval to half containing the root
///         if f_lower * f_mid < 0.0 {
///             // Root in left half
///             interval = IntervalFinitePositiveLength::Closed(
///                 IntervalClosed::new(lower, midpoint)
///             );
///         } else {
///             // Root in right half  
///             interval = IntervalFinitePositiveLength::Closed(
///                 IntervalClosed::new(midpoint, upper)
///             );
///         }
///         
///         iterations += 1;
///     }
///     
///     Some(interval.midpoint())
/// }
///
/// // Find root of f(x) = x² - 2 (should be √2 ≈ 1.414)
/// let search_interval = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(1.0, 2.0)
/// );
///
/// let root = bisection_method(|x| x * x - 2.0, search_interval, 1e-6).unwrap();
/// assert!((root - 2.0_f64.sqrt()).abs() < 1e-6);
/// ```
///
/// ## Type Conversion and Specialization
///
/// ### Converting to Specific Interval Types
/// ```rust
/// use grid1d::intervals::*;
///
/// let positive = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(0.0, 1.0)
/// );
///
/// // Convert to general interval enums
/// let finite: IntervalFiniteLength<f64> = positive.clone().into();
/// let general: Interval<f64> = positive.clone().into();
///
/// // Extract specific types when needed
/// match positive {
///     IntervalFinitePositiveLength::Closed(closed_interval) => {
///         println!("Working with closed interval: {:?}", closed_interval);
///         // Access closed-interval-specific behavior if needed
///         let (lower, upper) = closed_interval.into_bounds_pair();
///         assert_eq!((lower, upper), (0.0, 1.0));
///     }
///     IntervalFinitePositiveLength::Open(open_interval) => {
///         println!("Working with open interval: {:?}", open_interval);
///     }
///     IntervalFinitePositiveLength::LowerOpenUpperClosed(half_open) => {
///         println!("Working with left half-open interval: {:?}", half_open);
///     }
///     IntervalFinitePositiveLength::LowerClosedUpperOpen(half_open) => {
///         println!("Working with right half-open interval: {:?}", half_open);
///     }
/// }
/// ```
///
/// ### Extracting Bounds
/// ```rust
/// use grid1d::intervals::*;
///
/// fn extract_bounds_any_variant(
///     interval: IntervalFinitePositiveLength<f64>
/// ) -> (f64, f64) {
///     // Works uniformly across all variants
///     interval.into_bounds_pair()
/// }
///
/// let closed = IntervalFinitePositiveLength::Closed(IntervalClosed::new(1.0, 2.0));
/// let open = IntervalFinitePositiveLength::Open(IntervalOpen::new(3.0, 4.0));
/// let half_open = IntervalFinitePositiveLength::LowerOpenUpperClosed(
///     IntervalLowerOpenUpperClosed::new(5.0, 6.0)
/// );
///
/// assert_eq!(extract_bounds_any_variant(closed), (1.0, 2.0));
/// assert_eq!(extract_bounds_any_variant(open), (3.0, 4.0));
/// assert_eq!(extract_bounds_any_variant(half_open), (5.0, 6.0));
/// ```
///
/// ## Performance Characteristics
///
/// ### Memory Layout
/// - **Storage**: Two scalar values plus boundary type discriminant
/// - **Size**: Typically 16-24 bytes for f64, depending on alignment
/// - **Alignment**: Natural alignment of the scalar type
/// - **Enum overhead**: Small discriminant tag (1-8 bytes)
///
/// ### Operation Complexity
/// | Operation | Time Complexity | Space Complexity | Notes |
/// |-----------|----------------|------------------|-------|
/// | **Point queries** | O(1) | O(1) | 2 comparisons maximum |
/// | **Containment tests** | O(1) | O(1) | Boundary logic only |
/// | **Intersections** | O(1) | O(1) | Pure computation, may allocate result |
/// | **Geometric calculations** | O(1) | O(1) | Length, midpoint, etc. |
/// | **Pattern matching** | O(1) | O(1) | Compile-time optimized |
/// | **Bound extraction** | O(1) | O(1) | Zero-cost access |
///
/// ### Scalar Type Performance Impact
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::{RealNative64StrictFiniteInDebug, RealNative64StrictFinite, RealScalar};
///
/// // These have identical performance in release builds:
/// type FastPositiveInterval = IntervalFinitePositiveLength<f64>;
/// type OptimalPositiveInterval = IntervalFinitePositiveLength<RealNative64StrictFiniteInDebug>;
///
/// // This has small validation overhead:
/// type SafePositiveInterval = IntervalFinitePositiveLength<RealNative64StrictFinite>;
///
/// // Performance test function (generic over scalar type)
/// fn benchmark_positive_operations<T: RealScalar + Clone>(
///     interval1: &IntervalFinitePositiveLength<T>,
///     interval2: &IntervalFinitePositiveLength<T>
/// ) {
///     // All operations compile to identical assembly for f64 and RealNative64StrictFiniteInDebug
///     let _contains = interval1.contains_interval(interval2);
///     let _intersection = interval1.intersection(interval2);
///     let _length = interval1.length().into_inner();        // O(1) subtraction
///     let _midpoint = interval1.midpoint();   // O(1) arithmetic
///     let _symmetric = interval1.is_symmetric(); // O(1) comparison
///     
///     // Pattern matching is zero-cost
///     match interval1 {
///         IntervalFinitePositiveLength::Closed(_) => { /* ... */ }
///         IntervalFinitePositiveLength::Open(_) => { /* ... */ }
///         IntervalFinitePositiveLength::LowerOpenUpperClosed(_) => { /* ... */ }
///         IntervalFinitePositiveLength::LowerClosedUpperOpen(_) => { /* ... */ }
///     }
/// }
/// ```
///
/// ## Integration with Library Ecosystem
///
/// ### With Numerical Integration
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Adaptive quadrature integration
/// fn adaptive_integrate(
///     f: impl Fn(f64) -> f64 + Copy,
///     domain: &IntervalFinitePositiveLength<f64>,
///     tolerance: f64
/// ) -> f64 {
///     // The integration algorithm is identical regardless of boundary type
///     // because the measure is the same and boundary points have measure zero
///     
///     let length = domain.length().into_inner();
///     let midpoint = domain.midpoint();
///     
///     // Simpson's rule approximation (simplified)
///     let lower = *domain.lower_bound_value();
///     let upper = *domain.upper_bound_value();
///     
///     (length / 6.0) * (f(lower) + 4.0 * f(midpoint) + f(upper))
/// }
///
/// // All boundary types give the same integral (up to numerical precision)
/// let closed_domain = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(0.0, 1.0)
/// );
/// let open_domain = IntervalFinitePositiveLength::Open(
///     IntervalOpen::new(0.0, 1.0)
/// );
///
/// let f = |x: f64| x * x;
/// let integral_closed = adaptive_integrate(f, &closed_domain, 1e-6);
/// let integral_open = adaptive_integrate(f, &open_domain, 1e-6);
///
/// // Should be approximately equal (boundary points don't affect integral)
/// assert!((integral_closed - integral_open).abs() < 1e-10);
/// ```
///
/// ### With Mesh Generation
/// ```rust
/// use grid1d::intervals::*;
///
/// /// Generate uniform mesh points within any positive-length interval
/// fn generate_uniform_mesh(
///     domain: &IntervalFinitePositiveLength<f64>,
///     num_points: usize
/// ) -> Vec<f64> {
///     if num_points <= 1 {
///         return vec![domain.midpoint()];
///     }
///     
///     let lower = *domain.lower_bound_value();
///     let upper = *domain.upper_bound_value();
///     let step = (upper - lower) / (num_points - 1) as f64;
///     
///     (0..num_points)
///         .map(|i| lower + i as f64 * step)
///         .collect()
/// }
///
/// /// Generate mesh respecting boundary conditions
/// fn generate_boundary_aware_mesh(
///     domain: &IntervalFinitePositiveLength<f64>,
///     num_interior_points: usize
/// ) -> Vec<f64> {
///     let lower = *domain.lower_bound_value();
///     let upper = *domain.upper_bound_value();
///     
///     let mut points = Vec::new();
///     
///     // Include boundary points based on interval type
///     match domain {
///         IntervalFinitePositiveLength::Closed(_) => {
///             points.push(lower);
///         }
///         IntervalFinitePositiveLength::LowerClosedUpperOpen(_) => {
///             points.push(lower);
///         }
///         _ => {} // Open boundaries not included
///     }
///     
///     // Add interior points
///     for i in 1..=num_interior_points {
///         let t = i as f64 / (num_interior_points + 1) as f64;
///         points.push(lower + t * (upper - lower));
///     }
///     
///     // Include upper boundary if appropriate
///     match domain {
///         IntervalFinitePositiveLength::Closed(_) => {
///             points.push(upper);
///         }
///         IntervalFinitePositiveLength::LowerOpenUpperClosed(_) => {
///             points.push(upper);
///         }
///         _ => {} // Open boundaries not included
///     }
///     
///     points
/// }
/// ```
///
/// ## Best Practices and Recommendations
///
/// ### When to Use [`IntervalFinitePositiveLength`]
/// - **Numerical analysis**: When you need positive-length domains but want to abstract boundary behavior
/// - **Generic algorithms**: Writing code that works with any finite positive interval
/// - **API design**: Accepting any bounded interval while excluding singletons
/// - **Mathematical modeling**: When the boundary type may vary but the domain must be non-degenerate
///
/// ### When to Use Specific Variants
/// - **Closed**: Integration bounds, probability ranges, physical constraints with inclusive limits
/// - **Open**: Limit domains, convergence regions, strict inequality constraints  
/// - **Half-open**: Partitions, cumulative functions, discrete-continuous interfaces
///
/// ### Recommended Patterns
/// ```rust
/// use grid1d::intervals::*;
/// use into_inner::IntoInner;
/// use num_valid::{RealNative64StrictFiniteInDebug, functions::Rounding};
/// use num::Zero;
///
/// // Define type aliases for your domain
/// type Real = RealNative64StrictFiniteInDebug;
/// type PositiveInterval = IntervalFinitePositiveLength<Real>;
/// type ClosedInterval = IntervalClosed<Real>;
///
/// // Pattern: Handle all variants uniformly when possible
/// fn compute_interval_statistics(interval: &PositiveInterval) -> (Real, Real, Real) {
///     let length = interval.length().into_inner();
///     let midpoint = interval.midpoint();
///     let lower = interval.lower_bound_value().clone();
///     
///     (length, midpoint, lower) // Same calculation for all variants
/// }
///
/// // Pattern: Specialize behavior only when boundary semantics matter
/// fn count_integer_endpoints(interval: &PositiveInterval) -> usize {
///     let lower = interval.lower_bound_value().clone();
///     let upper = interval.upper_bound_value().clone();
///     let lower_int = lower.clone().kernel_floor().into_inner() as i64;
///     let upper_int = upper.clone().kernel_ceil().into_inner() as i64;
///     
///     let mut count = 0;
///     
///     // Check lower boundary
///     if lower == lower_int as f64 && interval.contains_point(&lower) {
///         count += 1;
///     }
///     
///     // Check upper boundary  
///     if upper == upper_int as f64 && interval.contains_point(&upper) {
///         count += 1;
///     }
///     
///     count
/// }
///
/// // Pattern: Convert to most specific type when needed
/// fn require_closed_interval(interval: PositiveInterval) -> Result<ClosedInterval, String> {
///     match interval {
///         IntervalFinitePositiveLength::Closed(closed) => Ok(closed),
///         _ => Err("Algorithm requires closed interval for boundary conditions".to_string()),
///     }
/// }
/// ```
///
/// ## Error Handling and Edge Cases
///
/// ### Construction Validation
/// ```rust,ignore
/// use grid1d::intervals::*;
///
/// // All variants validate that lower < upper during construction
/// assert!(IntervalClosed::try_new(1.0, 0.0).is_err());  // Invalid bounds
/// assert!(IntervalOpen::try_new(1.0, 1.0).is_err());    // Zero length
/// assert!(IntervalLowerOpenUpperClosed::try_new(2.0, 1.0).is_err()); // Inverted
///
/// // In debug mode, invalid construction panics
/// #[cfg(debug_assertions)]
/// {
///     std::panic::catch_unwind(|| {
///         IntervalClosed::new(1.0, 0.0); // Panics in debug
///     }).expect_err("Should panic on invalid bounds");
/// }
/// ```
///
/// ### Numerical Precision Considerations
/// ```rust
/// use grid1d::intervals::*;
///
/// // CAUTION: Very small intervals near floating-point precision limits
/// let tiny_interval = IntervalFinitePositiveLength::Closed(
///     IntervalClosed::new(1.0, 1.0 + f64::EPSILON)
/// );
///
/// // Length is positive but very small
/// assert!(tiny_interval.length().into_inner() > 0.0);
/// assert!(tiny_interval.length().into_inner() < 1e-15);
///
/// // Midpoint calculation may have precision issues
/// let midpoint = tiny_interval.midpoint();
/// let expected_mid = 1.0 + f64::EPSILON / 2.0;
///
/// // Use appropriate tolerance for comparisons
/// assert!((midpoint - expected_mid).abs() < f64::EPSILON);
/// ```
///
/// ### Common Pitfalls and Solutions
/// ```rust
/// use grid1d::intervals::*;
///
/// // WRONG: Assuming all intervals include their endpoints
/// fn naive_endpoint_processing(interval: &IntervalFinitePositiveLength<f64>) -> (f64, f64) {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     // This ignores boundary semantics!
///     (lower, upper) // May include points not actually in the interval
/// }
///
/// // CORRECT: Check boundary inclusion when it matters
/// fn proper_endpoint_processing(interval: &IntervalFinitePositiveLength<f64>) -> Vec<f64> {
///     let lower = *interval.lower_bound_value();
///     let upper = *interval.upper_bound_value();
///     
///     let mut endpoints = Vec::new();
///     
///     if interval.contains_point(&lower) {
///         endpoints.push(lower);
///     }
///     if interval.contains_point(&upper) {
///         endpoints.push(upper);
///     }
///     
///     endpoints
/// }
///
/// let closed = IntervalFinitePositiveLength::Closed(IntervalClosed::new(0.0, 1.0));
/// let open = IntervalFinitePositiveLength::Open(IntervalOpen::new(0.0, 1.0));
///
/// assert_eq!(proper_endpoint_processing(&closed), vec![0.0, 1.0]); // Both endpoints
/// assert!(proper_endpoint_processing(&open).is_empty()); // No endpoints
/// ```
///
/// ## Mathematical Correctness Guarantees
///
/// The [`IntervalFinitePositiveLength`] enum maintains all essential mathematical properties:
///
/// - **Positive measure**: `μ(I) = |upper - lower| > 0` for all variants
/// - **Containment transitivity**: If A ⊆ B and B ⊆ C, then A ⊆ C
/// - **Intersection commutativity**: A ∩ B = B ∩ A
/// - **Intersection associativity**: (A ∩ B) ∩ C = A ∩ (B ∩ C)
/// - **Monotonicity**: If A ⊆ B, then μ(A) ≤ μ(B)
/// - **Boundary consistency**: Containment and intersection operations respect boundary semantics
/// - **Geometric invariance**: Length, midpoint, and symmetry properties are boundary-independent
///
/// These properties are preserved regardless of the scalar type used and are guaranteed
/// by the underlying implementations of the [`IntervalTrait`] and [`IntervalFinitePositiveLengthTrait`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound(deserialize = "RealType: for<'a> Deserialize<'a>"))]
pub enum IntervalFinitePositiveLength<RealType: RealScalar> {
    /// A ***closed*** interval `[a,b]` where both endpoints are included.
    ///
    /// This variant represents the most restrictive form of inclusion, where both
    /// boundary points `a` and `b` are considered part of the interval. The interval
    /// contains all real numbers `x` such that `a ≤ x ≤ b`.
    ///
    /// **Mathematical properties:**
    /// - **Compactness**: Always compact (closed and bounded)
    /// - **Boundary inclusion**: Both `a` and `b` are contained
    /// - **Supremum/Infimum**: Both achieved at the endpoints
    /// - **Typical use cases**: Integration bounds, probability ranges, physical constraints
    Closed(IntervalClosed<RealType>),

    /// An ***open*** interval `(a,b)` where both endpoints are excluded.
    ///
    /// This variant represents the most permissive form of exclusion, where neither
    /// boundary point `a` nor `b` is considered part of the interval. The interval
    /// contains all real numbers `x` such that `a < x < b`.
    ///
    /// **Mathematical properties:**
    /// - **Openness**: Open set in the real line topology
    /// - **Boundary exclusion**: Neither `a` nor `b` are contained
    /// - **Supremum/Infimum**: Exist but are not achieved
    /// - **Typical use cases**: Limit domains, convergence regions, strict inequalities
    Open(IntervalOpen<RealType>),

    /// A ***left half-open*** interval `(a,b]` where the lower endpoint is excluded and the upper endpoint is included.
    ///
    /// This variant represents a mixed boundary condition where the lower bound `a`
    /// is not part of the interval but the upper bound `b` is included. The interval
    /// contains all real numbers `x` such that `a < x ≤ b`.
    ///
    /// **Mathematical properties:**
    /// - **Boundary behavior**: Excludes `a`, includes `b`
    /// - **Topology**: Neither open nor closed (half-open)
    /// - **Right-continuity**: Natural for right-continuous functions
    /// - **Typical use cases**: Cumulative distributions, partition elements
    LowerOpenUpperClosed(IntervalLowerOpenUpperClosed<RealType>),

    /// A ***right half-open*** interval `[a,b)` where the lower endpoint is included and the upper endpoint is excluded.
    ///
    /// This variant represents a mixed boundary condition where the lower bound `a`
    /// is part of the interval but the upper bound `b` is not included. The interval
    /// contains all real numbers `x` such that `a ≤ x < b`.
    ///
    /// **Mathematical properties:**
    /// - **Boundary behavior**: Includes `a`, excludes `b`
    /// - **Topology**: Neither open nor closed (half-open)
    /// - **Left-continuity**: Natural for left-continuous functions
    /// - **Typical use cases**: Array indexing ranges, interval partitions, discrete-continuous boundaries
    LowerClosedUpperOpen(IntervalLowerClosedUpperOpen<RealType>),
}

impl<RealType: RealScalar> IntervalFinitePositiveLength<RealType> {
    /// Constructs a finite-length interval with positive length from runtime-typed bounds.
    ///
    /// Similar to [`IntervalFiniteLength::try_from_runtime_bounds`], but excludes singleton intervals by
    /// construction. This function is used internally when the caller knows the interval
    /// must have positive length (e.g., in hull computation between bounded intervals).
    ///
    /// # Arguments
    ///
    /// * `lower_bound` - Runtime-typed lower bound (closed or open)
    /// * `upper_bound` - Runtime-typed upper bound (closed or open)
    ///
    /// # Bound Type Selection
    ///
    /// | Lower | Upper | Result Type | Notation |
    /// |-------|-------|-------------|----------|
    /// | Closed | Closed | [`IntervalClosed`] | `[a, b]` where `a < b` |
    /// | Closed | Open | [`IntervalLowerClosedUpperOpen`] | `[a, b)` |
    /// | Open | Closed | [`IntervalLowerOpenUpperClosed`] | `(a, b]` |
    /// | Open | Open | [`IntervalOpen`] | `(a, b)` |
    ///
    /// # Returns
    ///
    /// * `Ok(IntervalFinitePositiveLength)` - Successfully constructed interval with `lower < upper`
    /// * `Err(ErrorsIntervalConstruction)` - If `lower_bound ≥ upper_bound`
    ///
    /// # Difference from `IntervalFiniteLength::try_from_runtime_bounds`
    ///
    /// Unlike [`IntervalFiniteLength::try_from_runtime_bounds`], this function:
    /// - **Does not** check for singleton case (assumes `lower ≠ upper`)
    /// - **Always** creates positive-length intervals
    /// - Used when singleton case is excluded by construction
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Note: This is a private function used internally
    /// use grid1d::intervals::*;
    /// use grid1d::bounds::*;
    /// use try_create::New;
    ///
    /// // Half-open interval [0, 1)
    /// let lower: LowerBoundRuntime<f64> = LowerBoundClosed::new(0.0).into();
    /// let upper: UpperBoundRuntime<f64> = UpperBoundOpen::new(1.0).into();
    /// let interval = IntervalFinitePositiveLength::try_from_runtime_bounds(lower, upper).unwrap();
    /// ```
    ///
    /// # Use Cases
    ///
    /// - Hull computation between bounded intervals (always produces positive-length result)
    /// - Operations known to produce non-singleton intervals
    /// - Performance optimization when singleton check is unnecessary
    pub(crate) fn try_from_runtime_bounds(
        lower_bound: LowerBoundRuntime<RealType>,
        upper_bound: UpperBoundRuntime<RealType>,
    ) -> Result<Self, ErrorsIntervalConstruction<RealType>> {
        // Delegate to the appropriate concrete interval type's try_new() method
        // This ensures consistent validation and maintains a single source of truth
        match (lower_bound, upper_bound) {
            (LowerBoundRuntime::Closed(lower_bound), UpperBoundRuntime::Closed(upper_bound)) => {
                Ok(IntervalClosed::try_from_static_bounds(lower_bound, upper_bound)?.into())
            }
            (LowerBoundRuntime::Closed(lower_bound), UpperBoundRuntime::Open(upper_bound)) => Ok(
                IntervalLowerClosedUpperOpen::try_from_static_bounds(lower_bound, upper_bound)?
                    .into(),
            ),
            (LowerBoundRuntime::Open(lower_bound), UpperBoundRuntime::Closed(upper_bound)) => Ok(
                IntervalLowerOpenUpperClosed::try_from_static_bounds(lower_bound, upper_bound)?
                    .into(),
            ),
            (LowerBoundRuntime::Open(lower_bound), UpperBoundRuntime::Open(upper_bound)) => {
                Ok(IntervalOpen::try_from_static_bounds(lower_bound, upper_bound)?.into())
            }
        }
    }
}

impl<RealType: RealScalar> IntervalOperations for IntervalFinitePositiveLength<RealType> {}

impl<RealType: RealScalar> Contains for IntervalFinitePositiveLength<RealType> {
    /// Returns `true` if the 1D point/coordinate `x` is contained in the current [`IntervalFinitePositiveLength`].
    #[inline(always)]
    fn contains_point(&self, x: &RealType) -> bool {
        match self {
            IntervalFinitePositiveLength::Closed(interval) => interval.contains_point(x),
            IntervalFinitePositiveLength::Open(interval) => interval.contains_point(x),
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.contains_point(x)
            }
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.contains_point(x)
            }
        }
    }
}

impl<RealType: RealScalar> IntervalTrait for IntervalFinitePositiveLength<RealType> {}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// A singleton interval `[a]` containing exactly one point.
///
/// The [`IntervalSingleton`] represents the most degenerate form of interval in mathematical
/// analysis - a set containing exactly one point. While mathematically an interval typically
/// implies a range of values, singleton intervals are essential for representing point masses,
/// discrete events, and boundary conditions in mathematical modeling.
///
/// ## Mathematical Properties
///
/// - **Notation**: `[a]` or `{a}` - a single point
/// - **Definition**: `{x ∈ ℝ : x = a}` - the set containing only the value `a`
/// - **Measure**: Always `0` (zero length in Lebesgue measure)
/// - **Cardinality**: Exactly `1` (finite set)
/// - **Topology**: Isolated point with empty interior
/// - **Connectedness**: Trivially connected (single point)
/// - **Compactness**: Always compact (finite sets are compact)
///
/// ## Use Cases
///
/// Singleton intervals are essential when:
/// - **Point masses**: Representing discrete probability masses at specific values
/// - **Boundary conditions**: Modeling fixed points in differential equations
/// - **Discrete events**: Representing events that occur at exact moments or values
/// - **Degenerate cases**: Handling limit cases where intervals collapse to points
/// - **Constraint satisfaction**: Representing exact equality constraints
/// - **Intersection results**: When two intervals meet at exactly one point
///
/// ## Comparison with Other Interval Types
///
/// | Property | Singleton `[a]` | Closed `[a,b]` | Open `(a,b)` |
/// |----------|-----------------|----------------|--------------|
/// | Contains `a` | ✓ | ✓ | ✗ |
/// | Contains other points | ✗ | ✓ (if `b > a`) | ✓ (if `b > a`) |
/// | Length | `0` | `b - a` | `b - a` |
/// | Measure | `0` | `b - a` | `b - a` |
/// | Cardinality | `1` | Uncountably infinite | Uncountably infinite |
/// | Compactness | Always | Always | Never |
/// | Interior | Empty set `∅` | `(a, b)` | `(a, b)` |
///
/// ## Construction
///
/// ### Safe Construction (Recommended)
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::{New, TryNew};
///
/// // Use the recommended performance-optimal type
/// type Real = RealNative64StrictFiniteInDebug;
///
/// // Create singleton with validated scalar
/// let singleton = IntervalSingleton::new(Real::try_new(42.0).unwrap());
/// assert_eq!(singleton.value(), &Real::try_new(42.0).unwrap());
/// ```
///
/// ### Raw Construction (Use with Caution)
/// ```rust
/// use grid1d::intervals::IntervalSingleton;
/// use try_create::New;
///
/// // Direct construction with raw f64 - only when you trust your data
/// let singleton = IntervalSingleton::new(3.14159);
/// assert_eq!(singleton.value(), &3.14159);
/// ```
///
/// ## Key Operations
///
/// ### Point Containment (Exact Match Only)
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let singleton = IntervalSingleton::new(42.0);
///
/// // Only the exact value is contained
/// assert!(singleton.contains_point(&42.0));      // Exact match
/// assert!(!singleton.contains_point(&42.1));     // Any other value
/// assert!(!singleton.contains_point(&41.9));     // Any other value
/// assert!(!singleton.contains_point(&0.0));      // Any other value
///
/// // Floating-point precision considerations
/// let epsilon = f64::EPSILON;
/// assert!(!singleton.contains_point(&(42.0 * (1.0 + epsilon)))); // Not exactly 42.0
/// ```
///
/// ### Value Access and Consumption
/// ```rust
/// use grid1d::intervals::*;
/// use into_inner::IntoInner;
/// use try_create::New;
///
/// let singleton = IntervalSingleton::new(123.456);
///
/// // Access the value by reference
/// assert_eq!(singleton.value(), &123.456);
///
/// // Consume the singleton to get the value
/// let value = singleton.into_inner();
/// assert_eq!(value, 123.456);
/// ```
///
/// ### Interval Containment Testing
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let singleton_a = IntervalSingleton::new(5.0);
/// let singleton_b = IntervalSingleton::new(5.0);
/// let singleton_c = IntervalSingleton::new(10.0);
/// let interval = IntervalClosed::new(0.0, 10.0);
///
/// // Singleton contains itself if values are equal
/// assert!(singleton_a.contains_interval(&singleton_b));  // Both contain 5.0
/// assert!(singleton_b.contains_interval(&singleton_a));  // Symmetric
///
/// // Different singletons don't contain each other
/// assert!(!singleton_a.contains_interval(&singleton_c)); // 5.0 ≠ 10.0
/// assert!(!singleton_c.contains_interval(&singleton_a)); // 10.0 ≠ 5.0
///
/// // Larger intervals can contain singletons
/// assert!(interval.contains_interval(&singleton_a));     // [0,10] contains {5}
/// assert!(interval.contains_interval(&singleton_c));     // [0,10] contains {10}
///
/// // Singletons cannot contain larger intervals
/// assert!(!singleton_a.contains_interval(&interval));    // {5} cannot contain [0,10]
/// ```
///
/// ## Intersection Examples
///
/// ### Singleton with Singleton
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let singleton_a = IntervalSingleton::new(7.0);
/// let singleton_b = IntervalSingleton::new(7.0);
/// let singleton_c = IntervalSingleton::new(8.0);
///
/// // Intersection of identical singletons
/// if let Some(intersection) = singleton_a.intersection(&singleton_b) {
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::ZeroLength(result)) => {
///             assert_eq!(result.value(), &7.0);
///         }
///         _ => unreachable!("Expected singleton intersection"),
///     }
/// }
///
/// // Intersection of different singletons
/// assert!(singleton_a.intersection(&singleton_c).is_none()); // {7} ∩ {8} = ∅
/// ```
///
/// ### Singleton with Interval
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let singleton = IntervalSingleton::new(2.5);
/// let closed = IntervalClosed::new(2.0, 3.0);
/// let open = IntervalOpen::new(2.0, 3.0);
/// let outside = IntervalClosed::new(4.0, 5.0);
///
/// // Singleton intersects interval if contained
/// if let Some(intersection) = singleton.intersection(&closed) {
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::ZeroLength(result)) => {
///             assert_eq!(result.value(), &2.5); // Returns the singleton
///         }
///         _ => unreachable!("Expected singleton intersection"),
///     }
/// }
///
/// // Same result for open interval (since 2.5 is in interior)
/// if let Some(intersection) = singleton.intersection(&open) {
///     match intersection {
///         Interval::FiniteLength(IntervalFiniteLength::ZeroLength(result)) => {
///             assert_eq!(result.value(), &2.5);
///         }
///         _ => unreachable!("Expected singleton intersection"),
///     }
/// }
///
/// // No intersection when singleton is outside interval
/// assert!(singleton.intersection(&outside).is_none()); // {2.5} ∩ [4,5] = ∅
/// ```
///
/// ### Edge Cases: Boundary Intersections
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let boundary_singleton = IntervalSingleton::new(1.0);
/// let closed = IntervalClosed::new(1.0, 2.0);        // [1, 2]
/// let open = IntervalOpen::new(1.0, 2.0);            // (1, 2)
/// let half_open_left = IntervalLowerOpenUpperClosed::new(1.0, 2.0); // (1, 2]
/// let half_open_right = IntervalLowerClosedUpperOpen::new(1.0, 2.0); // [1, 2)
///
/// // Intersection depends on boundary inclusion
/// assert!(boundary_singleton.intersection(&closed).is_some());      // {1} ∩ [1,2] = {1}
/// assert!(boundary_singleton.intersection(&open).is_none());        // {1} ∩ (1,2) = ∅
/// assert!(boundary_singleton.intersection(&half_open_left).is_none()); // {1} ∩ (1,2] = ∅
/// assert!(boundary_singleton.intersection(&half_open_right).is_some()); // {1} ∩ [1,2) = {1}
/// ```
///
/// ## Advanced Usage Patterns
///
/// ### Generic Programming with Different Scalar Types
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::{RealScalar, RealNative64StrictFinite};
/// use try_create::{New, TryNew};
///
/// // Generic function works with any RealScalar type
/// fn analyze_singleton<T: RealScalar + std::fmt::Display>(
///     singleton: &IntervalSingleton<T>
/// ) -> String {
///     format!("Singleton interval containing the single point: {}", singleton.value())
/// }
///
/// // Works with validated types
/// let safe_singleton = IntervalSingleton::new(
///     RealNative64StrictFinite::try_new(2.71828).unwrap()
/// );
/// println!("{}", analyze_singleton(&safe_singleton));
///
/// // Also works with raw f64
/// let raw_singleton = IntervalSingleton::new(2.71828);
/// println!("{}", analyze_singleton(&raw_singleton));
/// ```
///
/// ### Conversion to Other Interval Types
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let singleton = IntervalSingleton::new(1.5);
///
/// // Convert to category enums
/// let finite_zero: IntervalFiniteLength<f64> = singleton.clone().into();
/// let general: Interval<f64> = singleton.into();
///
/// // Pattern match on the general enum
/// match general {
///     Interval::FiniteLength(IntervalFiniteLength::ZeroLength(recovered_singleton)) => {
///         assert_eq!(recovered_singleton.value(), &1.5);
///     }
///     _ => unreachable!("Should be singleton interval"),
/// }
/// ```
///
/// ## Mathematical Applications
///
/// ### Probability Theory: Point Masses
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// /// Represents a discrete probability distribution with point masses
/// struct DiscreteDistribution {
///     point_masses: Vec<(IntervalSingleton<f64>, f64)>, // (point, probability)
/// }
///
/// impl DiscreteDistribution {
///     fn new() -> Self {
///         Self { point_masses: Vec::new() }
///     }
///     
///     /// Add a point mass at a specific value
///     fn add_point_mass(&mut self, value: f64, probability: f64) {
///         self.point_masses.push((IntervalSingleton::new(value), probability));
///     }
///     
///     /// Probability mass function
///     fn pmf(&self, x: f64) -> f64 {
///         for (point, prob) in &self.point_masses {
///             if point.contains_point(&x) {
///                 return *prob;
///             }
///         }
///         0.0 // No mass at this point
///     }
///     
///     /// Support: all points with non-zero probability
///     fn support(&self) -> Vec<f64> {
///         self.point_masses.iter()
///             .map(|(point, _)| *point.value())
///             .collect()
///     }
/// }
///
/// let mut discrete = DiscreteDistribution::new();
/// discrete.add_point_mass(1.0, 0.3);
/// discrete.add_point_mass(2.0, 0.5);
/// discrete.add_point_mass(3.0, 0.2);
///
/// assert_eq!(discrete.pmf(1.0), 0.3);
/// assert_eq!(discrete.pmf(1.5), 0.0);  // No mass between points
/// assert_eq!(discrete.pmf(2.0), 0.5);
/// assert_eq!(discrete.support(), vec![1.0, 2.0, 3.0]);
/// ```
///
/// ### Constraint Satisfaction: Exact Equality
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// /// Represents an exact equality constraint in optimization
/// struct EqualityConstraint {
///     feasible_set: IntervalSingleton<f64>
/// }
///
/// impl EqualityConstraint {
///     /// Create constraint: x = target_value
///     fn new(target_value: f64) -> Self {
///         Self {
///             feasible_set: IntervalSingleton::new(target_value)
///         }
///     }
///     
///     /// Check if a point satisfies the exact equality constraint
///     fn is_satisfied(&self, x: f64) -> bool {
///         self.feasible_set.contains_point(&x)
///     }
///     
///     /// Get the target value
///     fn target_value(&self) -> f64 {
///         *self.feasible_set.value()
///     }
///     
///     /// Constraint violation (distance from feasible point)
///     fn violation(&self, x: f64) -> f64 {
///         (x - self.target_value()).abs()
///     }
///     
///     /// Project a point onto the feasible set (returns target value)
///     fn project(&self, _x: f64) -> f64 {
///         self.target_value() // Always project to the single feasible point
///     }
/// }
///
/// let constraint = EqualityConstraint::new(5.0); // x = 5
///
/// assert!(constraint.is_satisfied(5.0));     // Exact match
/// assert!(!constraint.is_satisfied(5.001));  // Any deviation
/// assert!(!constraint.is_satisfied(4.999));  // Any deviation
///
/// assert_eq!(constraint.target_value(), 5.0);
/// assert_eq!(constraint.violation(5.0), 0.0);
/// assert_eq!(constraint.violation(6.0), 1.0);
/// assert_eq!(constraint.project(100.0), 5.0); // Always projects to target
/// ```
///
/// ### Dynamical Systems: Fixed Points
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// /// Represents a fixed point in a dynamical system
/// struct FixedPoint {
///     point: IntervalSingleton<f64>
/// }
///
/// impl FixedPoint {
///     fn new(value: f64) -> Self {
///         Self {
///             point: IntervalSingleton::new(value)
///         }
///     }
///     
///     /// Check if a trajectory passes through the fixed point
///     fn is_visited_by_trajectory(&self, trajectory: &[f64]) -> bool {
///         trajectory.iter().any(|&x| self.point.contains_point(&x))
///     }
///     
///     /// Distance from a point to the fixed point
///     fn distance_from(&self, x: f64) -> f64 {
///         (x - self.point.value()).abs()
///     }
///     
///     /// Check if a point is within epsilon of the fixed point
///     fn is_near(&self, x: f64, epsilon: f64) -> bool {
///         self.distance_from(x) < epsilon
///     }
/// }
///
/// // Example: fixed point of f(x) = x/2 + 1 is x = 2
/// let fixed_point = FixedPoint::new(2.0);
///
/// let trajectory = vec![4.0, 3.0, 2.5, 2.25, 2.125]; // Converging to 2.0
/// assert!(!fixed_point.is_visited_by_trajectory(&trajectory)); // Doesn't hit exactly
///
/// let exact_trajectory = vec![4.0, 3.0, 2.0, 2.0, 2.0]; // Hits fixed point
/// assert!(fixed_point.is_visited_by_trajectory(&exact_trajectory));
///
/// assert!((fixed_point.distance_from(2.1) - 0.1).abs() < 1.0e-15);
/// assert!(fixed_point.is_near(1.999, 0.01));
/// assert!(!fixed_point.is_near(1.99, 0.001));
/// ```
///
/// ### Signal Processing: Impulse Functions
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// /// Represents a Dirac delta function approximation (impulse at specific point)
/// struct DiracDelta {
///     impulse_location: IntervalSingleton<f64>,
///     amplitude: f64,
/// }
///
/// impl DiracDelta {
///     fn new(location: f64, amplitude: f64) -> Self {
///         Self {
///             impulse_location: IntervalSingleton::new(location),
///             amplitude,
///         }
///     }
///     
///     /// Sample the delta function (infinite at impulse location, zero elsewhere)
///     fn sample(&self, x: f64) -> f64 {
///         if self.impulse_location.contains_point(&x) {
///             self.amplitude // In practice, this represents infinite amplitude
///         } else {
///             0.0
///         }
///     }
///     
///     /// Get the location of the impulse
///     fn location(&self) -> f64 {
///         *self.impulse_location.value()
///     }
///     
///     /// Integrate over any interval containing the impulse
///     fn integrate_over(&self, interval: &impl IntervalTrait<RealType = f64>) -> f64 {
///         if interval.contains_interval(&self.impulse_location) {
///             self.amplitude // Integral of delta function is its amplitude
///         } else {
///             0.0 // No impulse in this interval
///         }
///     }
/// }
///
/// let impulse = DiracDelta::new(0.0, 1.0); // Unit impulse at t=0
///
/// assert_eq!(impulse.sample(0.0), 1.0);     // At impulse location
/// assert_eq!(impulse.sample(0.001), 0.0);   // Anywhere else
/// assert_eq!(impulse.location(), 0.0);
///
/// let containing_interval = IntervalClosed::new(-1.0, 1.0);
/// let outside_interval = IntervalClosed::new(1.0, 2.0);
///
/// assert_eq!(impulse.integrate_over(&containing_interval), 1.0); // Contains impulse
/// assert_eq!(impulse.integrate_over(&outside_interval), 0.0);    // Doesn't contain impulse
/// ```
///
/// ## Performance Characteristics
///
/// ### Memory Layout
/// - **Storage**: Single scalar value (8 bytes for f64)
/// - **Alignment**: Natural alignment of the scalar type
/// - **No heap allocation**: All data stored inline
/// - **Minimal overhead**: Most compact interval representation
///
/// ### Operation Complexity
/// | Operation | Time Complexity | Notes |
/// |-----------|-----------------|-------|
/// | **Point queries** | O(1) | Single equality comparison |
/// | **Containment tests** | O(1) | Equality check only |
/// | **Intersections** | O(1) | Equality or emptiness check |
/// | **Value access** | O(1) | Direct field access |
/// | **Construction** | O(1) | Single validation check in debug mode |
///
/// ### Comparison with Other Interval Types
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// // Singleton has the smallest memory footprint
/// let singleton = IntervalSingleton::new(42.0);
/// let open = IntervalOpen::new(41.9, 42.1); // Approximation
///
/// // Closed interval with equal lower and upper bounds (degenerate interval) cannot be built
///
/// // All represent roughly the same mathematical concept but:
/// // - Singleton: 8 bytes, exact point representation
/// // - Open: 16+ bytes, approximate neighborhood
///
/// let n = 1000000;
/// let one_div_n = 1.0e-6;
///
/// // Operations on singleton are fastest
/// let start = std::time::Instant::now();
/// for i in 0..n {
///     let x = i as f64 * one_div_n;
///     let _ = singleton.contains_point(&x); // Single equality check
/// }
/// let singleton_time = start.elapsed();
///
/// let start = std::time::Instant::now();
/// for i in 0..n {
///     let x = i as f64 * one_div_n;
///     let _ = open.contains_point(&x); // Two comparisons + equality check
/// }
/// let open_time = start.elapsed();
///
/// // singleton_time should be faster than open_time
/// ```
///
/// ## Error Handling and Edge Cases
///
/// ### Construction Validation
/// ```rust,ignore
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// // Valid construction
/// let singleton = IntervalSingleton::new(123.456);
/// assert_eq!(singleton.value(), &123.456);
///
/// #[cfg(debug_assertions)]
/// {
///     // Debug mode validation catches invalid values
///     std::panic::catch_unwind(|| {
///         IntervalSingleton::new(f64::NAN); // Panics in debug
///     }).expect_err("Should panic on NaN");
///     
///     std::panic::catch_unwind(|| {
///         IntervalSingleton::new(f64::INFINITY); // Panics in debug
///     }).expect_err("Should panic on infinity");
/// }
/// ```
///
/// ### Floating-Point Precision Considerations
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// let singleton = IntervalSingleton::new(0.1);
///
/// // Exact comparison required for containment
/// let computed_value = 0.1_f64; // This might have precision issues
/// let sum_value = 0.05_f64 + 0.05_f64; // This might be different
///
/// // These might not be equal due to floating-point representation
/// if singleton.contains_point(&computed_value) {
///     println!("Exact match");
/// } else {
///     println!("Precision difference: {} vs {}", singleton.value(), computed_value);
/// }
///
/// // For approximate comparisons, use interval neighborhoods instead
/// let epsilon = 1e-10;
/// let neighborhood = IntervalClosed::new(0.1 - epsilon, 0.1 + epsilon);
/// assert!(neighborhood.contains_point(&computed_value)); // More robust
/// ```
///
/// ### Common Pitfalls and Solutions
/// ```rust
/// use grid1d::intervals::*;
/// use try_create::New;
///
/// // WRONG: Expecting singleton to behave like an interval with length
/// fn naive_midpoint(singleton: &IntervalSingleton<f64>) -> f64 {
///     // This doesn't make sense - singleton has no "middle"
///     *singleton.value() // The value IS the midpoint
/// }
///
/// // CORRECT: Understanding that singleton represents a single point
/// fn get_singleton_value(singleton: &IntervalSingleton<f64>) -> f64 {
///     *singleton.value() // The single point value
/// }
///
/// // WRONG: Trying to sample "within" a singleton
/// fn naive_sample_from_singleton(singleton: &IntervalSingleton<f64>) -> Vec<f64> {
///     // Can't sample multiple distinct points from a singleton!
///     vec![*singleton.value(); 10] // All samples are the same
/// }
///
/// // CORRECT: Understanding that singleton contains only one point
/// fn sample_singleton_correctly(singleton: &IntervalSingleton<f64>, n: usize) -> Vec<f64> {
///     vec![*singleton.value(); n] // All samples must be the same value
/// }
///
/// let singleton = IntervalSingleton::new(7.0);
/// assert_eq!(get_singleton_value(&singleton), 7.0);
/// assert_eq!(sample_singleton_correctly(&singleton, 5), vec![7.0, 7.0, 7.0, 7.0, 7.0]);
/// ```
///
/// ## Best Practices and Recommendations
///
/// ### When to Use [`IntervalSingleton`]
/// - **Point masses**: Discrete probability distributions
/// - **Exact constraints**: Equality constraints in optimization
/// - **Fixed points**: Dynamical systems analysis
/// - **Boundary conditions**: Specific value requirements
/// - **Degenerate limits**: When intervals collapse to points
/// - **Discrete events**: Events at specific values/times
///
/// ### When NOT to Use [`IntervalSingleton`]
/// - **Ranges of values**: Use proper intervals like [`IntervalClosed`]
/// - **Approximate equality**: Use small intervals instead
/// - **Continuous domains**: Use positive-length intervals
/// - **Tolerances**: Use intervals with appropriate width
///
/// ### Recommended Patterns
/// ```rust
/// use grid1d::intervals::*;
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::{New, TryNew};
/// use into_inner::IntoInner;
///
/// // Define type aliases for your application
/// type Real = RealNative64StrictFiniteInDebug;
/// type Singleton = IntervalSingleton<Real>;
///
/// // Pattern: Use for exact point representations
/// fn create_point_constraint(target: Real) -> Singleton {
///     Singleton::new(target)
/// }
///
/// // Pattern: Convert to interval when you need neighborhoods
/// fn expand_to_neighborhood(singleton: Singleton, epsilon: Real) -> IntervalClosed<Real> {
///     let value = singleton.into_inner();
///     IntervalClosed::new(value.clone() - &epsilon, value + epsilon)
/// }
///
/// // Pattern: Check exact equality, not approximate
/// fn is_exactly_at_point(singleton: &Singleton, candidate: &Real) -> bool {
///     singleton.contains_point(candidate) // Exact equality required
/// }
///
/// // Pattern: Handle singleton vs interval cases explicitly
/// fn handle_interval_or_singleton(input: Interval<Real>) -> String {
///     match input {
///         Interval::FiniteLength(IntervalFiniteLength::ZeroLength(singleton)) => {
///             format!("Exact point: {}", singleton.value())
///         }
///         Interval::FiniteLength(IntervalFiniteLength::PositiveLength(interval)) => {
///             format!("Range: [{}, {}]", interval.lower_bound_value(), interval.upper_bound_value())
///         }
///         Interval::InfiniteLength(_) => {
///             "Unbounded interval".to_string()
///         }
///     }
/// }
/// ```
///
/// ## Mathematical Correctness Guarantees
///
/// The [`IntervalSingleton`] struct maintains all essential mathematical properties:
///
/// - **Set equality**: Two singletons are equal if and only if they contain the same value
/// - **Containment**: A singleton contains another interval if and only if that interval is the same singleton
/// - **Intersection**: The intersection of a singleton with any interval is either the singleton (if contained) or empty
/// - **Measure**: The measure is always exactly zero
/// - **Compactness**: Always compact (finite sets are compact)
/// - **Closure**: The singleton is its own closure
/// - **Interior**: The interior is always empty
/// - **Boundary**: The singleton is its own boundary
///
/// These properties are preserved regardless of the scalar type used and are guaranteed
/// by the underlying implementations of the [`IntervalTrait`].
#[derive(Debug, Clone, PartialEq, Eq, IntoInner, Serialize, Deserialize)]
#[serde(bound(deserialize = "RealType: for<'a> Deserialize<'a>"))]
pub struct IntervalSingleton<RealType: RealScalar>(RealType);

impl<RealType: RealScalar> IntervalSingleton<RealType> {
    /// Get the value of the singleton.
    #[inline(always)]
    pub fn value(&self) -> &RealType {
        &self.0
    }
}

impl<RealType: RealScalar> New for IntervalSingleton<RealType> {
    fn new(value: RealType) -> Self {
        debug_assert!(value.is_finite(), "The input value {value} is not finite!");
        Self(value)
    }
}

impl<RealType: RealScalar> IntervalOperations for IntervalSingleton<RealType> {}

impl<RealType: RealScalar> Contains for IntervalSingleton<RealType> {
    /// Returns `true` if the 1D point/coordinate `x` is equal to the value of the current **singleton**.
    #[inline(always)]
    fn contains_point(&self, x: &RealType) -> bool {
        x == &self.0
    }
}

impl<RealType: RealScalar> IntervalTrait for IntervalSingleton<RealType> {}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
impl<RealType: RealScalar> IntervalBoundsRuntime for IntervalSingleton<RealType> {
    type RealType = RealType;

    #[inline(always)]
    fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<RealType>> {
        Some(IntervalBoundRuntime::Closed(LowerBoundClosed::new(
            self.value().clone(),
        )))
    }

    #[inline(always)]
    fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<RealType>> {
        Some(IntervalBoundRuntime::Closed(UpperBoundClosed::new(
            self.value().clone(),
        )))
    }
}

impl<RealType: RealScalar> IntervalBoundsRuntime for IntervalFinitePositiveLength<RealType> {
    type RealType = RealType;

    #[inline(always)]
    fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<RealType>> {
        match self {
            IntervalFinitePositiveLength::Open(interval) => interval.lower_bound_runtime(),
            IntervalFinitePositiveLength::Closed(interval) => interval.lower_bound_runtime(),
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.lower_bound_runtime()
            }
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.lower_bound_runtime()
            }
        }
    }

    #[inline(always)]
    fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<RealType>> {
        match self {
            IntervalFinitePositiveLength::Open(interval) => interval.upper_bound_runtime(),
            IntervalFinitePositiveLength::Closed(interval) => interval.upper_bound_runtime(),
            IntervalFinitePositiveLength::LowerClosedUpperOpen(interval) => {
                interval.upper_bound_runtime()
            }
            IntervalFinitePositiveLength::LowerOpenUpperClosed(interval) => {
                interval.upper_bound_runtime()
            }
        }
    }
}
//------------------------------------------------------------------------------------------------

/// Enum representing the different types of sub-intervals that can appear in a partition of a finite interval with positive length.
///
/// The [`SubIntervalInPartition`] enum encodes the **position-dependent boundary semantics** that arise
/// when partitioning an interval into adjacent, non-overlapping sub-intervals. The type of each sub-interval
/// depends on its position (first, middle, or last) and the boundary semantics of the original domain being partitioned.
///
/// ## Mathematical Foundation
///
/// When partitioning an interval domain `D` with partition points `{p₀, p₁, ..., pₙ}`, the resulting
/// sub-intervals must satisfy two critical requirements:
/// 1. **Complete coverage**: `⋃ᵢ Iᵢ = D` (union of all sub-intervals equals the original domain)
/// 2. **Non-overlapping**: `Iᵢ ∩ Iⱼ = ∅` for `i ≠ j` (disjoint interiors, at most boundary point overlap)
///
/// To achieve this while preserving the domain's boundary semantics, different sub-intervals require
/// different boundary types based on their position in the partition.
///
/// ## Core Design Philosophy
///
/// ### Why Four Variants?
/// The library uses a **partition strategy** that ensures:
/// - **Uniqueness**: Every point in the domain belongs to exactly one sub-interval
/// - **Boundary preservation**: Domain boundary semantics are maintained
/// - **Consistency**: Internal partition points never create ambiguity
///
/// This is achieved by following a specific rule: **partition points belong to the left sub-interval**
/// (except at the domain boundaries where the domain's own semantics apply).
///
/// ### The Partition Strategy
///
/// Given partition points `{p₀, p₁, ..., pₙ}` and domain `D`:
///
/// | Position | Sub-Interval Type | Mathematical Notation | Reason |
/// |----------|-------------------|----------------------|---------|
/// | **Only** (n=1) | Matches domain exactly | Depends on `D` | Single interval = domain itself |
/// | **First** (i=0) | Depends on domain | `[p₀, p₁)` for `[a,b]`/`[a,b)`; `(p₀, p₁]` for `(a,b)`/`(a,b]` | Inherits domain's boundary type |
/// | **Middle** (0<i<n-1) | Determined by `MiddleIntervalInPartition` | `[pᵢ, pᵢ₊₁)` for `[a,b]`/`[a,b)`; `(pᵢ, pᵢ₊₁]` for `(a,b)`/`(a,b]` | Avoids ambiguity at partition points |
/// | **Last** (i=n-1) | Depends on domain | `[pₙ₋₁, pₙ]` for `[a,b]`; `(pₙ₋₁, pₙ)` for `(a,b)`; `[pₙ₋₁, pₙ)` for `[a,b)`; `(pₙ₋₁, pₙ]` for `(a,b]` | Inherits domain's boundary type |
///
/// ### Why This Strategy?
/// Consider a closed domain `[0, 2]` partitioned at `{0, 1, 2}`:
///
/// **Strategy 1: All closed `[pᵢ, pᵢ₊₁]`** ❌
/// - Sub-intervals: `[0, 1]`, `[1, 2]`
/// - Problem: Point `1` belongs to **both** intervals (ambiguity!)
/// - Violates uniqueness requirement
///
/// **Strategy 2: All open `(pᵢ, pᵢ₊₁)`** ❌
/// - Sub-intervals: `(0, 1)`, `(1, 2)`
/// - Problem: Partition points `0, 1, 2` belong to **no** interval (gaps!)
/// - Violates complete coverage
///
/// **Strategy 3: Our approach (for `[a, b]` domain)** ✅
/// - Sub-intervals: `[0, 1)`, `[1, 2]`
/// - Result: Point `0 ∈ [0, 1)`, point `1 ∈ [1, 2]`, point `2 ∈ [1, 2]`
/// - Every point belongs to exactly one interval!
///
/// ## Variants
///
/// ### [`SubIntervalInPartition::Single`]
///
/// **Used when**: The partition consists of a **single interval** (n=1, meaning only 2 partition points).
///
/// **Semantics**: The sub-interval is **identical** to the original domain.
///
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use sorted_vec::partial::SortedSet;
///
/// // Single interval partition of closed domain [0, 1]
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0]);
/// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();
///
/// // The only interval matches the domain exactly
/// let only_interval = grid.interval(&IntervalId::new(0));
/// // Type: SubIntervalInPartition::Single(IntervalClosed<f64>)
/// // Result: [0, 1] - same as domain
///
/// // Single interval partition of open domain (0, 1)
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0]);
/// let grid = Grid1D::<IntervalOpen<f64>>::try_from_sorted(coords).unwrap();
///
/// // The only interval matches the domain exactly
/// let only_interval = grid.interval(&IntervalId::new(0));
/// // Type: SubIntervalInPartition::Single(IntervalOpen<f64>)
/// // Result: (0, 1) - same as domain
/// ```
///
/// **Mathematical property**: `Only(D) = D` for any domain `D`.
///
/// ### [`SubIntervalInPartition::First`]
///
/// **Used when**: This is the **leftmost** sub-interval in a multi-interval partition.
///
/// **Semantics**: The **lower bound** inherits the domain's lower boundary semantics.
/// The **inner (right) bound** type follows the domain's partition strategy.
///
/// **Type construction** — depends on the domain:
///
/// | Domain | First Interval Type | Notation |
/// |--------|---------------------|----------|
/// | `[a, b]` | `IntervalLowerClosedUpperOpen` | `[p₀, p₁)` |
/// | `(a, b)` | `IntervalLowerOpenUpperClosed` | `(p₀, p₁]` |
/// | `[a, b)` | `IntervalLowerClosedUpperOpen` | `[p₀, p₁)` |
/// | `(a, b]` | `IntervalLowerOpenUpperClosed` | `(p₀, p₁]` |
///
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use sorted_vec::partial::SortedSet;
///
/// // Closed domain [0, 2] partitioned at {0, 1, 2}
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 2.0]);
/// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();
///
/// let first_interval = grid.interval(&IntervalId::new(0));
/// // Type: SubIntervalInPartition::First(IntervalClosed<f64>)
/// // Result: [0, 1) - closed lower bound - open upper bound
/// assert!(first_interval.contains_point(&0.0)); // ✓ includes lower bound
/// assert!(!first_interval.contains_point(&1.0)); // ✗ excludes upper partition point
///
/// // Open domain (0, 2) partitioned at {0, 1, 2}
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 2.0]);
/// let grid = Grid1D::<IntervalOpen<f64>>::try_from_sorted(coords).unwrap();
///
/// let first_interval = grid.interval(&IntervalId::new(0));
/// // Type: SubIntervalInPartition::First(IntervalLowerOpenUpperClosed<f64>)
/// // Result: (0, 1] - open lower bound inherited from domain
/// assert!(!first_interval.contains_point(&0.0)); // ✗ excludes lower bound
/// assert!(first_interval.contains_point(&1.0));  // ✓ includes upper partition point
/// ```
///
/// **Inner bound convention**: For `[a, b]` and `[a, b)` domains the inner bound is open so
/// that `p₁` belongs to the **next** sub-interval. For `(a, b)` and `(a, b]` domains the inner
/// bound is closed so that `p₁` belongs to the First interval itself. Either way every partition
/// point belongs to exactly one sub-interval.
///
/// ### [`SubIntervalInPartition::Middle`]
///
/// **Used when**: This is an **interior** sub-interval (neither first nor last) in the partition.
///
/// **Semantics**: The concrete type is [`PartitionDomain1D::MiddleIntervalInPartition`](Grid1DIntervalBuilder::MiddleIntervalInPartition),
/// determined by the domain's [`Grid1DIntervalBuilder`] implementation.
///
/// | Domain | Middle Interval Type | Notation |
/// |--------|----------------------|----------|
/// | `[a, b]` | `IntervalLowerClosedUpperOpen` | `[pₖ, pₖ₊₁)` |
/// | `(a, b)` | `IntervalLowerOpenUpperClosed` | `(pₖ, pₖ₊₁]` |
/// | `[a, b)` | `IntervalLowerClosedUpperOpen` | `[pₖ, pₖ₊₁)` |
/// | `(a, b]` | `IntervalLowerOpenUpperClosed` | `(pₖ, pₖ₊₁]` |
///
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use sorted_vec::partial::SortedSet;
///
/// // Domain [0, 3] partitioned at {0, 1, 2, 3}
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 2.0, 3.0]);
/// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();
///
/// // Middle intervals: [1, 2) and [2, 3) (last is not middle!)
/// let middle_interval = grid.interval(&IntervalId::new(1));
/// // Type: SubIntervalInPartition::Middle(IntervalLowerClosedUpperOpen<f64>)
/// // Result: [1, 2)
/// assert!(middle_interval.contains_point(&1.0)); // ✓ includes left partition point
/// assert!(!middle_interval.contains_point(&2.0));  // ✗ excludes right partition point
///
/// // This prevents point 1.0 from belonging to both intervals [0, 1) and [1, 2)
/// let first_interval = grid.interval(&IntervalId::new(0));
/// assert!(!first_interval.contains_point(&1.0));   // Point 1 belongs to middle interval
/// ```
///
/// **Partition convention**: The middle interval's boundary type determines which sub-interval
/// each interior partition point belongs to:
/// - `[pₖ, pₖ₊₁)` (used by `[a,b]`, `[a,b)`): `pₖ` belongs to the **right** sub-interval
/// - `(pₖ, pₖ₊₁]` (used by `(a,b)`, `(a,b]`): `pₖ` belongs to the **left** sub-interval
///
/// Either convention guarantees that every partition point belongs to exactly one sub-interval.
/// Custom `Grid1DIntervalBuilder` implementations may use a different middle interval type,
/// provided the same uniqueness guarantee holds.
///
/// ### [`SubIntervalInPartition::Last`]
///
/// **Used when**: This is the **rightmost** sub-interval in a multi-interval partition.
///
/// **Semantics**: The **upper bound** inherits the domain's upper boundary semantics.
/// The **inner (left) bound** type follows the domain's partition strategy.
///
/// **Type construction** — depends on the domain:
///
/// | Domain | Last Interval Type | Notation |
/// |--------|-------------------|----------|
/// | `[a, b]` | `IntervalClosed` | `[pₙ₋₁, pₙ]` |
/// | `(a, b)` | `IntervalOpen` | `(pₙ₋₁, pₙ)` |
/// | `[a, b)` | `IntervalLowerClosedUpperOpen` | `[pₙ₋₁, pₙ)` |
/// | `(a, b]` | `IntervalLowerOpenUpperClosed` | `(pₙ₋₁, pₙ]` |
///
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use sorted_vec::partial::SortedSet;
///
/// // Closed domain [0, 2] partitioned at {0, 1, 2}
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 2.0]);
/// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();
///
/// let last_interval = grid.interval(&IntervalId::new(1));
/// // Type: SubIntervalInPartition::Last(IntervalClosed<f64>)
/// // Result: [1, 2] - closed upper bound inherited from domain
/// assert!(last_interval.contains_point(&1.0)); // ✓ includes left partition point
/// assert!(last_interval.contains_point(&2.0));  // ✓ includes upper bound from domain
///
/// // Semi-open domain [0, 2) partitioned at {0, 1, 2}
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 2.0]);
/// let grid = Grid1D::<IntervalLowerClosedUpperOpen<f64>>::try_from_sorted(coords).unwrap();
///
/// let last_interval = grid.interval(&IntervalId::new(1));
/// // Type: SubIntervalInPartition::Last(IntervalLowerClosedUpperOpen<f64>)
/// // Result: [1, 2) - open upper bound
/// assert!(last_interval.contains_point(&1.0)); // ✓ includes lower bound
/// assert!(!last_interval.contains_point(&2.0)); // ✗ excludes upper bound from domain
/// ```
///
/// **Inner bound convention**: For `[a, b]` and `[a, b)` domains the inner bound is closed so
/// that `pₙ₋₁` belongs to the Last interval itself. For `(a, b)` and `(a, b]` domains the inner
/// bound is open so that `pₙ₋₁` belongs to the previous sub-interval. Either way the
/// partition's uniqueness property is maintained.
///
/// ## Comprehensive Domain Examples
///
/// ### Closed Domain `[a, b]`
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use sorted_vec::partial::SortedSet;
///
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 2.0, 3.0]);
/// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();
///
/// // Partition result:
/// // - First:  [0, 1) (closed-open)
/// // - Middle: [1, 2) (closed-open)
/// // - Last:   [2, 3] (closed-closed)
///
/// let interval_0 = grid.interval(&IntervalId::new(0));
/// let interval_1 = grid.interval(&IntervalId::new(1));
/// let interval_2 = grid.interval(&IntervalId::new(2));
///
/// // Point 0 belongs only to first interval
/// use grid1d::intervals::{Contains, IntervalTrait};
/// assert!(interval_0.contains_point(&0.0));
/// assert!(!interval_1.contains_point(&0.0));
/// assert!(!interval_2.contains_point(&0.0));
///
/// // Point 1 belongs only to second interval (left boundary)
/// assert!(!interval_0.contains_point(&1.0));
/// assert!(interval_1.contains_point(&1.0));
/// assert!(!interval_2.contains_point(&1.0));
///
/// // Point 2 belongs only to last interval (left boundary)
/// assert!(!interval_0.contains_point(&2.0));
/// assert!(!interval_1.contains_point(&2.0));
/// assert!(interval_2.contains_point(&2.0));
///
/// // Point 3 belongs only to last interval (right boundary)
/// assert!(!interval_0.contains_point(&3.0));
/// assert!(!interval_1.contains_point(&3.0));
/// assert!(interval_2.contains_point(&3.0));
/// ```
///
/// ### Open Domain `(a, b)`
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use sorted_vec::partial::SortedSet;
///
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 2.0, 3.0]);
/// let grid = Grid1D::<IntervalOpen<f64>>::try_from_sorted(coords).unwrap();
///
/// // Partition result:
/// // - First:  (0, 1] (open-closed, inherits open lower from domain)
/// // - Middle: (1, 2] (open-closed)
/// // - Last:   (2, 3) (open-open, inherits open upper from domain)
///
/// let interval_0 = grid.interval(&IntervalId::new(0));
/// let interval_2 = grid.interval(&IntervalId::new(2));
///
/// // Point 0 belongs to no interval (domain excludes it)
/// assert!(!interval_0.contains_point(&0.0));
///
/// // Point 3 belongs to no interval (domain excludes it)
/// assert!(!interval_2.contains_point(&3.0));
/// ```
///
/// ### Semi-Open Domain `[a, b)`
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use sorted_vec::partial::SortedSet;
///
/// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 2.0, 3.0]);
/// let grid = Grid1D::<IntervalLowerClosedUpperOpen<f64>>::try_from_sorted(coords).unwrap();
///
/// // Partition result (all intervals share the domain's type [x, y)):
/// // - First:  [0, 1) (closed-open, inherits closed lower from domain)
/// // - Middle: [1, 2) (closed-open, partition point belongs to right interval)
/// // - Last:   [2, 3) (closed-open, inherits open upper from domain)
///
/// let interval_0 = grid.interval(&IntervalId::new(0));
/// let interval_2 = grid.interval(&IntervalId::new(2));
///
/// // Point 0 belongs to first interval (domain includes it)
/// assert!(interval_0.contains_point(&0.0));
///
/// // Point 3 belongs to no interval (domain excludes it)
/// assert!(!interval_2.contains_point(&3.0));
/// ```
///
/// ## Generic Type Parameter
///
/// ```rust,ignore
/// pub enum SubIntervalInPartition<PartitionDomain1D: Grid1DIntervalBuilder> {
///     Only(PartitionDomain1D),
///     First(PartitionDomain1D::FirstIntervalInPartition),
///     Middle(PartitionDomain1D::MiddleIntervalInPartition),
///     Last(PartitionDomain1D::LastIntervalInPartition),
/// }
/// ```
///
/// **`PartitionDomain1D`**: The type of the original domain being partitioned.
/// - Must implement [`Grid1DIntervalBuilder`] trait
/// - Determines the scalar type (`RealType`) used for coordinates
/// - Defines boundary semantics for first and last sub-intervals
///
/// ## Mathematical Guarantees
///
/// The [`SubIntervalInPartition`] enum, combined with the partition strategy, guarantees:
///
/// ### 1. Complete Coverage
/// ```text
/// ∀x ∈ D, ∃i : x ∈ Iᵢ
/// ```
/// Every point in the domain belongs to at least one sub-interval.
///
/// ### 2. Uniqueness (No Overlap)
/// ```text
/// ∀x ∈ D, |{i : x ∈ Iᵢ}| = 1
/// ```
/// Every point in the domain belongs to **exactly one** sub-interval.
///
/// ### 3. Exact Reconstruction
/// ```text
/// ⋃ᵢ Iᵢ = D
/// ```
/// The union of all sub-intervals exactly equals the original domain.
///
/// ### 4. Partition Point Assignment
/// ```text
/// ∀i ∈ (0, n-1) : pᵢ ∈ Iᵢ₋₁  (partition points belong to the left interval)
/// ```
/// Internal partition points always belong to the **left** sub-interval.
///
/// ### 5. Boundary Preservation
/// ```text
/// lower_bound(I₀) = lower_bound(D)  (semantics preserved)
/// upper_bound(Iₙ₋₁) = upper_bound(D)  (semantics preserved)
/// ```
/// Domain boundary semantics are preserved in the first and last sub-intervals.
///
/// ## Trait Implementations
///
/// The enum implements all standard interval operations through its variants:
///
/// - **[`IntervalTrait`]**: Full interval arithmetic and containment testing
/// - **[`IntervalFinitePositiveLengthTrait`]**: Length, midpoint, bounds access
/// - **[`GetLowerBoundValue`], [`GetUpperBoundValue`]**: Boundary value access
/// - **[`Contains`]**: Point containment testing
/// - **[`IntervalBoundsRuntime`]**: Runtime boundary type inspection
///
/// All operations delegate to the appropriate variant's implementation.
///
/// ## Performance Characteristics
///
/// | Operation | Time Complexity | Notes |
/// |-----------|-----------------|-------|
/// | **Variant matching** | O(1) | Single branch prediction |
/// | **Point containment** | O(1) | Delegates to concrete interval type |
/// | **Bounds access** | O(1) | Direct field access |
/// | **Length calculation** | O(1) | Cached or computed once |
/// | **Intersection** | O(1) | Delegates to interval operations |
///
/// ## Integration with Grid System
///
/// The [`SubIntervalInPartition`] enum is the **return type** for the
/// [`HasIntervals::interval`](crate::HasIntervals::interval) method, which is implemented by:
/// - [`Grid1DUniform`](crate::Grid1DUniform): Uniform spacing grids
/// - [`Grid1DNonUniform`](crate::Grid1DNonUniform): Non-uniform spacing grids
/// - [`Grid1D`](crate::Grid1D): Unified grid interface
/// - [`Grid1DUnion`](crate::Grid1DUnion): Union of multiple grids
///
/// ## Best Practices
///
/// ### Pattern Matching
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use sorted_vec::partial::SortedSet;
///
/// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(
///     SortedSet::from_unsorted(vec![0.0, 1.0, 2.0])
/// ).unwrap();
///
/// let interval = grid.interval(&IntervalId::new(0));
///
/// match interval {
///     SubIntervalInPartition::Single(domain) => {
///         println!("Single interval partition matching domain");
///     }
///     SubIntervalInPartition::First(first) => {
///         println!("First interval with inherited lower bound");
///     }
///     SubIntervalInPartition::Middle(middle) => {
///         println!("Middle interval (type depends on domain: `(a,b]` or `[a,b)` for built-in types)");
///     }
///     SubIntervalInPartition::Last(last) => {
///         println!("Last interval with inherited upper bound");
///     }
/// }
/// ```
///
/// ### Generic Operations
/// ```rust
/// use grid1d::{Grid1DIntervalBuilder, Grid1D, Grid1DTrait, intervals::*, scalars::IntervalId};
/// use sorted_vec::partial::SortedSet;
/// use num_valid::RealScalar;
///
/// fn analyze_sub_interval<T, D>(interval: &SubIntervalInPartition<D>) -> String
/// where
///     T: RealScalar,
///     D: Grid1DIntervalBuilder<RealType = T>,
///     SubIntervalInPartition<D>: IntervalFinitePositiveLengthTrait<RealType = T>,
/// {
///     format!(
///         "Interval: [{}, {}], length: {}",
///         interval.lower_bound_value(),
///         interval.upper_bound_value(),
///         interval.length()
///     )
/// }
/// ```
///
/// ## See Also
///
/// - [`Grid1DIntervalBuilder`]: Trait for constructing sub-intervals based on domain type
/// - [`Grid1DTrait`](crate::Grid1DTrait): Core trait that uses this enum for interval access
/// - [`IntervalTrait`]: Common interval operations
/// - [`Grid1D`](crate::Grid1D), [`Grid1DUniform`](crate::Grid1DUniform), [`Grid1DNonUniform`](crate::Grid1DNonUniform): Grid types that produce these sub-intervals
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound(deserialize = "PartitionDomain1D: for<'a> Deserialize<'a>"))]
pub enum SubIntervalInPartition<PartitionDomain1D: Grid1DIntervalBuilder> {
    /// A partition with a single interval covering the entire domain.
    Single(PartitionDomain1D),

    /// The first interval in a multi-interval partition.
    First(PartitionDomain1D::FirstIntervalInPartition),

    /// A middle interval in a multi-interval partition.
    /// The concrete type is [`Grid1DIntervalBuilder::MiddleIntervalInPartition`];
    /// for `[a, b]` and `[a, b)` domains this is `[a, b)`, for `(a, b)` and `(a, b]` it is `(a, b]`.
    Middle(PartitionDomain1D::MiddleIntervalInPartition),

    /// The last interval in a multi-interval partition.
    Last(PartitionDomain1D::LastIntervalInPartition),
}

impl<PartitionDomain1D: Grid1DIntervalBuilder> IntervalBoundsRuntime
    for SubIntervalInPartition<PartitionDomain1D>
{
    type RealType = PartitionDomain1D::RealType;

    #[inline]
    fn lower_bound_runtime(&self) -> Option<LowerBoundRuntime<PartitionDomain1D::RealType>> {
        match self {
            SubIntervalInPartition::Single(interval) => interval.lower_bound_runtime(),
            SubIntervalInPartition::First(interval) => interval.lower_bound_runtime(),
            SubIntervalInPartition::Middle(interval) => interval.lower_bound_runtime(),
            SubIntervalInPartition::Last(interval) => interval.lower_bound_runtime(),
        }
    }

    #[inline]
    fn upper_bound_runtime(&self) -> Option<UpperBoundRuntime<PartitionDomain1D::RealType>> {
        match self {
            SubIntervalInPartition::Single(interval) => interval.upper_bound_runtime(),
            SubIntervalInPartition::First(interval) => interval.upper_bound_runtime(),
            SubIntervalInPartition::Middle(interval) => interval.upper_bound_runtime(),
            SubIntervalInPartition::Last(interval) => interval.upper_bound_runtime(),
        }
    }
}

impl<PartitionDomain1D: Grid1DIntervalBuilder> IntervalOperations
    for SubIntervalInPartition<PartitionDomain1D>
{
}

impl<PartitionDomain1D: Grid1DIntervalBuilder> Contains
    for SubIntervalInPartition<PartitionDomain1D>
{
    #[inline(always)]
    fn contains_point(&self, x: &PartitionDomain1D::RealType) -> bool {
        match self {
            SubIntervalInPartition::Single(interval) => interval.contains_point(x),
            SubIntervalInPartition::First(interval) => interval.contains_point(x),
            SubIntervalInPartition::Middle(interval) => interval.contains_point(x),
            SubIntervalInPartition::Last(interval) => interval.contains_point(x),
        }
    }
}

impl<PartitionDomain1D: Grid1DIntervalBuilder> IntervalTrait
    for SubIntervalInPartition<PartitionDomain1D>
{
}

impl<PartitionDomain1D: Grid1DIntervalBuilder> GetLowerBoundValue
    for SubIntervalInPartition<PartitionDomain1D>
{
    type LowerBoundValue = PartitionDomain1D::RealType;

    #[inline(always)]
    fn lower_bound_value(&self) -> &Self::LowerBoundValue {
        match self {
            SubIntervalInPartition::Single(interval) => interval.lower_bound_value(),
            SubIntervalInPartition::First(interval) => interval.lower_bound_value(),
            SubIntervalInPartition::Middle(interval) => interval.lower_bound_value(),
            SubIntervalInPartition::Last(interval) => interval.lower_bound_value(),
        }
    }

    #[inline(always)]
    fn is_lower_bound_closed(&self) -> bool {
        match self {
            SubIntervalInPartition::Single(interval) => interval.is_lower_bound_closed(),
            SubIntervalInPartition::First(interval) => interval.is_lower_bound_closed(),
            SubIntervalInPartition::Middle(interval) => interval.is_lower_bound_closed(),
            SubIntervalInPartition::Last(interval) => interval.is_lower_bound_closed(),
        }
    }
}

impl<PartitionDomain1D: Grid1DIntervalBuilder> GetUpperBoundValue
    for SubIntervalInPartition<PartitionDomain1D>
{
    type UpperBoundValue = PartitionDomain1D::RealType;

    #[inline(always)]
    fn upper_bound_value(&self) -> &Self::UpperBoundValue {
        match self {
            SubIntervalInPartition::Single(interval) => interval.upper_bound_value(),
            SubIntervalInPartition::First(interval) => interval.upper_bound_value(),
            SubIntervalInPartition::Middle(interval) => interval.upper_bound_value(),
            SubIntervalInPartition::Last(interval) => interval.upper_bound_value(),
        }
    }

    /// Check if the upper bound of this sub-interval is closed (inclusive).
    ///
    /// Returns `true` if the upper boundary point is included in the interval,
    /// `false` if it is excluded.
    ///
    /// # Partition Semantics
    ///
    /// The upper bound closure depends on the variant and the partition domain type:
    ///
    /// - **`SubIntervalInPartition::Single`**: Inherits the upper bound type from the partition domain
    ///   - Closed domain `[a, b]` → closed upper bound
    ///   - Open domain `(a, b)` → open upper bound
    ///   - Half-open `[a, b)` → open upper bound
    ///
    /// - **`SubIntervalInPartition::First`**: For partitions with multiple intervals, first intervals typically
    ///   have closed upper bounds to ensure gap-free coverage. The exact type depends
    ///   on the partition domain's implementation of [`Grid1DIntervalBuilder`].
    ///
    /// - **`SubIntervalInPartition::Middle`**: Determined by [`Grid1DIntervalBuilder::MiddleIntervalInPartition`].
    ///   - For `[a, b]` and `[a, b)` domains this is `[a, b)` (open upper bound).
    ///   - For `(a, b)` and `(a, b]` domains this is `(a, b]` (closed upper bound).
    ///
    /// - **`SubIntervalInPartition::Last`**: Inherits the upper bound type from the partition domain
    ///   - Closed domain `[a, b]` → closed upper bound
    ///   - Open domain `(a, b)` → open upper bound
    ///   - Half-open `[a, b)` → open upper bound
    ///   - Half-open `(a, b]` → closed upper bound
    ///
    /// # Examples
    ///
    /// ```
    /// use grid1d::intervals::*;
    ///
    /// // Only variant with closed domain [0, 10]
    /// let only_closed: SubIntervalInPartition<IntervalClosed<f64>> =
    ///     SubIntervalInPartition::Single(IntervalClosed::new(0.0, 10.0));
    /// assert!(only_closed.is_upper_bound_closed());  // Closed upper bound
    ///
    /// // Only variant with open domain (0, 10)
    /// let only_open: SubIntervalInPartition<IntervalOpen<f64>> =
    ///     SubIntervalInPartition::Single(IntervalOpen::new(0.0, 10.0));
    /// assert!(!only_open.is_upper_bound_closed());   // Open upper bound
    ///
    /// // Middle variant: for IntervalClosed domain, MiddleIntervalInPartition = IntervalLowerClosedUpperOpen
    /// let middle: SubIntervalInPartition<IntervalClosed<f64>> =
    ///     SubIntervalInPartition::Middle(IntervalLowerClosedUpperOpen::new(3.0, 7.0));
    /// assert!(!middle.is_upper_bound_closed());
    ///
    /// // Last variant with half-open domain [0, 10)
    /// let last_half_open: SubIntervalInPartition<IntervalLowerClosedUpperOpen<f64>> =
    ///     SubIntervalInPartition::Last(IntervalLowerClosedUpperOpen::new(7.0, 10.0));
    /// assert!(!last_half_open.is_upper_bound_closed()); // Open upper bound from domain
    /// ```
    ///
    /// # 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
    #[inline(always)]
    fn is_upper_bound_closed(&self) -> bool {
        match self {
            SubIntervalInPartition::Single(interval) => interval.is_upper_bound_closed(),
            SubIntervalInPartition::First(interval) => interval.is_upper_bound_closed(),
            SubIntervalInPartition::Middle(interval) => interval.is_upper_bound_closed(),
            SubIntervalInPartition::Last(interval) => interval.is_upper_bound_closed(),
        }
    }

    /// Check if the upper bound of this sub-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).
    ///
    /// # Partition Semantics
    ///
    /// The upper bound openness depends on the variant and partition domain type:
    ///
    /// - **`SubIntervalInPartition::Single`**: Inherits from the partition domain
    ///   - Closed domain `[a, b]` → closed upper (returns `false`)
    ///   - Open domain `(a, b)` → open upper (returns `true`)
    ///   - Half-open `[a, b)` → open upper (returns `true`)
    ///   - Half-open `(a, b]` → closed upper (returns `false`)
    ///
    /// - **`SubIntervalInPartition::First`**: Typically has closed upper bounds for gap-free partitions,
    ///   so usually returns `false`. The exact behavior depends on the
    ///   [`Grid1DIntervalBuilder`] implementation.
    ///
    /// - **`SubIntervalInPartition::Middle`**: Returns `true` for `[a, b]` and `[a, b)` domains (upper bound open).
    ///   Returns `false` for `(a, b)` and `(a, b]` domains (upper bound closed). Custom
    ///   `SubIntervalInPartition::Middle` types may behave differently.
    ///
    /// - **`SubIntervalInPartition::Last`**: Inherits from the partition domain
    ///   - Closed domain → closed upper (returns `false`)
    ///   - Open domain → open upper (returns `true`)
    ///   - Half-open `[a, b)` → open upper (returns `true`)
    ///   - Half-open `(a, b]` → closed upper (returns `false
    ///
    /// # Examples
    ///
    /// ```
    /// use grid1d::intervals::*;
    ///
    /// // Only variant with half-open domain [0, 10)
    /// let only_half_open: SubIntervalInPartition<IntervalLowerClosedUpperOpen<f64>> =
    ///     SubIntervalInPartition::Single(IntervalLowerClosedUpperOpen::new(0.0, 10.0));
    /// assert!(only_half_open.is_upper_bound_open());  // Open upper bound
    ///
    /// // Middle variant: for IntervalClosed domain, MiddleIntervalInPartition = IntervalLowerClosedUpperOpen
    /// let middle: SubIntervalInPartition<IntervalClosed<f64>> =
    ///     SubIntervalInPartition::Middle(IntervalLowerClosedUpperOpen::new(3.0, 7.0));
    /// assert!(middle.is_upper_bound_open());
    ///
    /// // Verify complement relationship
    /// assert_eq!(
    ///     middle.is_upper_bound_open(),
    ///     !middle.is_upper_bound_closed()
    /// );
    /// ```
    ///
    /// # Implementation Note
    ///
    /// This method has a default implementation in [`GetUpperBoundValue`] as
    /// `!self.is_upper_bound_closed()`. It delegates to the underlying interval's
    /// implementation through pattern matching.
    ///
    /// # 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
    #[inline(always)]
    fn is_upper_bound_open(&self) -> bool {
        !self.is_upper_bound_closed()
    }
}

impl<PartitionDomain1D: Grid1DIntervalBuilder> IntervalFinitePositiveLengthTrait
    for SubIntervalInPartition<PartitionDomain1D>
{
    /// Return the inner bounds of the interval as a pair in which the first entry of the pair
    /// is the lower bound and the second entry of the pair is the upper bound.
    ///
    /// # Note
    /// This function consumes `Self` (no cloning of the bounds is needed).
    #[inline(always)]
    fn into_bounds_pair(self) -> (Self::RealType, Self::RealType) {
        match self {
            SubIntervalInPartition::Single(interval) => interval.into_bounds_pair(),
            SubIntervalInPartition::First(interval) => interval.into_bounds_pair(),
            SubIntervalInPartition::Middle(interval) => interval.into_bounds_pair(),
            SubIntervalInPartition::Last(interval) => interval.into_bounds_pair(),
        }
    }

    fn translate(&self, amount: Self::RealType) -> Self {
        match self {
            SubIntervalInPartition::Single(interval) => {
                SubIntervalInPartition::Single(interval.translate(amount))
            }
            SubIntervalInPartition::First(interval) => {
                SubIntervalInPartition::First(interval.translate(amount))
            }
            SubIntervalInPartition::Middle(interval) => {
                SubIntervalInPartition::Middle(interval.translate(amount))
            }
            SubIntervalInPartition::Last(interval) => {
                SubIntervalInPartition::Last(interval.translate(amount))
            }
        }
    }

    fn scale(&self, factor: &PositiveRealScalar<Self::RealType>) -> Self {
        match self {
            SubIntervalInPartition::Single(interval) => {
                SubIntervalInPartition::Single(interval.scale(factor))
            }
            SubIntervalInPartition::First(interval) => {
                SubIntervalInPartition::First(interval.scale(factor))
            }
            SubIntervalInPartition::Middle(interval) => {
                SubIntervalInPartition::Middle(interval.scale(factor))
            }
            SubIntervalInPartition::Last(interval) => {
                SubIntervalInPartition::Last(interval.scale(factor))
            }
        }
    }
    fn expand(&self, amount: &PositiveRealScalar<Self::RealType>) -> Self {
        match self {
            SubIntervalInPartition::Single(interval) => {
                SubIntervalInPartition::Single(interval.expand(amount))
            }
            SubIntervalInPartition::First(interval) => {
                SubIntervalInPartition::First(interval.expand(amount))
            }
            SubIntervalInPartition::Middle(interval) => {
                SubIntervalInPartition::Middle(interval.expand(amount))
            }
            SubIntervalInPartition::Last(interval) => {
                SubIntervalInPartition::Last(interval.expand(amount))
            }
        }
    }
}

// IntervalFinitePositiveLength hull implementation
impl<RealType: RealScalar, I2: IntervalFinitePositiveLengthTrait<RealType = RealType>>
    IntervalHull<I2> for IntervalFinitePositiveLength<RealType>
{
    type Output = IntervalFinitePositiveLength<RealType>;

    #[inline]
    fn hull(&self, other: &I2) -> Self::Output {
        compute_hull_bounded_intervals(self, other)
    }
}