grid1d 0.5.2

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
#![deny(rustdoc::broken_intra_doc_links)]

//! Runtime-dispatched bound representation for dynamic or serialization-driven contexts.
//!
//! This module provides [`IntervalBoundRuntime<RealType, Side>`] — an enum whose
//! `Open`/`Closed` variant is chosen at runtime rather than encoded in the type.
//! It complements the compile-time bound types when the boundary inclusion semantics
//! are not known until runtime (e.g. user input, deserialization, configuration files).
//!
//! ## Types
//!
//! | Type | Description |
//! |------|-------------|
//! | [`IntervalBoundRuntime<T, Side>`] | Enum with `Open(IntervalBound<T, Side, Open>)` and `Closed(IntervalBound<T, Side, Closed>)` variants |
//! | [`LowerBoundRuntime<T>`] | Type alias for `IntervalBoundRuntime<T, Lower>` |
//! | [`UpperBoundRuntime<T>`] | Type alias for `IntervalBoundRuntime<T, Upper>` |
//!
//! ## When to Use
//!
//! Prefer the compile-time typed bounds ([`LowerBoundClosed`](crate::bounds::LowerBoundClosed),
//! [`UpperBoundOpen`](crate::bounds::UpperBoundOpen), etc.) whenever the open/closed nature is
//! known at compile time — they are zero-cost abstractions with stronger type guarantees.
//! Use the runtime enum when:
//!
//! - Constructing bounds from user input or configuration
//! - Deserializing bounds from JSON / other formats
//! - Writing algorithms that must handle both open and closed bounds generically
//!
//! ## Example
//!
//! ```rust
//! use grid1d::bounds::*;
//! use try_create::New;
//!
//! fn make_lower(value: f64, closed: bool) -> LowerBoundRuntime<f64> {
//!     if closed {
//!         IntervalBoundRuntime::Closed(LowerBoundClosed::new(value))
//!     } else {
//!         IntervalBoundRuntime::Open(LowerBoundOpen::new(value))
//!     }
//! }
//!
//! let b = make_lower(0.0, true);
//! assert!(b.is_closed());
//! assert!(b.value_within_bound(&0.0));
//! ```

use crate::bounds::{
    IntervalBound,
    markers::{Closed, Lower, Open, Upper},
    traits::{BoundChecks, BoundSide, BoundSideChecks, BoundTypeChecks, ValueWithinBound},
};
use duplicate::duplicate_item;
use num_valid::RealScalar;
use serde::{Deserialize, Serialize};
use std::{cmp::Ordering, fmt::Debug};
use try_create::{IntoInner, New};

//------------------------------------------------------------------------------------------------
/// Runtime-determined bound type that can be either open or closed.
///
/// [`IntervalBoundRuntime<RealType, Side>`] provides a unified enum for representing bounds
/// where the open/closed nature needs to be determined at runtime rather than
/// compile time. This is essential for dynamic interval construction, serialization,
/// configuration-driven applications, and algorithms that need to work with varying
/// boundary semantics.
///
/// ## Design Philosophy
///
/// ### Compile-Time vs Runtime Trade-offs
///
/// Unlike the compile-time typed bounds ([`LowerBoundOpen`](crate::bounds::LowerBoundOpen), [`LowerBoundClosed`](crate::bounds::LowerBoundClosed), etc.),
/// this enum moves the open/closed distinction from compile time to runtime:
///
/// | Aspect | Compile-Time Bounds | Runtime Bounds |
/// |--------|-------------------|----------------|
/// | **Type Safety** | ✅ Cannot mix open/closed at compile time | ❌ Open/closed confusion possible |
/// | **Performance** | ✅ Zero-cost abstractions, inlined | ⚡ Small pattern matching overhead |
/// | **Flexibility** | ❌ Fixed at compile time | ✅ Can change dynamically |
/// | **Serialization** | ❌ Complex (type information lost) | ✅ Natural enum serialization |
/// | **User Input** | ❌ Requires compile-time knowledge | ✅ Can handle dynamic input |
///
/// ### When to Use Runtime Bounds
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // ✅ GOOD: Dynamic interval construction from user input
/// fn create_bound_from_config(value: f64, is_closed: bool) -> LowerBoundRuntime<f64> {
///     if is_closed {
///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(value))
///     } else {
///         IntervalBoundRuntime::Open(LowerBoundOpen::new(value))
///     }
/// }
///
/// // ✅ GOOD: Serialization scenarios
/// let bound = create_bound_from_config(0.0, true);
/// let serialized = serde_json::to_string(&bound).unwrap();
/// let deserialized: LowerBoundRuntime<f64> = serde_json::from_str(&serialized).unwrap();
///
/// // ❌ AVOID: When bound type is known at compile time
/// fn bad_usage() -> LowerBoundRuntime<f64> {
///     // This should just be LowerBoundClosed::new(0.0)
///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0))
/// }
/// ```
///
/// ## Type Parameters
///
/// - **`RealType`**: Any scalar type implementing [`num_valid::RealScalar`]
/// - **`Side`**: Either [`Lower`] or [`Upper`] boundary side marker
///
/// ## Variants
///
/// ### [`IntervalBoundRuntime::Open`]
///
/// Contains an open bound that excludes the boundary value:
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let open_lower = IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));
/// let open_upper = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));
///
/// // Open bounds exclude their boundary values
/// assert!(!open_lower.value_within_bound(&5.0));   // 5 > 5 → false
/// assert!(!open_upper.value_within_bound(&10.0));  // 10 < 10 → false
///
/// // But include nearby values
/// assert!(open_lower.value_within_bound(&5.1));    // 5.1 > 5 → true
/// assert!(open_upper.value_within_bound(&9.9));    // 9.9 < 10 → true
/// ```
///
/// ### [`IntervalBoundRuntime::Closed`]
///
/// Contains a closed bound that includes the boundary value:
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let closed_lower = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
/// let closed_upper = IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0));
///
/// // Closed bounds include their boundary values
/// assert!(closed_lower.value_within_bound(&5.0));   // 5 ≥ 5 → true
/// assert!(closed_upper.value_within_bound(&10.0));  // 10 ≤ 10 → true
///
/// // And also include nearby values
/// assert!(closed_lower.value_within_bound(&5.1));   // 5.1 ≥ 5 → true
/// assert!(closed_upper.value_within_bound(&9.9));   // 9.9 ≤ 10 → true
/// ```
///
/// ## Type Aliases for Convenience
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Specific side aliases for cleaner code
/// type LowerBoundRuntime<T> = IntervalBoundRuntime<T, Lower>;
/// type UpperBoundRuntime<T> = IntervalBoundRuntime<T, Upper>;
///
/// // Usage examples
/// let lower: LowerBoundRuntime<f64> = IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0));
/// let upper: UpperBoundRuntime<f64> = IntervalBoundRuntime::Open(UpperBoundOpen::new(1.0));
/// ```
///
/// ## Core Operations
///
/// ### Boundary Constraint Testing
///
/// All runtime bounds implement [`BoundTypeChecks`] and provide constraint validation:
///
/// ```rust
/// use grid1d::bounds::*;
/// use num_valid::RealScalar;
/// use try_create::New;
///
/// fn test_constraint<T: RealScalar>(
///     bound: &IntervalBoundRuntime<T, Lower>,
///     test_value: &T
/// ) -> bool {
///     match bound {
///         IntervalBoundRuntime::Open(open_bound) => {
///             open_bound.value_within_bound(test_value)  // x > bound_value
///         }
///         IntervalBoundRuntime::Closed(closed_bound) => {
///             closed_bound.value_within_bound(test_value)  // x ≥ bound_value
///         }
///     }
/// }
///
/// let open_bound = IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));
/// let closed_bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
///
/// assert!(!test_constraint(&open_bound, &5.0));    // 5 > 5 → false
/// assert!(test_constraint(&closed_bound, &5.0));   // 5 ≥ 5 → true
/// ```
///
/// ### Value Access and Manipulation
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::{New, IntoInner};
///
/// let bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(3.14));
///
/// // Access the underlying value
/// let value_ref: &f64 = bound.as_ref();
/// assert_eq!(*value_ref, 3.14);
///
/// // Extract the value (consuming the bound)
/// let value: f64 = bound.into_inner();
/// assert_eq!(value, 3.14);
/// ```
///
/// ### Type Information Queries
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let open_bound = IntervalBoundRuntime::Open(LowerBoundOpen::new(1.0));
/// let closed_bound = IntervalBoundRuntime::Closed(UpperBoundClosed::new(2.0));
///
/// // Query boundary inclusion behavior
/// assert!(open_bound.is_open());
/// assert!(!open_bound.is_closed());
/// assert!(!open_bound.includes_boundary());
///
/// assert!(!closed_bound.is_open());
/// assert!(closed_bound.is_closed());
/// assert!(closed_bound.includes_boundary());
/// ```
///
/// ## Conversion Patterns
///
/// ### From Compile-Time to Runtime Bounds
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Automatic conversion via From trait
/// let compile_time_bound = LowerBoundClosed::new(5.0);
/// let runtime_bound: LowerBoundRuntime<f64> = compile_time_bound.into();
///
/// match runtime_bound {
///     IntervalBoundRuntime::Closed(bound) => {
///         println!("Converted to runtime closed bound: {}", bound.as_ref());
///     }
///     IntervalBoundRuntime::Open(_) => unreachable!(),
/// }
/// ```
///
/// ### Collection of Mixed Bound Types
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Store different bound types in the same collection
/// let bounds: Vec<LowerBoundRuntime<f64>> = vec![
///     LowerBoundClosed::new(0.0).into(),
///     LowerBoundOpen::new(1.0).into(),
///     LowerBoundClosed::new(2.0).into(),
///     LowerBoundOpen::new(3.0).into(),
/// ];
///
/// // Process them uniformly
/// for (i, bound) in bounds.iter().enumerate() {
///     let inclusion = if bound.is_closed() { "includes" } else { "excludes" };
///     println!("Bound {}: {} (value {})", i, inclusion, bound.as_ref());
/// }
/// ```
///
/// ## Mathematical Ordering
///
/// Runtime bounds maintain the same mathematical ordering as their compile-time counterparts:
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let closed_lower = LowerBoundRuntime::Closed(LowerBoundClosed::new(5.0));
/// let open_lower = LowerBoundRuntime::Open(LowerBoundOpen::new(5.0));
///
/// // For lower bounds: closed is "tighter" than open
/// assert!(closed_lower < open_lower);  // [5 < (5
///
/// let open_upper = UpperBoundRuntime::Open(UpperBoundOpen::new(5.0));
/// let closed_upper = UpperBoundRuntime::Closed(UpperBoundClosed::new(5.0));
///
/// // For upper bounds: open is "tighter" than closed
/// assert!(open_upper < closed_upper);  // 5) < 5]
/// ```
///
/// ## Serialization Support
///
/// Runtime bounds have natural serialization support via `serde`:
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
/// use serde_json;
///
/// let bounds = vec![
///     LowerBoundRuntime::Closed(LowerBoundClosed::new(0.0)),
///     LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)),
/// ];
///
/// // Serialize to JSON
/// let json = serde_json::to_string_pretty(&bounds).unwrap();
/// println!("Serialized bounds:\n{}", json);
///
/// // Deserialize back
/// let deserialized: Vec<LowerBoundRuntime<f64>> =
///     serde_json::from_str(&json).unwrap();
///
/// assert_eq!(bounds.len(), deserialized.len());
/// for (original, restored) in bounds.iter().zip(deserialized.iter()) {
///     assert_eq!(original.as_ref(), restored.as_ref());
///     assert_eq!(original.is_closed(), restored.is_closed());
/// }
/// ```
///
/// ## Advanced Usage Patterns
///
/// ### Dynamic Interval Construction
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// struct IntervalConfig {
///     lower_value: f64,
///     lower_closed: bool,
///     upper_value: f64,
///     upper_closed: bool,
/// }
///
/// fn create_dynamic_interval(config: IntervalConfig) -> (LowerBoundRuntime<f64>, UpperBoundRuntime<f64>) {
///     let lower = if config.lower_closed {
///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(config.lower_value))
///     } else {
///         IntervalBoundRuntime::Open(LowerBoundOpen::new(config.lower_value))
///     };
///     
///     let upper = if config.upper_closed {
///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(config.upper_value))
///     } else {
///         IntervalBoundRuntime::Open(UpperBoundOpen::new(config.upper_value))
///     };
///     
///     (lower, upper)
/// }
///
/// // Create different interval types from configuration
/// let closed_interval = create_dynamic_interval(IntervalConfig {
///     lower_value: 0.0, lower_closed: true,
///     upper_value: 1.0, upper_closed: true,
/// }); // Represents [0, 1]
///
/// let half_open_interval = create_dynamic_interval(IntervalConfig {
///     lower_value: 0.0, lower_closed: true,
///     upper_value: 1.0, upper_closed: false,
/// }); // Represents [0, 1)
/// ```
///
/// ### Generic Algorithm Implementation
///
/// ```rust
/// use grid1d::bounds::*;
/// use num_valid::RealScalar;
/// use try_create::New;
///
/// fn find_overlapping_bounds<T: RealScalar + std::fmt::Display>(
///     bounds: &[IntervalBoundRuntime<T, Lower>],
///     test_value: &T
/// ) -> Vec<usize> {
///     bounds.iter()
///         .enumerate()
///         .filter_map(|(i, bound)| {
///             let satisfies = match bound {
///                 IntervalBoundRuntime::Open(open_bound) => {
///                     open_bound.value_within_bound(test_value)
///                 }
///                 IntervalBoundRuntime::Closed(closed_bound) => {
///                     closed_bound.value_within_bound(test_value)
///                 }
///             };
///             if satisfies { Some(i) } else { None }
///         })
///         .collect()
/// }
///
/// let bounds = vec![
///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0)),  // [0 - includes 0.0
///     IntervalBoundRuntime::Open(LowerBoundOpen::new(0.0)),      // (0 - excludes 0.0
///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(1.0)),  // [1 - excludes 0.0
/// ];
///
/// let overlapping = find_overlapping_bounds(&bounds, &0.0);
/// assert_eq!(overlapping, vec![0]); // Only the closed bound includes 0.0
/// ```
///
/// ## Performance Characteristics
///
/// ### Memory Layout
/// - **Size**: Same as underlying [`IntervalBound`] plus enum discriminant
/// - **Alignment**: Natural alignment of the largest variant
/// - **Overhead**: One byte discriminant plus potential padding
///
/// ### Operation Complexity
/// | Operation | Time | Notes |
/// |-----------|------|-------|
/// | Construction | O(1) | Simple enum wrapping |
/// | Pattern matching | O(1) | Compile-time branch prediction |
/// | Value access | O(1) | Direct field access |
/// | Constraint testing | O(1) | Inlined comparison operations |
/// | Serialization | O(1) | Direct enum serialization |
///
/// ### Performance vs Compile-Time Bounds
///
/// ```rust
/// use grid1d::bounds::*;
///
/// // Runtime bounds: small pattern matching overhead
/// fn check_runtime_bound(bound: &LowerBoundRuntime<f64>, value: f64) -> bool {
///     match bound {  // Small branching cost
///         IntervalBoundRuntime::Open(b) => value > *b.as_ref(),
///         IntervalBoundRuntime::Closed(b) => value >= *b.as_ref(),
///     }
/// }
///
/// // Compile-time bounds: zero overhead
/// fn check_compile_time_bound<T: BoundType>(bound: &LowerBound<f64, T>, value: f64) -> bool {
///     if T::is_open() {
///         value > *bound.as_ref()  // Optimized to direct comparison
///     } else {
///         value >= *bound.as_ref() // Optimized to direct comparison
///     }
/// }
/// ```
///
/// ## Best Practices
///
/// ### When to Use Runtime Bounds
/// - ✅ **User input**: Boundary types determined by configuration
/// - ✅ **Serialization**: Saving/loading interval data
/// - ✅ **Dynamic algorithms**: Boundary types vary during execution
/// - ✅ **Heterogeneous collections**: Storing different bound types together
///
/// ### When to Use Compile-Time Bounds
/// - ✅ **Known constraints**: Boundary types fixed at compile time
/// - ✅ **Performance critical**: Zero-overhead abstractions required
/// - ✅ **Type safety**: Prevent mixing incompatible boundary types
/// - ✅ **Generic algorithms**: Type-parameterized over boundary semantics
///
/// ### Conversion Strategy
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Pattern: Convert from runtime to compile-time when possible
/// fn extract_closed_bound(bound: LowerBoundRuntime<f64>) -> Option<LowerBoundClosed<f64>> {
///     match bound {
///         IntervalBoundRuntime::Closed(closed_bound) => Some(closed_bound),
///         IntervalBoundRuntime::Open(_) => None,
///     }
/// }
///
/// // Pattern: Use runtime bounds at API boundaries, compile-time internally
/// fn process_user_interval(
///     lower: LowerBoundRuntime<f64>,
///     upper: UpperBoundRuntime<f64>
/// ) -> String {
///     match (lower, upper) {
///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Closed(u)) => {
///             process_closed_interval(l, u)  // Delegate to compile-time version
///         }
///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Open(u)) => {
///             process_open_interval(l, u)    // Delegate to compile-time version
///         }
///         // Handle mixed cases...
///         _ => "Mixed interval types".to_string(),
///     }
/// }
///
/// fn process_closed_interval(
///     lower: LowerBoundClosed<f64>,
///     upper: UpperBoundClosed<f64>
/// ) -> String {
///     format!("Closed interval: [{}, {}]", lower.as_ref(), upper.as_ref())
/// }
///
/// fn process_open_interval(
///     lower: LowerBoundOpen<f64>,
///     upper: UpperBoundOpen<f64>
/// ) -> String {
///     format!("Open interval: ({}, {})", lower.as_ref(), upper.as_ref())
/// }
/// ```
///
/// ## Integration with Grid1D
///
/// Runtime bounds integrate seamlessly with the broader grid1d ecosystem:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use try_create::{IntoInner, New};
///
/// // Convert runtime bounds to actual intervals when needed
/// fn runtime_bounds_to_interval(
///     lower: LowerBoundRuntime<f64>,
///     upper: UpperBoundRuntime<f64>
/// ) -> Box<dyn std::fmt::Debug> {
///     match (lower, upper) {
///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Closed(u)) => {
///             Box::new(IntervalClosed::new(l.into_inner(), u.into_inner()))
///         }
///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Open(u)) => {
///             Box::new(IntervalOpen::new(l.into_inner(), u.into_inner()))
///         }
///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Open(u)) => {
///             Box::new(IntervalLowerClosedUpperOpen::new(l.into_inner(), u.into_inner()))
///         }
///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Closed(u)) => {
///             Box::new(IntervalLowerOpenUpperClosed::new(l.into_inner(), u.into_inner()))
///         }
///     }
/// }
/// ```
///
/// The [`IntervalBoundRuntime`] enum provides essential flexibility for dynamic interval
/// construction while maintaining mathematical correctness and integration with the
/// grid1d type system. Use it when runtime flexibility is needed, but prefer
/// compile-time bounds when the boundary semantics are known statically.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound(deserialize = "RealType: for<'a> Deserialize<'a>"))]
pub enum IntervalBoundRuntime<RealType: RealScalar, Side: BoundSide> {
    /// An open (exclusive) interval bound.
    Open(IntervalBound<RealType, Side, Open>),
    /// A closed (inclusive) interval bound.
    Closed(IntervalBound<RealType, Side, Closed>),
}

impl<RealType: RealScalar, Side: BoundSide> IntervalBoundRuntime<RealType, Side> {
    /// Create a new open (exclusive) runtime bound.
    ///
    /// This is a convenience constructor that creates an open bound variant without
    /// requiring explicit construction of the underlying [`IntervalBound`].
    ///
    /// # Mathematical Meaning
    ///
    /// - For **lower bounds**: Creates `x > value` constraint (excludes the boundary)
    /// - For **upper bounds**: Creates `x < value` constraint (excludes the boundary)
    ///
    /// # Examples
    ///
    /// ## Lower Bound
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let lower_open: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
    ///
    /// // Excludes the boundary value
    /// assert!(!lower_open.value_within_bound(&5.0));  // 5 > 5 → false
    /// assert!(lower_open.value_within_bound(&5.1));   // 5.1 > 5 → true
    /// assert!(!lower_open.value_within_bound(&4.9));  // 4.9 > 5 → false
    ///
    /// assert!(lower_open.is_open());
    /// assert!(lower_open.is_open_variant());
    /// ```
    ///
    /// ## Upper Bound
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let upper_open: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_open(10.0);
    ///
    /// // Excludes the boundary value
    /// assert!(!upper_open.value_within_bound(&10.0));  // 10 < 10 → false
    /// assert!(upper_open.value_within_bound(&9.9));    // 9.9 < 10 → true
    /// assert!(!upper_open.value_within_bound(&10.1));  // 10.1 < 10 → false
    ///
    /// assert!(upper_open.is_open());
    /// assert!(upper_open.is_open_variant());
    /// ```
    ///
    /// ## Comparison with Manual Construction
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    /// use try_create::New;
    ///
    /// // Using convenience constructor (cleaner)
    /// let bound1: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
    ///
    /// // Manual construction (more verbose)
    /// let bound2: LowerBoundRuntime<f64> =
    ///     IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));
    ///
    /// assert_eq!(bound1, bound2);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`new_closed`](Self::new_closed) - Create a closed (inclusive) bound
    /// - [`is_open_variant`](Self::is_open_variant) - Check if bound is open
    #[must_use]
    pub fn new_open(value: RealType) -> Self {
        Self::Open(IntervalBound::<RealType, Side, Open>::new(value))
    }

    /// Create a new closed (inclusive) runtime bound.
    ///
    /// This is a convenience constructor that creates a closed bound variant without
    /// requiring explicit construction of the underlying [`IntervalBound`].
    ///
    /// # Mathematical Meaning
    ///
    /// - For **lower bounds**: Creates `x ≥ value` constraint (includes the boundary)
    /// - For **upper bounds**: Creates `x ≤ value` constraint (includes the boundary)
    ///
    /// # Examples
    ///
    /// ## Lower Bound
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let lower_closed: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
    ///
    /// // Includes the boundary value
    /// assert!(lower_closed.value_within_bound(&5.0));  // 5 ≥ 5 → true
    /// assert!(lower_closed.value_within_bound(&5.1));  // 5.1 ≥ 5 → true
    /// assert!(!lower_closed.value_within_bound(&4.9)); // 4.9 ≥ 5 → false
    ///
    /// assert!(lower_closed.is_closed());
    /// assert!(lower_closed.is_closed_variant());
    /// ```
    ///
    /// ## Upper Bound
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let upper_closed: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_closed(10.0);
    ///
    /// // Includes the boundary value
    /// assert!(upper_closed.value_within_bound(&10.0));  // 10 ≤ 10 → true
    /// assert!(upper_closed.value_within_bound(&9.9));   // 9.9 ≤ 10 → true
    /// assert!(!upper_closed.value_within_bound(&10.1)); // 10.1 ≤ 10 → false
    ///
    /// assert!(upper_closed.is_closed());
    /// assert!(upper_closed.is_closed_variant());
    /// ```
    ///
    /// ## Comparison with Manual Construction
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    /// use try_create::New;
    ///
    /// // Using convenience constructor (cleaner)
    /// let bound1: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
    ///
    /// // Manual construction (more verbose)
    /// let bound2: LowerBoundRuntime<f64> =
    ///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
    ///
    /// assert_eq!(bound1, bound2);
    /// ```
    ///
    /// # See Also
    ///
    /// - [`new_open`](Self::new_open) - Create an open (exclusive) bound
    /// - [`is_closed_variant`](Self::is_closed_variant) - Check if bound is closed
    #[must_use]
    pub fn new_closed(value: RealType) -> Self {
        Self::Closed(IntervalBound::<RealType, Side, Closed>::new(value))
    }

    /// Check if this runtime bound is a closed variant without consuming it.
    ///
    /// This method provides a non-consuming way to check the bound type, which is useful
    /// when you need to inspect the bound type without pattern matching or when you want
    /// to check the type multiple times.
    ///
    /// # Returns
    ///
    /// - `true` if the bound is [`IntervalBoundRuntime::Closed`]
    /// - `false` if the bound is [`IntervalBoundRuntime::Open`]
    ///
    /// # Performance
    ///
    /// This is a zero-cost check that compiles to a simple discriminant comparison.
    ///
    /// # Examples
    ///
    /// ## Basic Usage
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let closed_bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
    /// let open_bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
    ///
    /// assert!(closed_bound.is_closed_variant());
    /// assert!(!open_bound.is_closed_variant());
    /// ```
    ///
    /// ## Conditional Logic
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// fn describe_bound(bound: &LowerBoundRuntime<f64>) -> String {
    ///     let inclusion = if bound.is_closed_variant() {
    ///         "inclusive"
    ///     } else {
    ///         "exclusive"
    ///     };
    ///     format!("Lower bound at {} ({})", bound.as_ref(), inclusion)
    /// }
    ///
    /// let bound = IntervalBoundRuntime::new_closed(10.0);
    /// assert_eq!(describe_bound(&bound), "Lower bound at 10 (inclusive)");
    /// ```
    ///
    /// ## Difference from `is_closed()` Trait Method
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
    ///
    /// // Both return the same result
    /// assert_eq!(bound.is_closed_variant(), bound.is_closed());
    ///
    /// // is_closed_variant() is more explicit about checking the enum variant
    /// // is_closed() comes from the BoundTypeChecks trait
    /// ```
    ///
    /// # See Also
    ///
    /// - [`is_open_variant`](Self::is_open_variant) - Check if bound is open
    /// - [`is_closed`](BoundTypeChecks::is_closed) - Trait method for same check
    /// - [`new_closed`](Self::new_closed) - Create a closed bound
    #[inline(always)]
    pub fn is_closed_variant(&self) -> bool {
        matches!(self, Self::Closed(_))
    }

    /// Check if this runtime bound is an open variant without consuming it.
    ///
    /// This method provides a non-consuming way to check the bound type, which is useful
    /// when you need to inspect the bound type without pattern matching or when you want
    /// to check the type multiple times.
    ///
    /// # Returns
    ///
    /// - `true` if the bound is [`IntervalBoundRuntime::Open`]
    /// - `false` if the bound is [`IntervalBoundRuntime::Closed`]
    ///
    /// # Performance
    ///
    /// This is a zero-cost check that compiles to a simple discriminant comparison.
    ///
    /// # Examples
    ///
    /// ## Basic Usage
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let open_bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
    /// let closed_bound: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(5.0);
    ///
    /// assert!(open_bound.is_open_variant());
    /// assert!(!closed_bound.is_open_variant());
    /// ```
    ///
    /// ## Conditional Logic
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// fn describe_constraint(bound: &UpperBoundRuntime<f64>) -> String {
    ///     let symbol = if bound.is_open_variant() { "<" } else { "≤" };
    ///     format!("x {} {}", symbol, bound.as_ref())
    /// }
    ///
    /// let bound = IntervalBoundRuntime::new_open(100.0);
    /// assert_eq!(describe_constraint(&bound), "x < 100");
    /// ```
    ///
    /// ## Collecting by Type
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let bounds = vec![
    ///     LowerBoundRuntime::new_open(1.0),
    ///     LowerBoundRuntime::new_closed(2.0),
    ///     LowerBoundRuntime::new_open(3.0),
    ///     LowerBoundRuntime::new_closed(4.0),
    /// ];
    ///
    /// let open_count = bounds.iter().filter(|b| b.is_open_variant()).count();
    /// let closed_count = bounds.iter().filter(|b| b.is_closed_variant()).count();
    ///
    /// assert_eq!(open_count, 2);
    /// assert_eq!(closed_count, 2);
    /// ```
    ///
    /// ## Difference from `is_open()` Trait Method
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let bound: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
    ///
    /// // Both return the same result
    /// assert_eq!(bound.is_open_variant(), bound.is_open());
    ///
    /// // is_open_variant() is more explicit about checking the enum variant
    /// // is_open() comes from the BoundTypeChecks trait
    /// ```
    ///
    /// # See Also
    ///
    /// - [`is_closed_variant`](Self::is_closed_variant) - Check if bound is closed
    /// - [`is_open`](BoundTypeChecks::is_open) - Trait method for same check
    /// - [`new_open`](Self::new_open) - Create an open bound
    #[inline(always)]
    pub fn is_open_variant(&self) -> bool {
        matches!(self, Self::Open(_))
    }

    /// Convert this bound to the opposite bound type, preserving the value.
    ///
    /// This method transforms an open bound to a closed bound with the same value, or vice versa.
    /// The side (lower/upper) is preserved - only the inclusion/exclusion semantics change.
    ///
    /// # Mathematical Meaning
    ///
    /// ## For Lower Bounds
    /// - **Open → Closed**: `(a` becomes `[a` — changes `x > a` to `x ≥ a`
    /// - **Closed → Open**: `[a` becomes `(a` — changes `x ≥ a` to `x > a`
    ///
    /// ## For Upper Bounds
    /// - **Open → Closed**: `b)` becomes `b]` — changes `x < b` to `x ≤ b`
    /// - **Closed → Open**: `b]` becomes `b)` — changes `x ≤ b` to `x < b`
    ///
    /// # Use Cases
    ///
    /// This method is particularly useful when:
    /// - Adjusting interval boundaries in set difference operations
    /// - Converting between interval types (e.g., `[a, b)` ↔ `(a, b]`)
    /// - Implementing boundary adjustments in computational geometry
    /// - Handling boundary conditions in numerical algorithms
    ///
    /// # Examples
    ///
    /// ## Lower Bound Conversion
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let open_lower: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
    ///
    /// // Check properties before conversion
    /// assert!(open_lower.is_open_variant());
    /// assert!(!open_lower.value_within_bound(&5.0));   // 5 > 5 → false
    ///
    /// // Convert (consumes original)
    /// let closed_lower = open_lower.flip_bound_type();
    ///
    /// // Value is preserved
    /// assert_eq!(*closed_lower.as_ref(), 5.0);
    ///
    /// // But semantics change
    /// assert!(closed_lower.is_closed_variant());
    /// assert!(closed_lower.value_within_bound(&5.0));  // 5 ≥ 5 → true
    /// ```
    ///
    /// ## Upper Bound Conversion
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let closed_upper: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_closed(10.0);
    ///
    /// // Check properties before conversion
    /// assert!(closed_upper.is_closed_variant());
    /// assert!(closed_upper.value_within_bound(&10.0));  // 10 ≤ 10 → true
    ///
    /// // Convert (consumes original)
    /// let open_upper = closed_upper.flip_bound_type();
    ///
    /// // Value is preserved
    /// assert_eq!(*open_upper.as_ref(), 10.0);
    ///
    /// // But semantics change
    /// assert!(open_upper.is_open_variant());
    /// assert!(!open_upper.value_within_bound(&10.0));   // 10 < 10 → false
    /// ```
    ///
    /// ## Interval Boundary Adjustment
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// // When computing interval difference A \ B, we often need to flip boundaries
    /// // If B has lower bound [b, we need to create upper bound b) for the left remainder
    /// let b_lower: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(3.0);  // [3
    /// let left_upper = b_lower.flip_bound_type();            // 3) — exclude what B includes
    ///
    /// // Similarly for upper bounds
    /// let b_upper: UpperBoundRuntime<f64> = IntervalBoundRuntime::new_open(7.0);    // 7)
    /// let right_lower = b_upper.flip_bound_type();          // [7 — include what B excludes
    ///
    /// assert!(left_upper.is_open_variant());
    /// assert!(right_lower.is_closed_variant());
    /// ```
    ///
    /// ## Round-Trip Consistency
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let original: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_closed(2.5);
    ///
    /// // Save properties for comparison
    /// let original_value = *original.as_ref();
    /// let was_closed = original.is_closed_variant();
    ///
    /// // Double flip restores the type
    /// let flipped = original.flip_bound_type();
    /// let restored = flipped.flip_bound_type();
    ///
    /// // Value preserved through transformations
    /// assert_eq!(*restored.as_ref(), original_value);
    ///
    /// // Type restored
    /// assert_eq!(was_closed, restored.is_closed_variant());
    /// ```
    ///
    /// ## Dynamic Interval Adjustment
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// fn adjust_boundary_for_exclusion(bound: LowerBoundRuntime<f64>) -> LowerBoundRuntime<f64> {
    ///     // Convert any lower bound to open (exclusive) form
    ///     if bound.is_closed_variant() {
    ///         bound.flip_bound_type()
    ///     } else {
    ///         bound
    ///     }
    /// }
    ///
    /// let closed = IntervalBoundRuntime::new_closed(1.0);
    /// let open = adjust_boundary_for_exclusion(closed);
    ///
    /// assert!(!open.value_within_bound(&1.0));  // Now excludes the boundary
    /// assert!(open.value_within_bound(&1.1));   // But includes values above
    /// ```
    ///
    /// # Performance
    ///
    /// This is an O(1) operation that:
    /// - Extracts the underlying scalar value (moving it)
    /// - Constructs a new enum variant
    /// - Has no allocations or clones
    ///
    /// For `Copy` types like `f64`, this is a single register move. For non-`Copy` types,
    /// it moves the value without cloning.
    ///
    /// If you need to preserve the original bound, clone it before calling this method:
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let original: LowerBoundRuntime<f64> = IntervalBoundRuntime::new_open(5.0);
    /// let flipped = original.clone().flip_bound_type();  // Keep original
    ///
    /// assert!(original.is_open_variant());
    /// assert!(flipped.is_closed_variant());
    /// ```
    ///
    /// # See Also
    ///
    /// - [`new_open`](Self::new_open) - Create an open bound
    /// - [`new_closed`](Self::new_closed) - Create a closed bound
    /// - [`is_open_variant`](Self::is_open_variant) - Check if bound is open
    /// - [`is_closed_variant`](Self::is_closed_variant) - Check if bound is closed
    #[inline(always)]
    pub fn flip_bound_type(self) -> Self {
        match self {
            Self::Open(bound) => Self::Closed(IntervalBound::new(bound.into_inner())),
            Self::Closed(bound) => Self::Open(IntervalBound::new(bound.into_inner())),
        }
    }

    /// Converts a bound to the opposite side while preserving the open/closed type.
    ///
    /// This function transforms an `IntervalBoundRuntime<RealType, Side>` to
    /// `IntervalBoundRuntime<RealType, Side::Opposite>`, changing `Lower` ↔ `Upper`
    /// while keeping `Open` ↔ `Open` and `Closed` ↔ `Closed`.
    ///
    /// The return type is determined by the [`BoundSide::Opposite`] associated type,
    /// so no turbofish syntax is needed - the type system automatically infers the
    /// correct opposite side based on the input.
    ///
    /// # Type Transformations
    ///
    /// | Input Type | Output Type |
    /// |------------|-------------|
    /// | `LowerBoundRuntime::Open(a)` | `UpperBoundRuntime::Open(a)` |
    /// | `LowerBoundRuntime::Closed(a)` | `UpperBoundRuntime::Closed(a)` |
    /// | `UpperBoundRuntime::Open(b)` | `LowerBoundRuntime::Open(b)` |
    /// | `UpperBoundRuntime::Closed(b)` | `LowerBoundRuntime::Closed(b)` |
    ///
    /// # Use Cases
    ///
    /// This function is primarily useful in interval set operations (like difference)
    /// where you need to take a bound from one interval and use it as the opposite
    /// side for another interval, while flipping the inclusion/exclusion semantics.
    ///
    /// # Examples
    ///
    /// ## Converting Lower to Upper Bounds
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// // Convert lower bound to upper bound (both open)
    /// let lower_open = LowerBoundRuntime::new_open(5.0);
    /// let upper_open: UpperBoundRuntime<f64> = lower_open.flip_bound_side();
    /// assert!(upper_open.is_open_variant());
    /// assert_eq!(*upper_open.as_ref(), 5.0);
    ///
    /// // Convert lower bound to upper bound (both closed)
    /// let lower_closed = LowerBoundRuntime::new_closed(10.0);
    /// let upper_closed: UpperBoundRuntime<f64> = lower_closed.flip_bound_side();
    /// assert!(upper_closed.is_closed_variant());
    /// assert_eq!(*upper_closed.as_ref(), 10.0);
    /// ```
    ///
    /// ## Converting Upper to Lower Bounds
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// // Convert upper bound to lower bound (both open)
    /// let upper_open = UpperBoundRuntime::new_open(20.0);
    /// let lower_open: LowerBoundRuntime<f64> = upper_open.flip_bound_side();
    /// assert!(lower_open.is_open_variant());
    /// assert_eq!(*lower_open.as_ref(), 20.0);
    ///
    /// // Convert upper bound to lower bound (both closed)
    /// let upper_closed = UpperBoundRuntime::new_closed(15.0);
    /// let lower_closed: LowerBoundRuntime<f64> = upper_closed.flip_bound_side();
    /// assert!(lower_closed.is_closed_variant());
    /// assert_eq!(*lower_closed.as_ref(), 15.0);
    /// ```
    ///
    /// ## Combining with Bound Type Flipping
    ///
    /// You can combine `flip_bound_side()` with `flip_bound_type()` to perform
    /// both transformations:
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// // Start with a closed lower bound
    /// let lower_closed = LowerBoundRuntime::new_closed(3.0);
    ///
    /// // Convert to open upper bound (both transformations)
    /// let upper_open: UpperBoundRuntime<f64> = lower_closed
    ///     .flip_bound_side()  // Lower Closed -> Upper Closed
    ///     .flip_bound_type();  // Upper Closed -> Upper Open
    ///
    /// assert!(upper_open.is_open_variant());
    /// assert_eq!(*upper_open.as_ref(), 3.0);
    /// ```
    ///
    /// ## Use in Interval Difference Operations
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// // When computing A \ B, if B has lower bound [5, we need upper bound )5
    /// let b_lower = LowerBoundRuntime::new_closed(5.0);
    ///
    /// // Convert and flip for the difference result
    /// let result_upper: UpperBoundRuntime<f64> = b_lower
    ///     .flip_bound_side()   // Lower -> Upper
    ///     .flip_bound_type();   // Closed -> Open
    ///
    /// assert!(result_upper.is_open_variant());
    /// assert_eq!(*result_upper.as_ref(), 5.0);
    /// // This creates the upper bound )5 from the lower bound [5
    /// ```
    ///
    /// # Performance
    ///
    /// - **Time Complexity**: O(1) - just moves the underlying value
    /// - **Memory**: Consumes `self`, no allocation or cloning required
    /// - **Inlining**: Marked `#[inline(always)]` for zero-cost abstraction
    ///
    /// # See Also
    ///
    /// - [`flip_bound_type`](Self::flip_bound_type) - Change Open ↔ Closed
    /// - [`new_open`](Self::new_open) - Create an open bound
    /// - [`new_closed`](Self::new_closed) - Create a closed bound
    #[inline(always)]
    pub fn flip_bound_side(self) -> IntervalBoundRuntime<RealType, Side::Opposite> {
        match self {
            Self::Open(bound) => IntervalBoundRuntime::Open(IntervalBound::new(bound.into_inner())),
            Self::Closed(bound) => {
                IntervalBoundRuntime::Closed(IntervalBound::new(bound.into_inner()))
            }
        }
    }

    /// Converts a bound to the opposite side AND flips the open/closed type.
    ///
    /// This is a convenience function that combines [`flip_bound_side`](Self::flip_bound_side)
    /// and [`flip_bound_type`](Self::flip_bound_type) in a single operation, performing
    /// both transformations atomically:
    /// - Changes `Lower` ↔ `Upper` (side transformation)
    /// - Changes `Open` ↔ `Closed` (type transformation)
    ///
    /// This is equivalent to calling `self.flip_bound_side().flip_bound_type()` but
    /// more concise and expresses the intent clearly.
    ///
    /// # Type Transformations
    ///
    /// | Input Type | Output Type |
    /// |------------|-------------|
    /// | `LowerBoundRuntime::Open(a)` | `UpperBoundRuntime::Closed(a)` |
    /// | `LowerBoundRuntime::Closed(a)` | `UpperBoundRuntime::Open(a)` |
    /// | `UpperBoundRuntime::Open(b)` | `LowerBoundRuntime::Closed(b)` |
    /// | `UpperBoundRuntime::Closed(b)` | `LowerBoundRuntime::Open(b)` |
    ///
    /// # Mathematical Motivation
    ///
    /// In interval arithmetic, particularly in set difference operations, when you
    /// exclude a portion of an interval, the complementary bound needs both transformations:
    ///
    /// - If the excluded interval has a **closed** lower bound `[a`, the remaining part
    ///   needs an **open** upper bound `)a` to avoid including the boundary
    /// - If the excluded interval has an **open** lower bound `(a`, the remaining part
    ///   needs a **closed** upper bound `]a` to include what was excluded
    ///
    /// This is precisely the transformation this function performs.
    ///
    /// # Use Cases
    ///
    /// This function is essential for interval difference operations (`A \ B`) where
    /// bounds from the subtracted interval need to become complementary bounds in the result.
    ///
    /// # Examples
    ///
    /// ## Basic Transformations
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// // Lower Closed -> Upper Open
    /// let lower_closed = LowerBoundRuntime::new_closed(5.0);
    /// let upper_open: UpperBoundRuntime<f64> = lower_closed.flip_bound_side_and_type();
    /// assert!(upper_open.is_open_variant());
    /// assert_eq!(*upper_open.as_ref(), 5.0);
    ///
    /// // Lower Open -> Upper Closed
    /// let lower_open = LowerBoundRuntime::new_open(10.0);
    /// let upper_closed: UpperBoundRuntime<f64> = lower_open.flip_bound_side_and_type();
    /// assert!(upper_closed.is_closed_variant());
    /// assert_eq!(*upper_closed.as_ref(), 10.0);
    ///
    /// // Upper Closed -> Lower Open
    /// let upper_closed = UpperBoundRuntime::new_closed(15.0);
    /// let lower_open: LowerBoundRuntime<f64> = upper_closed.flip_bound_side_and_type();
    /// assert!(lower_open.is_open_variant());
    /// assert_eq!(*lower_open.as_ref(), 15.0);
    ///
    /// // Upper Open -> Lower Closed
    /// let upper_open = UpperBoundRuntime::new_open(20.0);
    /// let lower_closed: LowerBoundRuntime<f64> = upper_open.flip_bound_side_and_type();
    /// assert!(lower_closed.is_closed_variant());
    /// assert_eq!(*lower_closed.as_ref(), 20.0);
    /// ```
    ///
    /// ## Interval Difference: Why This Matters
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// // Computing A \ B where:
    /// // A = [0, 10]
    /// // B = [5, 7]
    /// // Result should be [0, 5) ∪ (7, 10]
    ///
    /// // B's lower bound is [5 (closed), so left remainder needs )5 (open upper)
    /// let b_lower = LowerBoundRuntime::new_closed(5.0);
    /// let left_upper: UpperBoundRuntime<f64> = b_lower.flip_bound_side_and_type();
    /// assert!(left_upper.is_open_variant());
    /// assert_eq!(*left_upper.as_ref(), 5.0);
    /// // This creates [0, 5) - the left part of A \ B
    ///
    /// // B's upper bound is ]7 (closed), so right remainder needs (7 (open lower)
    /// let b_upper = UpperBoundRuntime::new_closed(7.0);
    /// let right_lower: LowerBoundRuntime<f64> = b_upper.flip_bound_side_and_type();
    /// assert!(right_lower.is_open_variant());
    /// assert_eq!(*right_lower.as_ref(), 7.0);
    /// // This creates (7, 10] - the right part of A \ B
    /// ```
    ///
    /// ## Comparison with Sequential Operations
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let bound = LowerBoundRuntime::new_closed(3.0);
    ///
    /// // These are equivalent:
    /// let result1: UpperBoundRuntime<f64> = bound.clone().flip_bound_side_and_type();
    /// let result2: UpperBoundRuntime<f64> = bound.flip_bound_side().flip_bound_type();
    ///
    /// assert_eq!(result1.is_open_variant(), result2.is_open_variant());
    /// assert_eq!(*result1.as_ref(), *result2.as_ref());
    /// ```
    ///
    /// ## Involutive Property
    ///
    /// Applying this transformation twice returns to the original state (modulo the value):
    ///
    /// ```rust
    /// use grid1d::bounds::*;
    ///
    /// let original = LowerBoundRuntime::new_closed(7.5);
    /// let was_closed = original.is_closed_variant();
    /// let original_value = *original.as_ref();
    ///
    /// // Apply transformation twice
    /// let transformed: UpperBoundRuntime<f64> = original.flip_bound_side_and_type();
    /// let back: LowerBoundRuntime<f64> = transformed.flip_bound_side_and_type();
    ///
    /// // Returns to original type and value
    /// assert_eq!(back.is_closed_variant(), was_closed);
    /// assert_eq!(*back.as_ref(), original_value);
    /// ```
    ///
    /// # Performance
    ///
    /// - **Time Complexity**: O(1) - single pattern match and value move
    /// - **Memory**: Consumes `self`, no allocation or cloning required
    /// - **Inlining**: Marked `#[inline(always)]` for zero-cost abstraction
    /// - **Optimization**: Compiler can optimize to a simple field swap
    ///
    /// # See Also
    ///
    /// - [`flip_bound_side`](Self::flip_bound_side) - Change only the side (Lower ↔ Upper)
    /// - [`flip_bound_type`](Self::flip_bound_type) - Change only the type (Open ↔ Closed)
    /// - [`new_open`](Self::new_open) - Create an open bound
    /// - [`new_closed`](Self::new_closed) - Create a closed bound
    #[inline(always)]
    pub fn flip_bound_side_and_type(self) -> IntervalBoundRuntime<RealType, Side::Opposite> {
        match self {
            Self::Open(bound) => {
                IntervalBoundRuntime::Closed(IntervalBound::new(bound.into_inner()))
            }
            Self::Closed(bound) => {
                IntervalBoundRuntime::Open(IntervalBound::new(bound.into_inner()))
            }
        }
    }
}

/// Runtime-determined lower bound that can be either open or closed.
///
/// [`LowerBoundRuntime<RealType>`] is a convenient type alias for [`IntervalBoundRuntime<RealType, Lower>`]
/// that specifically represents lower boundaries where the open/closed nature is determined at runtime.
/// This type is essential for dynamic interval construction, user configuration, serialization,
/// and algorithms that work with varying lower boundary semantics.
///
/// ## Type Definition
///
/// ```rust
/// use grid1d::bounds::*;
///
/// // These are equivalent:
/// type LowerBoundRuntime<T> = IntervalBoundRuntime<T, Lower>;
/// type ExplicitForm<T> = IntervalBoundRuntime<T, Lower>;
/// ```
///
/// ## Mathematical Properties
///
/// Lower bounds define minimum constraints for intervals and domains with runtime-determined inclusion:
///
/// | Variant | Mathematical Constraint | Notation | Value at Boundary |
/// |---------|------------------------|----------|-------------------|
/// | `Open(LowerBoundOpen)`   | `x > lower_value` | `(a` | **Excluded** |
/// | `Closed(LowerBoundClosed)` | `x ≥ lower_value` | `[a` | **Included** |
///
/// ## When to Use Lower Bound Runtime
///
/// ### ✅ **Recommended Use Cases**
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // ✅ GOOD: User input with configuration
/// fn create_constraint_from_user_input(min_value: f64, inclusive: bool) -> LowerBoundRuntime<f64> {
///     if inclusive {
///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(min_value))
///     } else {
///         IntervalBoundRuntime::Open(LowerBoundOpen::new(min_value))
///     }
/// }
///
/// // ✅ GOOD: Configuration-driven interval construction
/// struct DomainConfig {
///     start: f64,
///     include_start: bool,
///     end: f64,
///     include_end: bool,
/// }
///
/// fn build_dynamic_domain(config: DomainConfig) -> (LowerBoundRuntime<f64>, UpperBoundRuntime<f64>) {
///     let lower = create_constraint_from_user_input(config.start, config.include_start);
///     let upper = if config.include_end {
///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(config.end))
///     } else {
///         IntervalBoundRuntime::Open(UpperBoundOpen::new(config.end))
///     };
///     (lower, upper)
/// }
/// ```
///
/// ### ❌ **Avoid When**
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // ❌ AVOID: When boundary type is known at compile time
/// fn bad_usage() -> LowerBoundRuntime<f64> {
///     // This should just be LowerBoundClosed::new(0.0)
///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0))
/// }
///
/// // ✅ BETTER: Use compile-time types when semantics are fixed
/// fn good_usage() -> LowerBoundClosed<f64> {
///     LowerBoundClosed::new(0.0)
/// }
/// ```
///
/// ## Core Operations
///
/// ### Constraint Testing
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let closed_lower = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
/// let open_lower = IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));
///
/// // Test the boundary value itself
/// assert!(closed_lower.value_within_bound(&5.0));  // 5 ≥ 5 → true
/// assert!(!open_lower.value_within_bound(&5.0));   // 5 > 5 → false
///
/// // Test values above the boundary
/// assert!(closed_lower.value_within_bound(&5.1));  // 5.1 ≥ 5 → true
/// assert!(open_lower.value_within_bound(&5.1));    // 5.1 > 5 → true
///
/// // Test values below the boundary
/// assert!(!closed_lower.value_within_bound(&4.9)); // 4.9 ≥ 5 → false
/// assert!(!open_lower.value_within_bound(&4.9));   // 4.9 > 5 → false
/// ```
///
/// ### Type Information Queries
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let closed_bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(1.0));
/// let open_bound = IntervalBoundRuntime::Open(LowerBoundOpen::new(1.0));
///
/// // Query boundary inclusion behavior
/// assert!(closed_bound.is_closed());
/// assert!(!closed_bound.is_open());
/// assert!(closed_bound.includes_boundary());
///
/// assert!(!open_bound.is_closed());
/// assert!(open_bound.is_open());
/// assert!(!open_bound.includes_boundary());
///
/// // All lower bounds share this property
/// assert!(closed_bound.is_lower_bound());
/// assert!(open_bound.is_lower_bound());
/// assert!(!closed_bound.is_upper_bound());
/// assert!(!open_bound.is_upper_bound());
/// ```
///
/// ### Value Access
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::{New, IntoInner};
///
/// let bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(3.14));
///
/// // Access the underlying value by reference
/// let value_ref: &f64 = bound.as_ref();
/// assert_eq!(*value_ref, 3.14);
///
/// // Extract the value (consuming the bound)
/// let value: f64 = bound.into_inner();
/// assert_eq!(value, 3.14);
/// ```
///
/// ## Mathematical Ordering
///
/// Lower bounds maintain mathematically correct ordering where "tighter" constraints are considered smaller:
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let closed_lower = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));  // [5
/// let open_lower = IntervalBoundRuntime::Open(LowerBoundOpen::new(5.0));        // (5
///
/// // Closed bound is "tighter" (more restrictive) than open bound
/// assert!(closed_lower < open_lower);  // [5 < (5
///
/// // This ordering ensures correct interval operations:
/// // intersection([5, 10]) ∩ (5, 10]) = (5, 10] (the looser constraint wins)
/// ```
///
/// ## Practical Usage Patterns
///
/// ### Dynamic Interval Construction
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// struct IntervalBuilder {
///     lower_value: f64,
///     lower_inclusive: bool,
/// }
///
/// impl IntervalBuilder {
///     fn build_lower_bound(&self) -> LowerBoundRuntime<f64> {
///         if self.lower_inclusive {
///             IntervalBoundRuntime::Closed(LowerBoundClosed::new(self.lower_value))
///         } else {
///             IntervalBoundRuntime::Open(LowerBoundOpen::new(self.lower_value))
///         }
///     }
///     
///     fn set_constraint(&mut self, value: f64, inclusive: bool) {
///         self.lower_value = value;
///         self.lower_inclusive = inclusive;
///     }
/// }
///
/// let mut builder = IntervalBuilder { lower_value: 0.0, lower_inclusive: true };
/// let bound1 = builder.build_lower_bound(); // [0
///
/// builder.set_constraint(1.0, false);
/// let bound2 = builder.build_lower_bound(); // (1
///
/// assert!(bound1.is_closed());
/// assert!(bound2.is_open());
/// ```
///
/// ### Configuration-Driven Systems
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct ConstraintConfig {
///     minimum_value: f64,
///     include_minimum: bool,
/// }
///
/// impl ConstraintConfig {
///     fn to_lower_bound(&self) -> LowerBoundRuntime<f64> {
///         if self.include_minimum {
///             IntervalBoundRuntime::Closed(LowerBoundClosed::new(self.minimum_value))
///         } else {
///             IntervalBoundRuntime::Open(LowerBoundOpen::new(self.minimum_value))
///         }
///     }
/// }
///
/// // Load from configuration file or user input
/// let config = ConstraintConfig {
///     minimum_value: 0.0,
///     include_minimum: true,
/// };
///
/// let lower_bound = config.to_lower_bound();
/// assert!(lower_bound.value_within_bound(&0.0)); // Includes minimum
/// ```
///
/// ### Collection Processing
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Store different lower bound types in the same collection
/// let constraints: Vec<LowerBoundRuntime<f64>> = vec![
///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0)),   // [0
///     IntervalBoundRuntime::Open(LowerBoundOpen::new(1.0)),       // (1
///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(2.0)),   // [2
///     IntervalBoundRuntime::Open(LowerBoundOpen::new(3.0)),       // (3
/// ];
///
/// // Process them uniformly
/// for (i, constraint) in constraints.iter().enumerate() {
///     let inclusion = if constraint.is_closed() { "≥" } else { ">" };
///     println!("Constraint {}: x {} {}", i, inclusion, constraint.as_ref());
/// }
/// // Output:
/// // Constraint 0: x ≥ 0
/// // Constraint 1: x > 1
/// // Constraint 2: x ≥ 2
/// // Constraint 3: x > 3
///
/// // Find all constraints satisfied by a test value
/// let test_value = 2.0;
/// let satisfied: Vec<usize> = constraints.iter()
///     .enumerate()
///     .filter(|(_, constraint)| constraint.value_within_bound(&test_value))
///     .map(|(i, _)| i)
///     .collect();
///
/// assert_eq!(satisfied, vec![0, 1, 2]); // Only [0, (1 and [2 include 2.0
/// ```
///
/// ## Serialization Support
///
/// Runtime bounds have natural serialization support, making them ideal for persistent configuration:
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
/// use serde_json;
///
/// let bounds = vec![
///     IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0)),
///     IntervalBoundRuntime::Open(LowerBoundOpen::new(1.5)),
/// ];
///
/// // Serialize to JSON
/// let json = serde_json::to_string_pretty(&bounds).unwrap();
/// println!("Serialized lower bounds:\n{}", json);
///
/// // Deserialize back
/// let deserialized: Vec<LowerBoundRuntime<f64>> =
///     serde_json::from_str(&json).unwrap();
///
/// // Verify round-trip correctness
/// for (original, restored) in bounds.iter().zip(deserialized.iter()) {
///     assert_eq!(original.as_ref(), restored.as_ref());
///     assert_eq!(original.is_closed(), restored.is_closed());
///     assert_eq!(original.value_within_bound(&0.0), restored.value_within_bound(&0.0));
/// }
/// ```
///
/// ## Generic Algorithm Support
///
/// ```rust
/// use grid1d::bounds::*;
/// use num_valid::RealScalar;
/// use try_create::New;
///
/// fn find_minimum_satisfying_constraint<T: RealScalar + Copy>(
///     candidates: &[T],
///     constraint: &LowerBoundRuntime<T>
/// ) -> Option<T>
/// where
///     T: PartialOrd,
/// {
///     candidates.iter()
///         .filter(|&&value| constraint.value_within_bound(&value))
///         .min_by(|a, b| a.partial_cmp(b).unwrap())
///         .copied()
/// }
///
/// let values = vec![0.0, 0.5, 1.0, 1.5, 2.0];
///
/// let closed_constraint = IntervalBoundRuntime::Closed(LowerBoundClosed::new(1.0));
/// let open_constraint = IntervalBoundRuntime::Open(LowerBoundOpen::new(1.0));
///
/// assert_eq!(find_minimum_satisfying_constraint(&values, &closed_constraint), Some(1.0)); // x ≥ 1
/// assert_eq!(find_minimum_satisfying_constraint(&values, &open_constraint), Some(1.5));   // x > 1
/// ```
///
/// ## Performance vs Compile-Time Bounds
///
/// ### Runtime Performance
/// - **Memory**: Same as underlying bound plus small enum discriminant (~9 bytes for f64)
/// - **Operations**: Small pattern matching overhead (~1-2 CPU cycles)
/// - **Constraint Testing**: O(1) with inlined comparisons
///
/// ### Comparison with Compile-Time Bounds
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Runtime bound: small branching cost
/// fn check_runtime_constraint(bound: &LowerBoundRuntime<f64>, value: f64) -> bool {
///     match bound {  // Runtime dispatch (small cost)
///         IntervalBoundRuntime::Open(b) => value > *b.as_ref(),
///         IntervalBoundRuntime::Closed(b) => value >= *b.as_ref(),
///     }
/// }
///
/// // Compile-time bound: zero overhead
/// fn check_compile_time_constraint<T: BoundType>(bound: &LowerBound<f64, T>, value: f64) -> bool {
///     if T::is_open() {
///         value > *bound.as_ref()  // Direct comparison, no branching
///     } else {
///         value >= *bound.as_ref() // Direct comparison, no branching
///     }
/// }
/// ```
///
/// ## Integration with Grid1D
///
/// Runtime bounds integrate seamlessly with interval construction:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use try_create::{IntoInner, New};
///
/// fn create_interval_from_runtime_bounds(
///     lower: LowerBoundRuntime<f64>,
///     upper: UpperBoundRuntime<f64>
/// ) -> Box<dyn std::fmt::Debug> {
///     match (lower, upper) {
///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Closed(u)) => {
///             Box::new(IntervalClosed::new(l.into_inner(), u.into_inner()))
///         }
///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Open(u)) => {
///             Box::new(IntervalOpen::new(l.into_inner(), u.into_inner()))
///         }
///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Open(u)) => {
///             Box::new(IntervalLowerClosedUpperOpen::new(l.into_inner(), u.into_inner()))
///         }
///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Closed(u)) => {
///             Box::new(IntervalLowerOpenUpperClosed::new(l.into_inner(), u.into_inner()))
///         }
///     }
/// }
///
/// // Example usage
/// let lower = IntervalBoundRuntime::Closed(LowerBoundClosed::new(0.0));
/// let upper = IntervalBoundRuntime::Open(UpperBoundOpen::new(1.0));
/// let interval = create_interval_from_runtime_bounds(lower, upper); // Creates [0, 1)
/// ```
///
/// ## Conversion Patterns
///
/// ### Extract Specific Bound Types
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// fn extract_closed_lower_bound(bound: LowerBoundRuntime<f64>) -> Option<LowerBoundClosed<f64>> {
///     match bound {
///         IntervalBoundRuntime::Closed(closed_bound) => Some(closed_bound),
///         IntervalBoundRuntime::Open(_) => None,
///     }
/// }
///
/// let runtime_bound = IntervalBoundRuntime::Closed(LowerBoundClosed::new(5.0));
/// let compile_time_bound = extract_closed_lower_bound(runtime_bound);
/// assert!(compile_time_bound.is_some());
/// ```
///
/// ### Convert to Compile-Time When Possible
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Pattern: Use runtime bounds at API boundaries, compile-time internally
/// fn process_constraint(constraint: LowerBoundRuntime<f64>) -> String {
///     match constraint {
///         IntervalBoundRuntime::Closed(closed_bound) => {
///             // Delegate to compile-time optimized function
///             process_closed_constraint(closed_bound)
///         }
///         IntervalBoundRuntime::Open(open_bound) => {
///             // Delegate to compile-time optimized function
///             process_open_constraint(open_bound)
///         }
///     }
/// }
///
/// fn process_closed_constraint(bound: LowerBoundClosed<f64>) -> String {
///     format!("Inclusive lower bound: x ≥ {}", bound.as_ref())
/// }
///
/// fn process_open_constraint(bound: LowerBoundOpen<f64>) -> String {
///     format!("Exclusive lower bound: x > {}", bound.as_ref())
/// }
/// ```
///
/// ## Best Practices
///
/// ### 1. **Use at API Boundaries**
/// ```rust
/// use grid1d::bounds::*;
///
/// // ✅ GOOD: Runtime bounds for user-facing APIs
/// pub fn create_domain_from_config(
///     lower: LowerBoundRuntime<f64>,
///     upper: UpperBoundRuntime<f64>
/// ) -> Result<Box<dyn std::fmt::Debug>, String> {
///     // Implementation...
///     Ok(Box::new(format!("Domain created")))
/// }
///
/// // ✅ GOOD: Compile-time bounds for internal algorithms
/// fn optimize_grid_spacing<T: BoundType>(
///     lower: &LowerBound<f64, T>
/// ) -> f64 {
///     // High-performance internal computation
///     *lower.as_ref() * 1.1
/// }
/// ```
///
/// ### 2. **Pattern Match Early**
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // ✅ GOOD: Extract compile-time types early
/// fn efficient_processing(constraint: LowerBoundRuntime<f64>) -> f64 {
///     match constraint {
///         IntervalBoundRuntime::Closed(bound) => {
///             // Use compile-time optimized path
///             bound.as_ref() * 1.0  // Zero overhead
///         }
///         IntervalBoundRuntime::Open(bound) => {
///             // Use compile-time optimized path
///             bound.as_ref() + f64::EPSILON  // Zero overhead
///         }
///     }
/// }
/// ```
///
/// ### 3. **Validate Early**
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// fn create_constraint_with_validation(
///     value: f64,
///     inclusive: bool
/// ) -> Result<LowerBoundRuntime<f64>, String> {
///     if !value.is_finite() {
///         return Err(format!("Constraint value must be finite, got: {}", value));
///     }
///     
///     let bound = if inclusive {
///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(value))
///     } else {
///         IntervalBoundRuntime::Open(LowerBoundOpen::new(value))
///     };
///     
///     Ok(bound)
/// }
/// ```
///
/// ## Mathematical Guarantees
///
/// The [`LowerBoundRuntime`] type maintains mathematical correctness by:
///
/// - **Constraint Semantics**: Properly implements `x ≥ a` (closed) vs `x > a` (open)
/// - **Ordering Consistency**: Maintains mathematical ordering where `[a < (a`
/// - **Type Safety**: Prevents mixing with upper bounds at compile time
/// - **Value Preservation**: Maintains exact scalar values without precision loss
/// - **Conversion Safety**: Provides safe extraction of compile-time types
///
/// Use [`LowerBoundRuntime`] when you need the flexibility of runtime boundary semantics
/// while maintaining mathematical correctness and integration with the grid1d ecosystem.
/// For maximum performance when boundary types are known at compile time, prefer the
/// direct types [`LowerBoundClosed`](crate::bounds::LowerBoundClosed) and [`LowerBoundOpen`](crate::bounds::LowerBoundOpen).
pub type LowerBoundRuntime<RealType> = IntervalBoundRuntime<RealType, Lower>;

/// Runtime-determined upper bound that can be either open or closed.
///
/// [`UpperBoundRuntime<RealType>`] is a convenient type alias for [`IntervalBoundRuntime<RealType, Upper>`]
/// that specifically represents upper boundaries where the open/closed nature is determined at runtime.
/// This type is essential for dynamic interval construction, user configuration, serialization,
/// and algorithms that work with varying upper boundary semantics.
///
/// ## Type Definition
///
/// ```rust
/// use grid1d::bounds::*;
///
/// // These are equivalent:
/// type UpperBoundRuntime<T> = IntervalBoundRuntime<T, Upper>;
/// type ExplicitForm<T> = IntervalBoundRuntime<T, Upper>;
/// ```
///
/// ## Mathematical Properties
///
/// Upper bounds define maximum constraints for intervals and domains with runtime-determined inclusion:
///
/// | Variant | Mathematical Constraint | Notation | Value at Boundary |
/// |---------|------------------------|----------|-------------------|
/// | `Open(UpperBoundOpen)`   | `x < upper_value` | `b)` | **Excluded** |
/// | `Closed(UpperBoundClosed)` | `x ≤ upper_value` | `b]` | **Included** |
///
/// ## When to Use Upper Bound Runtime
///
/// ### ✅ **Recommended Use Cases**
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // ✅ GOOD: User input with configuration
/// fn create_upper_constraint_from_user_input(max_value: f64, inclusive: bool) -> UpperBoundRuntime<f64> {
///     if inclusive {
///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(max_value))
///     } else {
///         IntervalBoundRuntime::Open(UpperBoundOpen::new(max_value))
///     }
/// }
///
/// // ✅ GOOD: Configuration-driven interval construction
/// struct RangeConfig {
///     start: f64,
///     include_start: bool,
///     end: f64,
///     include_end: bool,
/// }
///
/// fn build_dynamic_range(config: RangeConfig) -> (LowerBoundRuntime<f64>, UpperBoundRuntime<f64>) {
///     let lower = if config.include_start {
///         IntervalBoundRuntime::Closed(LowerBoundClosed::new(config.start))
///     } else {
///         IntervalBoundRuntime::Open(LowerBoundOpen::new(config.start))
///     };
///     
///     let upper = create_upper_constraint_from_user_input(config.end, config.include_end);
///     (lower, upper)
/// }
/// ```
///
/// ### ❌ **Avoid When**
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // ❌ AVOID: When boundary type is known at compile time
/// fn bad_usage() -> UpperBoundRuntime<f64> {
///     // This should just be UpperBoundOpen::new(10.0)
///     IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0))
/// }
///
/// // ✅ BETTER: Use compile-time types when semantics are fixed
/// fn good_usage() -> UpperBoundOpen<f64> {
///     UpperBoundOpen::new(10.0)
/// }
/// ```
///
/// ## Core Operations
///
/// ### Constraint Testing
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let closed_upper = IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0));
/// let open_upper = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));
///
/// // Test the boundary value itself
/// assert!(closed_upper.value_within_bound(&10.0));  // 10 ≤ 10 → true
/// assert!(!open_upper.value_within_bound(&10.0));   // 10 < 10 → false
///
/// // Test values below the boundary
/// assert!(closed_upper.value_within_bound(&9.5));   // 9.5 ≤ 10 → true
/// assert!(open_upper.value_within_bound(&9.5));     // 9.5 < 10 → true
///
/// // Test values above the boundary
/// assert!(!closed_upper.value_within_bound(&10.5)); // 10.5 ≤ 10 → false
/// assert!(!open_upper.value_within_bound(&10.5));   // 10.5 < 10 → false
/// ```
///
/// ### Type Information Queries
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let closed_bound = IntervalBoundRuntime::Closed(UpperBoundClosed::new(5.0));
/// let open_bound = IntervalBoundRuntime::Open(UpperBoundOpen::new(5.0));
///
/// // Query boundary inclusion behavior
/// assert!(closed_bound.is_closed());
/// assert!(!closed_bound.is_open());
/// assert!(closed_bound.includes_boundary());
///
/// assert!(!open_bound.is_closed());
/// assert!(open_bound.is_open());
/// assert!(!open_bound.includes_boundary());
///
/// // All upper bounds share this property
/// assert!(closed_bound.is_upper_bound());
/// assert!(open_bound.is_upper_bound());
/// assert!(!closed_bound.is_lower_bound());
/// assert!(!open_bound.is_lower_bound());
/// ```
///
/// ### Value Access
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::{New, IntoInner};
///
/// let bound = IntervalBoundRuntime::Closed(UpperBoundClosed::new(2.718));
///
/// // Access the underlying value by reference
/// let value_ref: &f64 = bound.as_ref();
/// assert_eq!(*value_ref, 2.718);
///
/// // Extract the value (consuming the bound)
/// let value: f64 = bound.into_inner();
/// assert_eq!(value, 2.718);
/// ```
///
/// ## Mathematical Ordering
///
/// Upper bounds maintain mathematically correct ordering where "tighter" constraints are considered smaller:
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// let open_upper = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));        // 10)
/// let closed_upper = IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0));  // 10]
///
/// // Open bound is "tighter" (more restrictive) than closed bound
/// assert!(open_upper < closed_upper);  // 10) < 10]
///
/// // This ordering ensures correct interval operations:
/// // intersection([0, 10)) ∩ [0, 10]) = [0, 10) (the tighter constraint wins)
/// ```
///
/// ## Practical Usage Patterns
///
/// ### Dynamic Range Construction
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// struct RangeBuilder {
///     upper_value: f64,
///     upper_inclusive: bool,
/// }
///
/// impl RangeBuilder {
///     fn build_upper_bound(&self) -> UpperBoundRuntime<f64> {
///         if self.upper_inclusive {
///             IntervalBoundRuntime::Closed(UpperBoundClosed::new(self.upper_value))
///         } else {
///             IntervalBoundRuntime::Open(UpperBoundOpen::new(self.upper_value))
///         }
///     }
///     
///     fn set_maximum(&mut self, value: f64, inclusive: bool) {
///         self.upper_value = value;
///         self.upper_inclusive = inclusive;
///     }
/// }
///
/// let mut builder = RangeBuilder { upper_value: 100.0, upper_inclusive: true };
/// let bound1 = builder.build_upper_bound(); // 100]
///
/// builder.set_maximum(50.0, false);
/// let bound2 = builder.build_upper_bound(); // 50)
///
/// assert!(bound1.is_closed());
/// assert!(bound2.is_open());
/// ```
///
/// ### Configuration-Driven Systems
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct MaximumConfig {
///     maximum_value: f64,
///     include_maximum: bool,
/// }
///
/// impl MaximumConfig {
///     fn to_upper_bound(&self) -> UpperBoundRuntime<f64> {
///         if self.include_maximum {
///             IntervalBoundRuntime::Closed(UpperBoundClosed::new(self.maximum_value))
///         } else {
///             IntervalBoundRuntime::Open(UpperBoundOpen::new(self.maximum_value))
///         }
///     }
/// }
///
/// // Load from configuration file or user input
/// let config = MaximumConfig {
///     maximum_value: 100.0,
///     include_maximum: false,
/// };
///
/// let upper_bound = config.to_upper_bound();
/// assert!(!upper_bound.value_within_bound(&100.0)); // Excludes maximum
/// assert!(upper_bound.value_within_bound(&99.9));   // Includes values below
/// ```
///
/// ### Collection Processing
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Store different upper bound types in the same collection
/// let constraints: Vec<UpperBoundRuntime<f64>> = vec![
///     IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0)),  // 10]
///     IntervalBoundRuntime::Open(UpperBoundOpen::new(20.0)),      // 20)
///     IntervalBoundRuntime::Closed(UpperBoundClosed::new(30.0)),  // 30]
///     IntervalBoundRuntime::Open(UpperBoundOpen::new(40.0)),      // 40)
/// ];
///
/// // Process them uniformly
/// for (i, constraint) in constraints.iter().enumerate() {
///     let inclusion = if constraint.is_closed() { "≤" } else { "<" };
///     println!("Constraint {}: x {} {}", i, inclusion, constraint.as_ref());
/// }
/// // Output:
/// // Constraint 0: x ≤ 10
/// // Constraint 1: x < 20
/// // Constraint 2: x ≤ 30
/// // Constraint 3: x < 40
///
/// // Find all constraints satisfied by a test value
/// let test_value = 20.0;
/// let satisfied: Vec<usize> = constraints.iter()
///     .enumerate()
///     .filter(|(_, constraint)| constraint.value_within_bound(&test_value))
///     .map(|(i, _)| i)
///     .collect();
///
/// assert_eq!(satisfied, vec![2, 3]); // Only 30] and 40) include 20.0
/// ```
///
/// ## Serialization Support
///
/// Runtime bounds have natural serialization support, making them ideal for persistent configuration:
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
/// use serde_json;
///
/// let bounds = vec![
///     IntervalBoundRuntime::Closed(UpperBoundClosed::new(100.0)),
///     IntervalBoundRuntime::Open(UpperBoundOpen::new(50.0)),
/// ];
///
/// // Serialize to JSON
/// let json = serde_json::to_string_pretty(&bounds).unwrap();
/// println!("Serialized upper bounds:\n{}", json);
///
/// // Deserialize back
/// let deserialized: Vec<UpperBoundRuntime<f64>> =
///     serde_json::from_str(&json).unwrap();
///
/// // Verify round-trip correctness
/// for (original, restored) in bounds.iter().zip(deserialized.iter()) {
///     assert_eq!(original.as_ref(), restored.as_ref());
///     assert_eq!(original.is_closed(), restored.is_closed());
///     assert_eq!(original.value_within_bound(&50.0), restored.value_within_bound(&50.0));
/// }
/// ```
///
/// ## Generic Algorithm Support
///
/// ```rust
/// use grid1d::bounds::*;
/// use num_valid::RealScalar;
/// use try_create::New;
///
/// fn find_maximum_satisfying_constraint<T: RealScalar + Copy>(
///     candidates: &[T],
///     constraint: &UpperBoundRuntime<T>
/// ) -> Option<T>
/// where
///     T: PartialOrd,
/// {
///     candidates.iter()
///         .filter(|&&value| constraint.value_within_bound(&value))
///         .max_by(|a, b| a.partial_cmp(b).unwrap())
///         .copied()
/// }
///
/// let values = vec![8.0, 9.0, 10.0, 11.0, 12.0];
///
/// let closed_constraint = IntervalBoundRuntime::Closed(UpperBoundClosed::new(10.0));
/// let open_constraint = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));
///
/// assert_eq!(find_maximum_satisfying_constraint(&values, &closed_constraint), Some(10.0)); // x ≤ 10
/// assert_eq!(find_maximum_satisfying_constraint(&values, &open_constraint), Some(9.0));    // x < 10
/// ```
///
/// ## Performance vs Compile-Time Bounds
///
/// ### Runtime Performance
/// - **Memory**: Same as underlying bound plus small enum discriminant (~9 bytes for f64)
/// - **Operations**: Small pattern matching overhead (~1-2 CPU cycles)
/// - **Constraint Testing**: O(1) with inlined comparisons
///
/// ### Comparison with Compile-Time Bounds
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Runtime bound: small branching cost
/// fn check_runtime_constraint(bound: &UpperBoundRuntime<f64>, value: f64) -> bool {
///     match bound {  // Runtime dispatch (small cost)
///         IntervalBoundRuntime::Open(b) => value < *b.as_ref(),
///         IntervalBoundRuntime::Closed(b) => value <= *b.as_ref(),
///     }
/// }
///
/// // Compile-time bound: zero overhead
/// fn check_compile_time_constraint<T: BoundType>(bound: &UpperBound<f64, T>, value: f64) -> bool {
///     if T::is_open() {
///         value < *bound.as_ref()  // Direct comparison, no branching
///     } else {
///         value <= *bound.as_ref() // Direct comparison, no branching
///     }
/// }
/// ```
///
/// ## Integration with Grid1D
///
/// Runtime bounds integrate seamlessly with interval construction:
///
/// ```rust
/// use grid1d::{bounds::*, intervals::*};
/// use try_create::{IntoInner, New};
///
/// fn create_interval_from_runtime_bounds(
///     lower: LowerBoundRuntime<f64>,
///     upper: UpperBoundRuntime<f64>
/// ) -> Box<dyn std::fmt::Debug> {
///     match (lower, upper) {
///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Closed(u)) => {
///             Box::new(IntervalClosed::new(l.into_inner(), u.into_inner()))
///         }
///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Open(u)) => {
///             Box::new(IntervalOpen::new(l.into_inner(), u.into_inner()))
///         }
///         (IntervalBoundRuntime::Closed(l), IntervalBoundRuntime::Open(u)) => {
///             Box::new(IntervalLowerClosedUpperOpen::new(l.into_inner(), u.into_inner()))
///         }
///         (IntervalBoundRuntime::Open(l), IntervalBoundRuntime::Closed(u)) => {
///             Box::new(IntervalLowerOpenUpperClosed::new(l.into_inner(), u.into_inner()))
///         }
///     }
/// }
///
/// // Example usage
/// let lower = IntervalBoundRuntime::Open(LowerBoundOpen::new(0.0));
/// let upper = IntervalBoundRuntime::Closed(UpperBoundClosed::new(1.0));
/// let interval = create_interval_from_runtime_bounds(lower, upper); // Creates (0, 1]
/// ```
///
/// ## Conversion Patterns
///
/// ### Extract Specific Bound Types
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// fn extract_open_upper_bound(bound: UpperBoundRuntime<f64>) -> Option<UpperBoundOpen<f64>> {
///     match bound {
///         IntervalBoundRuntime::Open(open_bound) => Some(open_bound),
///         IntervalBoundRuntime::Closed(_) => None,
///     }
/// }
///
/// let runtime_bound = IntervalBoundRuntime::Open(UpperBoundOpen::new(10.0));
/// let compile_time_bound = extract_open_upper_bound(runtime_bound);
/// assert!(compile_time_bound.is_some());
/// ```
///
/// ### Convert to Compile-Time When Possible
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Pattern: Use runtime bounds at API boundaries, compile-time internally
/// fn process_upper_constraint(constraint: UpperBoundRuntime<f64>) -> String {
///     match constraint {
///         IntervalBoundRuntime::Closed(closed_bound) => {
///             // Delegate to compile-time optimized function
///             process_closed_upper_constraint(closed_bound)
///         }
///         IntervalBoundRuntime::Open(open_bound) => {
///             // Delegate to compile-time optimized function
///             process_open_upper_constraint(open_bound)
///         }
///     }
/// }
///
/// fn process_closed_upper_constraint(bound: UpperBoundClosed<f64>) -> String {
///     format!("Inclusive upper bound: x ≤ {}", bound.as_ref())
/// }
///
/// fn process_open_upper_constraint(bound: UpperBoundOpen<f64>) -> String {
///     format!("Exclusive upper bound: x < {}", bound.as_ref())
/// }
/// ```
///
/// ## Best Practices
///
/// ### 1. **Use at API Boundaries**
/// ```rust
/// use grid1d::bounds::*;
///
/// // ✅ GOOD: Runtime bounds for user-facing APIs
/// pub fn create_range_from_config(
///     lower: LowerBoundRuntime<f64>,
///     upper: UpperBoundRuntime<f64>
/// ) -> Result<Box<dyn std::fmt::Debug>, String> {
///     // Implementation...
///     Ok(Box::new(format!("Range created")))
/// }
///
/// // ✅ GOOD: Compile-time bounds for internal algorithms
/// fn optimize_upper_limit<T: BoundType>(
///     upper: &UpperBound<f64, T>
/// ) -> f64 {
///     // High-performance internal computation
///     *upper.as_ref() * 0.9
/// }
/// ```
///
/// ### 2. **Pattern Match Early**
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // ✅ GOOD: Extract compile-time types early
/// fn efficient_upper_processing(constraint: UpperBoundRuntime<f64>) -> f64 {
///     match constraint {
///         IntervalBoundRuntime::Closed(bound) => {
///             // Use compile-time optimized path
///             *bound.as_ref()  // Zero overhead
///         }
///         IntervalBoundRuntime::Open(bound) => {
///             // Use compile-time optimized path
///             *bound.as_ref() - f64::EPSILON  // Zero overhead
///         }
///     }
/// }
/// ```
///
/// ### 3. **Validate Early**
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// fn create_upper_constraint_with_validation(
///     value: f64,
///     inclusive: bool
/// ) -> Result<UpperBoundRuntime<f64>, String> {
///     if !value.is_finite() {
///         return Err(format!("Upper bound value must be finite, got: {}", value));
///     }
///     
///     let bound = if inclusive {
///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(value))
///     } else {
///         IntervalBoundRuntime::Open(UpperBoundOpen::new(value))
///     };
///     
///     Ok(bound)
/// }
/// ```
///
/// ## Array-Like Range Construction
///
/// Upper bounds work naturally with Rust-style range construction:
///
/// ```rust
/// use grid1d::bounds::*;
/// use try_create::New;
///
/// // Pattern: Rust-style ranges with runtime bounds
/// fn create_rust_like_range(start: f64, end: f64, end_inclusive: bool) -> (LowerBoundClosed<f64>, UpperBoundRuntime<f64>) {
///     let lower = LowerBoundClosed::new(start);  // Always include start like [start, ...)
///     let upper = if end_inclusive {
///         IntervalBoundRuntime::Closed(UpperBoundClosed::new(end))  // [start, end]
///     } else {
///         IntervalBoundRuntime::Open(UpperBoundOpen::new(end))      // [start, end)
///     };
///     (lower, upper)
/// }
///
/// let (lower, upper_inclusive) = create_rust_like_range(0.0, 10.0, true);   // [0, 10]
/// let (_, upper_exclusive) = create_rust_like_range(0.0, 10.0, false);      // [0, 10)
///
/// assert!(upper_inclusive.value_within_bound(&10.0));  // 10 ≤ 10 → true
/// assert!(!upper_exclusive.value_within_bound(&10.0)); // 10 < 10 → false
/// ```
///
/// ## Mathematical Guarantees
///
/// The [`UpperBoundRuntime`] type maintains mathematical correctness by:
///
/// - **Constraint Semantics**: Properly implements `x ≤ b` (closed) vs `x < b` (open)
/// - **Ordering Consistency**: Maintains mathematical ordering where `b) < b]`
/// - **Type Safety**: Prevents mixing with lower bounds at compile time
/// - **Value Preservation**: Maintains exact scalar values without precision loss
/// - **Conversion Safety**: Provides safe extraction of compile-time types
///
/// Use [`UpperBoundRuntime`] when you need the flexibility of runtime boundary semantics
/// while maintaining mathematical correctness and integration with the grid1d ecosystem.
/// For maximum performance when boundary types are known at compile time, prefer the
/// direct types [`UpperBoundClosed`](crate::bounds::UpperBoundClosed) and [`UpperBoundOpen`](crate::bounds::UpperBoundOpen).
pub type UpperBoundRuntime<RealType> = IntervalBoundRuntime<RealType, Upper>;

impl<RealType: RealScalar, Side: BoundSide> BoundTypeChecks
    for IntervalBoundRuntime<RealType, Side>
{
    #[inline(always)]
    fn includes_boundary(&self) -> bool {
        matches!(self, IntervalBoundRuntime::Closed(_))
    }
}

impl<RealType: RealScalar> BoundSideChecks for LowerBoundRuntime<RealType> {
    #[inline(always)]
    fn is_upper_bound(&self) -> bool {
        false
    }
}

impl<RealType: RealScalar> BoundSideChecks for UpperBoundRuntime<RealType> {
    #[inline(always)]
    fn is_upper_bound(&self) -> bool {
        true
    }
}

impl<RealType: RealScalar, Side: BoundSide> ValueWithinBound
    for IntervalBoundRuntime<RealType, Side>
where
    IntervalBound<RealType, Side, Open>: ValueWithinBound<RealType = RealType>,
    IntervalBound<RealType, Side, Closed>: ValueWithinBound<RealType = RealType>,
{
    type RealType = RealType;

    #[inline(always)]
    fn value_within_bound(&self, value: &RealType) -> bool {
        match self {
            IntervalBoundRuntime::Open(bound) => bound.value_within_bound(value),
            IntervalBoundRuntime::Closed(bound) => bound.value_within_bound(value),
        }
    }
}

impl<RealType: RealScalar, Side: BoundSide> AsRef<RealType>
    for IntervalBoundRuntime<RealType, Side>
{
    #[inline(always)]
    fn as_ref(&self) -> &RealType {
        match self {
            IntervalBoundRuntime::Open(bound) => bound.as_ref(),
            IntervalBoundRuntime::Closed(bound) => bound.as_ref(),
        }
    }
}

impl<RealType: RealScalar, Side: BoundSide> IntoInner for IntervalBoundRuntime<RealType, Side> {
    type InnerType = RealType;

    #[inline(always)]
    fn into_inner(self) -> RealType {
        match self {
            IntervalBoundRuntime::Open(bound) => bound.into_inner(),
            IntervalBoundRuntime::Closed(bound) => bound.into_inner(),
        }
    }
}

impl<RealType: RealScalar, Side: BoundSide> BoundChecks for IntervalBoundRuntime<RealType, Side> where
    Self: BoundSideChecks
{
}

#[duplicate_item(
    Type;
    [Open];
    [Closed];
)]
impl<RealType: RealScalar, Side: BoundSide> From<IntervalBound<RealType, Side, Type>>
    for IntervalBoundRuntime<RealType, Side>
{
    #[inline(always)]
    fn from(bound: IntervalBound<RealType, Side, Type>) -> Self {
        IntervalBoundRuntime::Type(bound)
    }
}

impl<RealType: RealScalar> PartialOrd for LowerBoundRuntime<RealType> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        if self.as_ref() == other.as_ref() {
            // Same value, closed is "less than" open
            Some(match (self, other) {
                (LowerBoundRuntime::Closed(_), LowerBoundRuntime::Open(_)) => Ordering::Less,
                (LowerBoundRuntime::Open(_), LowerBoundRuntime::Closed(_)) => Ordering::Greater,
                _ => Ordering::Equal,
            })
        } else {
            // different values, compare normally
            self.as_ref().partial_cmp(other.as_ref())
        }
    }
}

impl<RealType: RealScalar> PartialOrd for UpperBoundRuntime<RealType> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        if self.as_ref() == other.as_ref() {
            // Same value, closed is "less than" open
            Some(match (self, other) {
                (UpperBoundRuntime::Closed(_), UpperBoundRuntime::Open(_)) => Ordering::Greater,
                (UpperBoundRuntime::Open(_), UpperBoundRuntime::Closed(_)) => Ordering::Less,
                _ => Ordering::Equal,
            })
        } else {
            // different values, compare normally
            self.as_ref().partial_cmp(other.as_ref())
        }
    }
}
//------------------------------------------------------------------------------------------------

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

    mod lower_bound {
        use super::*;
        use crate::bounds::{LowerBoundClosed, LowerBoundOpen};
        use std::cmp::Ordering;

        #[test]
        fn test_interval_lower_bound_equality() {
            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let closed_3 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));

            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
            let open_2 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));

            // Test equality for same variant and value
            assert_eq!(closed_1, closed_2);
            assert_eq!(open_1, open_2);

            // Test inequality for different values
            assert_ne!(closed_1, closed_3);

            // Test inequality for different variants, same value
            assert_ne!(closed_1, open_1);
        }

        mod interval_upper_bound {
            use super::*;
            use crate::bounds::{UpperBoundClosed, UpperBoundOpen};
            use std::cmp::Ordering;

            #[test]
            fn test_interval_upper_bound_equality() {
                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                let closed_3 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));

                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
                let open_2 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));

                // Test equality for same variant and value
                assert_eq!(closed_1, closed_2);
                assert_eq!(open_1, open_2);

                // Test inequality for different values
                assert_ne!(closed_1, closed_3);

                // Test inequality for different variants, same value
                assert_ne!(closed_1, open_1);
            }

            #[test]
            fn test_interval_upper_bound_partial_ord() {
                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
                let open_2 = UpperBoundRuntime::Open(UpperBoundOpen::new(2.0));

                // Test closed vs closed
                assert_eq!(closed_1.partial_cmp(&closed_1), Some(Ordering::Equal));
                assert_eq!(closed_1.partial_cmp(&closed_2), Some(Ordering::Less));
                assert_eq!(closed_2.partial_cmp(&closed_1), Some(Ordering::Greater));

                // Test open vs open
                assert_eq!(open_1.partial_cmp(&open_1), Some(Ordering::Equal));
                assert_eq!(open_1.partial_cmp(&open_2), Some(Ordering::Less));
                assert_eq!(open_2.partial_cmp(&open_1), Some(Ordering::Greater));

                // Test open vs closed with same value (open < closed for upper bounds)
                assert_eq!(open_1.partial_cmp(&closed_1), Some(Ordering::Less));
                assert_eq!(closed_1.partial_cmp(&open_1), Some(Ordering::Greater));

                // Test open vs closed with different values
                assert_eq!(open_1.partial_cmp(&closed_2), Some(Ordering::Less));
                assert_eq!(closed_1.partial_cmp(&open_2), Some(Ordering::Less));
            }

            #[test]
            fn test_interval_upper_bound_ordering_consistency() {
                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
                let open_2 = UpperBoundRuntime::Open(UpperBoundOpen::new(2.0));

                // Create sorted list based on expected ordering
                // For upper bounds: smaller values < larger values, and open < closed for same value
                let bounds = vec![
                    open_1.clone(),
                    closed_1.clone(),
                    open_2.clone(),
                    closed_2.clone(),
                ];

                // Test that the ordering is consistent
                for i in 0..bounds.len() {
                    for j in i + 1..bounds.len() {
                        assert!(bounds[i] < bounds[j],);
                        assert!(bounds[j] > bounds[i],);
                    }
                }

                // Test sorting
                let mut shuffled = bounds.clone();
                shuffled.reverse();
                shuffled.sort_by(|a, b| a.partial_cmp(b).unwrap());
                assert_eq!(shuffled, bounds);
            }

            #[test]
            fn test_interval_upper_bound_edge_cases() {
                // Test with special floating point values
                let closed_zero = UpperBoundRuntime::Closed(UpperBoundClosed::new(0.0));
                let closed_neg_zero = UpperBoundRuntime::Closed(UpperBoundClosed::new(-0.0));
                let open_zero = UpperBoundRuntime::Open(UpperBoundOpen::new(0.0));

                // 0.0 and -0.0 should be equal
                assert_eq!(closed_zero, closed_neg_zero);

                // But closed and open should be different even with same value
                assert_ne!(closed_zero, open_zero);
                assert!(open_zero < closed_zero); // open < closed for upper bounds

                // Test with very small differences
                let closed_small = UpperBoundRuntime::Closed(UpperBoundClosed::new(1e-15));
                let open_small = UpperBoundRuntime::Open(UpperBoundOpen::new(1e-15));
                assert!(open_small < closed_small);
            }

            #[test]
            fn test_interval_upper_bound_transitivity() {
                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));

                // Test transitivity: if a < b and b < c, then a < c
                assert!(open_1 < closed_1);
                assert!(closed_1 < closed_2);
                assert!(open_1 < closed_2); // transitivity
            }

            #[test]
            fn test_interval_upper_bound_reflexivity() {
                let closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                let open = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));

                // Test reflexivity: a == a
                assert_eq!(closed.partial_cmp(&closed), Some(Ordering::Equal));
                assert_eq!(open.partial_cmp(&open), Some(Ordering::Equal));
            }

            #[test]
            fn test_interval_upper_bound_antisymmetry() {
                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));
                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));

                // Test antisymmetry: if a <= b and b <= a, then a == b
                // (This should only happen when a == b)
                assert_eq!(closed_1.partial_cmp(&closed_1), Some(Ordering::Equal));

                // When a < b, then b > a (not equal)
                assert_eq!(closed_1.partial_cmp(&closed_2), Some(Ordering::Less));
                assert_eq!(closed_2.partial_cmp(&closed_1), Some(Ordering::Greater));

                assert_eq!(open_1.partial_cmp(&closed_1), Some(Ordering::Less));
                assert_eq!(closed_1.partial_cmp(&open_1), Some(Ordering::Greater));
            }

            #[test]
            fn test_min_upper_bound() {
                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));

                // min with same value, different types should be open (smaller for upper bounds)
                assert_eq!(min_upper_bound(closed_1.clone(), open_1.clone()), open_1);
                assert_eq!(min_upper_bound(open_1.clone(), closed_1.clone()), open_1);

                // min with different values
                assert_eq!(
                    min_upper_bound(closed_1.clone(), closed_2.clone()),
                    closed_1
                );
                assert_eq!(
                    min_upper_bound(closed_2.clone(), closed_1.clone()),
                    closed_1
                );

                // min with same bound should return that bound
                assert_eq!(
                    min_upper_bound(closed_1.clone(), closed_1.clone()),
                    closed_1
                );
            }

            #[test]
            fn test_max_upper_bound() {
                let closed_1 = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                let open_1 = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
                let closed_2 = UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0));

                // max with same value, different types should be closed (larger for upper bounds)
                assert_eq!(max_upper_bound(closed_1.clone(), open_1.clone()), closed_1);
                assert_eq!(max_upper_bound(open_1.clone(), closed_1.clone()), closed_1);

                // max with different values
                assert_eq!(
                    max_upper_bound(closed_1.clone(), closed_2.clone()),
                    closed_2
                );
                assert_eq!(
                    max_upper_bound(closed_2.clone(), closed_1.clone()),
                    closed_2
                );

                // max with same bound should return that bound
                assert_eq!(
                    max_upper_bound(closed_1.clone(), closed_1.clone()),
                    closed_1
                );
            }

            #[test]
            fn test_interval_upper_bound_with_negative_values() {
                let closed_neg = UpperBoundRuntime::Closed(UpperBoundClosed::new(-5.0));
                let open_neg = UpperBoundRuntime::Open(UpperBoundOpen::new(-5.0));
                let closed_pos = UpperBoundRuntime::Closed(UpperBoundClosed::new(5.0));

                // Negative values should still follow the ordering rules
                assert!(open_neg < closed_neg);
                assert!(closed_neg < closed_pos);

                // More negative values should be smaller
                let closed_more_neg = UpperBoundRuntime::Closed(UpperBoundClosed::new(-10.0));
                assert!(closed_more_neg < closed_neg);
            }

            #[test]
            fn test_interval_upper_bound_with_large_values() {
                let closed_large = UpperBoundRuntime::Closed(UpperBoundClosed::new(1e6));
                let open_large = UpperBoundRuntime::Open(UpperBoundOpen::new(1e6));
                let closed_larger = UpperBoundRuntime::Closed(UpperBoundClosed::new(1e9));

                // Large values should still follow ordering
                assert!(open_large < closed_large);
                assert!(closed_large < closed_larger);

                // Should be consistent with regular values
                let closed_small = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
                assert!(closed_small < closed_large);
            }

            #[test]
            fn test_interval_upper_bound_boundary_semantics() {
                // Test the key difference between upper and lower bounds:
                // For upper bounds, open < closed (opposite of lower bounds)

                let open_5 = UpperBoundRuntime::Open(UpperBoundOpen::new(5.0));
                let closed_5 = UpperBoundRuntime::Closed(UpperBoundClosed::new(5.0));

                // For upper bounds: open is more restrictive (smaller) than closed
                assert!(open_5 < closed_5);
                assert!(closed_5 > open_5);

                // This reflects the fact that (-∞, 5) ⊂ (-∞, 5]
                // The open upper bound excludes the endpoint, making it "smaller"
            }
        }

        #[test]
        fn test_interval_lower_bound_partial_ord() {
            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));
            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
            let open_2 = LowerBoundRuntime::Open(LowerBoundOpen::new(2.0));

            // Test closed vs closed
            assert_eq!(closed_1.partial_cmp(&closed_1), Some(Ordering::Equal));
            assert_eq!(closed_1.partial_cmp(&closed_2), Some(Ordering::Less));
            assert_eq!(closed_2.partial_cmp(&closed_1), Some(Ordering::Greater));

            // Test open vs open
            assert_eq!(open_1.partial_cmp(&open_1), Some(Ordering::Equal));
            assert_eq!(open_1.partial_cmp(&open_2), Some(Ordering::Less));
            assert_eq!(open_2.partial_cmp(&open_1), Some(Ordering::Greater));

            // Test closed vs open with same value (closed < open)
            assert_eq!(closed_1.partial_cmp(&open_1), Some(Ordering::Less));
            assert_eq!(open_1.partial_cmp(&closed_1), Some(Ordering::Greater));

            // Test closed vs open with different values
            assert_eq!(closed_1.partial_cmp(&open_2), Some(Ordering::Less));
            assert_eq!(open_1.partial_cmp(&closed_2), Some(Ordering::Less));
        }

        #[test]
        fn test_interval_lower_bound_ordering_consistency() {
            let closed_0 = LowerBoundRuntime::Closed(LowerBoundClosed::new(0.0));
            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let open_0 = LowerBoundRuntime::Open(LowerBoundOpen::new(0.0));
            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));

            // Create sorted list based on expected ordering
            let bounds = vec![
                closed_0.clone(),
                open_0.clone(),
                closed_1.clone(),
                open_1.clone(),
            ];

            // Test that the ordering is consistent
            for i in 0..bounds.len() {
                for j in i + 1..bounds.len() {
                    assert!(bounds[i] < bounds[j],);
                    assert!(bounds[j] > bounds[i],);
                }
            }

            // Test sorting
            let mut shuffled = bounds.clone();
            shuffled.reverse();
            shuffled.sort_by(|a, b| a.partial_cmp(b).unwrap());
            assert_eq!(shuffled, bounds);
        }

        #[test]
        fn test_interval_lower_bound_edge_cases() {
            // Test with special floating point values
            let closed_zero = LowerBoundRuntime::Closed(LowerBoundClosed::new(0.0));
            let closed_neg_zero = LowerBoundRuntime::Closed(LowerBoundClosed::new(-0.0));
            let open_zero = LowerBoundRuntime::Open(LowerBoundOpen::new(0.0));

            // 0.0 and -0.0 should be equal
            assert_eq!(closed_zero, closed_neg_zero);

            // But closed and open should be different even with same value
            assert_ne!(closed_zero, open_zero);
            assert!(closed_zero < open_zero);

            // Test with very small differences
            let closed_small = LowerBoundRuntime::Closed(LowerBoundClosed::new(1e-15));
            let open_small = LowerBoundRuntime::Open(LowerBoundOpen::new(1e-15));
            assert!(closed_small < open_small);
        }

        #[test]
        fn test_interval_lower_bound_transitivity() {
            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));

            // Test transitivity: if a < b and b < c, then a < c
            assert!(closed_1 < open_1);

            assert!(open_1 < closed_2);
            assert!(closed_1 < closed_2); // transitivity
        }

        #[test]
        fn test_interval_lower_bound_reflexivity() {
            let closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let open = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));

            // Test reflexivity: a == a
            assert_eq!(closed.partial_cmp(&closed), Some(Ordering::Equal));
            assert_eq!(open.partial_cmp(&open), Some(Ordering::Equal));
        }

        #[test]
        fn test_interval_lower_bound_antisymmetry() {
            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));
            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));

            // Test antisymmetry: if a <= b and b <= a, then a == b
            // (This should only happen when a == b)
            assert_eq!(closed_1.partial_cmp(&closed_1), Some(Ordering::Equal));

            // When a < b, then b > a (not equal)
            assert_eq!(closed_1.partial_cmp(&closed_2), Some(Ordering::Less));
            assert_eq!(closed_2.partial_cmp(&closed_1), Some(Ordering::Greater));

            assert_eq!(closed_1.partial_cmp(&open_1), Some(Ordering::Less));
            assert_eq!(open_1.partial_cmp(&closed_1), Some(Ordering::Greater));
        }

        #[test]
        fn test_min_lower_bound() {
            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));

            // min with same value, different types should be closed (smaller)
            assert_eq!(min_lower_bound(closed_1.clone(), open_1.clone()), closed_1);
            assert_eq!(min_lower_bound(open_1.clone(), closed_1.clone()), closed_1);

            // min with different values
            assert_eq!(
                min_lower_bound(closed_1.clone(), closed_2.clone()),
                closed_1
            );
            assert_eq!(
                min_lower_bound(closed_2.clone(), closed_1.clone()),
                closed_1
            );

            // min with same bound should return that bound
            assert_eq!(
                min_lower_bound(closed_1.clone(), closed_1.clone()),
                closed_1
            );
        }

        #[test]
        fn test_max_lower_bound() {
            let closed_1 = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let open_1 = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
            let closed_2 = LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0));

            // max with same value, different types should be open (larger)
            assert_eq!(max_lower_bound(closed_1.clone(), open_1.clone()), open_1);
            assert_eq!(max_lower_bound(open_1.clone(), closed_1.clone()), open_1);

            // max with different values
            assert_eq!(
                max_lower_bound(closed_1.clone(), closed_2.clone()),
                closed_2
            );
            assert_eq!(
                max_lower_bound(closed_2.clone(), closed_1.clone()),
                closed_2
            );

            // max with same bound should return that bound
            assert_eq!(
                max_lower_bound(closed_1.clone(), closed_1.clone()),
                closed_1
            );
        }

        #[test]
        fn test_interval_lower_bound_with_negative_values() {
            let closed_neg = LowerBoundRuntime::Closed(LowerBoundClosed::new(-5.0));
            let open_neg = LowerBoundRuntime::Open(LowerBoundOpen::new(-5.0));
            let closed_pos = LowerBoundRuntime::Closed(LowerBoundClosed::new(5.0));

            // Negative values should still follow the ordering rules
            assert!(closed_neg < open_neg);
            assert!(open_neg < closed_pos);

            // More negative values should be smaller
            let closed_more_neg = LowerBoundRuntime::Closed(LowerBoundClosed::new(-10.0));
            assert!(closed_more_neg < closed_neg);
        }

        #[test]
        fn test_interval_lower_bound_with_large_values() {
            let closed_large = LowerBoundRuntime::Closed(LowerBoundClosed::new(1e6));
            let open_large = LowerBoundRuntime::Open(LowerBoundOpen::new(1e6));
            let closed_larger = LowerBoundRuntime::Closed(LowerBoundClosed::new(1e9));

            // Large values should still follow ordering
            assert!(closed_large < open_large);
            assert!(open_large < closed_larger);

            // Should be consistent with regular values
            let closed_small = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            assert!(closed_small < closed_large);
        }
    }

    mod interval_bounds_runtime {
        use super::*;
        use crate::intervals::*;

        #[test]
        fn get_interval_bound_closed() {
            let interval = IntervalClosed::new(1.0, 2.0);

            let lower = interval.lower_bound_runtime().unwrap();
            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));

            let upper = interval.upper_bound_runtime().unwrap();
            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
        }

        #[test]
        fn get_interval_bound_open() {
            let interval = IntervalOpen::new(1.0, 2.0);

            let lower = interval.lower_bound_runtime().unwrap();
            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));

            let upper = interval.upper_bound_runtime().unwrap();
            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
        }

        #[test]
        fn get_interval_bound_left_open_upper_closed() {
            let interval = IntervalLowerOpenUpperClosed::new(1.0, 2.0);

            let lower = interval.lower_bound_runtime().unwrap();
            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));

            let upper = interval.upper_bound_runtime().unwrap();
            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
        }

        #[test]
        fn get_interval_bound_left_closed_upper_open() {
            let interval = IntervalLowerClosedUpperOpen::new(1.0, 2.0);

            let lower = interval.lower_bound_runtime().unwrap();
            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));

            let upper = interval.upper_bound_runtime().unwrap();
            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
        }

        #[test]
        fn get_interval_bound_lower_closed_upper_unbounded() {
            let interval = IntervalLowerClosedUpperUnbounded::new(1.0);

            let lower = interval.lower_bound_runtime().unwrap();
            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));

            let upper = interval.upper_bound_runtime();
            assert_eq!(upper, None);
        }

        #[test]
        fn get_interval_bound_lower_open_upper_unbounded() {
            let interval = IntervalLowerOpenUpperUnbounded::new(1.0);

            let lower = interval.lower_bound_runtime().unwrap();
            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));

            let upper = interval.upper_bound_runtime();
            assert_eq!(upper, None);
        }

        #[test]
        fn get_interval_bound_lower_unbounded_upper_closed() {
            let interval = IntervalLowerUnboundedUpperClosed::new(2.0);

            let lower = interval.lower_bound_runtime();
            assert_eq!(lower, None);

            let upper = interval.upper_bound_runtime().unwrap();
            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
        }

        #[test]
        fn get_interval_bound_lower_unbounded_upper_open() {
            let interval = IntervalLowerUnboundedUpperOpen::new(2.0);

            let lower = interval.lower_bound_runtime();
            assert_eq!(lower, None);

            let upper = interval.upper_bound_runtime().unwrap();
            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
        }

        #[test]
        fn get_interval_bound_singleton() {
            let interval = IntervalSingleton::new(1.5);

            let lower = interval.lower_bound_runtime().unwrap();
            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.5)));

            let upper = interval.upper_bound_runtime().unwrap();
            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(1.5)));
        }

        #[test]
        fn get_interval_bound_finite_length() {
            let closed = IntervalClosed::new(1.0, 2.0);
            let singleton = IntervalSingleton::new(1.5);
            let finite =
                IntervalFiniteLength::PositiveLength(IntervalFinitePositiveLength::Closed(closed));
            let zero = IntervalFiniteLength::ZeroLength(singleton);

            let lower = finite.lower_bound_runtime().unwrap();
            let upper = finite.upper_bound_runtime().unwrap();
            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));
            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));

            let lower = zero.lower_bound_runtime().unwrap();
            let upper = zero.upper_bound_runtime().unwrap();
            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.5)));
            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(1.5)));
        }

        #[test]
        fn get_interval_bound_finite_positive_length() {
            use crate::intervals::IntervalFinitePositiveLengthTrait;

            let closed = IntervalClosed::new(1.0, 2.0);
            let open = IntervalOpen::new(1.0, 2.0);
            let left = IntervalLowerOpenUpperClosed::new(1.0, 2.0);
            let right = IntervalLowerClosedUpperOpen::new(1.0, 2.0);

            let c = IntervalFinitePositiveLength::Closed(closed);
            let o = IntervalFinitePositiveLength::Open(open);
            let l = IntervalFinitePositiveLength::LowerOpenUpperClosed(left);
            let r = IntervalFinitePositiveLength::LowerClosedUpperOpen(right);

            let (lower, upper) = (
                c.lower_bound_runtime().unwrap(),
                c.upper_bound_runtime().unwrap(),
            );
            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));
            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
            assert_eq!(c.clone().into_bounds_pair(), (1., 2.));

            let (lower, upper) = (
                o.lower_bound_runtime().unwrap(),
                o.upper_bound_runtime().unwrap(),
            );
            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));
            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
            assert_eq!(o.clone().into_bounds_pair(), (1., 2.));

            let (lower, upper) = (
                l.lower_bound_runtime().unwrap(),
                l.upper_bound_runtime().unwrap(),
            );
            assert_eq!(lower, LowerBoundRuntime::Open(LowerBoundOpen::new(1.0)));
            assert_eq!(upper, UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0)));
            assert_eq!(l.clone().into_bounds_pair(), (1., 2.));

            let (lower, upper) = (
                r.lower_bound_runtime().unwrap(),
                r.upper_bound_runtime().unwrap(),
            );
            assert_eq!(lower, LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)));
            assert_eq!(upper, UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)));
            assert_eq!(r.clone().into_bounds_pair(), (1., 2.));
        }

        #[test]
        fn get_interval_bound_infinite_length() {
            let closed = IntervalLowerClosedUpperUnbounded::new(1.0);
            let open = IntervalLowerOpenUpperUnbounded::new(2.0);
            let right_closed = IntervalLowerUnboundedUpperClosed::new(3.0);
            let right_open = IntervalLowerUnboundedUpperOpen::new(4.0);
            let unbounded = IntervalLowerUnboundedUpperUnbounded::<f64>::new();

            let c = IntervalInfiniteLength::LowerClosedUpperUnbounded(closed);
            let o = IntervalInfiniteLength::LowerOpenUpperUnbounded(open);
            let rc = IntervalInfiniteLength::LowerUnboundedUpperClosed(right_closed);
            let ro = IntervalInfiniteLength::LowerUnboundedUpperOpen(right_open);
            let u = IntervalInfiniteLength::LowerUnboundedUpperUnbounded(unbounded);

            let (lower, upper) = (c.lower_bound_runtime(), c.upper_bound_runtime());
            assert_eq!(
                lower.unwrap(),
                LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0))
            );
            assert_eq!(upper, None);

            let (lower, upper) = (o.lower_bound_runtime(), o.upper_bound_runtime());
            assert_eq!(
                lower.unwrap(),
                LowerBoundRuntime::Open(LowerBoundOpen::new(2.0))
            );
            assert_eq!(upper, None);

            let (lower, upper) = (rc.lower_bound_runtime(), rc.upper_bound_runtime());
            assert_eq!(lower, None);
            assert_eq!(
                upper.unwrap(),
                UpperBoundRuntime::Closed(UpperBoundClosed::new(3.0))
            );

            let (lower, upper) = (ro.lower_bound_runtime(), ro.upper_bound_runtime());
            assert_eq!(lower, None);
            assert_eq!(
                upper.unwrap(),
                UpperBoundRuntime::Open(UpperBoundOpen::new(4.0))
            );

            let (lower, upper) = (u.lower_bound_runtime(), u.upper_bound_runtime());
            assert_eq!(lower, None);
            assert_eq!(upper, None);
        }

        #[test]
        fn get_interval_bound_enum_wrappers() {
            let closed = IntervalClosed::new(1.0, 2.0);
            let finite =
                IntervalFiniteLength::PositiveLength(IntervalFinitePositiveLength::Closed(closed));
            let inf = IntervalInfiniteLength::LowerUnboundedUpperUnbounded(
                IntervalLowerUnboundedUpperUnbounded::<f64>::new(),
            );
            let interval = Interval::FiniteLength(finite.clone());
            let interval_inf = Interval::InfiniteLength(inf.clone());

            let (lower, upper) = (
                interval.lower_bound_runtime(),
                interval.upper_bound_runtime(),
            );
            assert_eq!(
                lower.unwrap(),
                LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0))
            );
            assert_eq!(
                upper.unwrap(),
                UpperBoundRuntime::Closed(UpperBoundClosed::new(2.0))
            );

            let (lower, upper) = (
                interval_inf.lower_bound_runtime(),
                interval_inf.upper_bound_runtime(),
            );
            assert_eq!(lower, None);
            assert_eq!(upper, None);
        }

        #[test]
        fn get_interval_bound_subinterval_in_partition() {
            type S = SubIntervalInPartition<IntervalClosed<f64>>;
            let first = IntervalLowerClosedUpperOpen::new(1.0, 2.0);
            let last = IntervalClosed::new(2.0, 3.0);
            let s1 = S::First(first);
            let s2 = S::Last(last);

            let (lower, upper) = (s1.lower_bound_runtime(), s1.upper_bound_runtime());
            assert_eq!(
                lower,
                Some(LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0)))
            );
            assert_eq!(
                upper,
                Some(UpperBoundRuntime::Open(UpperBoundOpen::new(2.0)))
            );

            let (lower, upper) = (s2.lower_bound_runtime(), s2.upper_bound_runtime());
            assert_eq!(
                lower,
                Some(LowerBoundRuntime::Closed(LowerBoundClosed::new(2.0)))
            );
            assert_eq!(
                upper,
                Some(UpperBoundRuntime::Closed(UpperBoundClosed::new(3.0)))
            );
        }
    }

    mod partial_ord {
        use super::*;

        #[test]
        fn partial_ord_lower_bound_structs() {
            let closed1 = LowerBoundClosed::new(1.0);
            let closed2 = LowerBoundClosed::new(2.0);
            let open1 = LowerBoundOpen::new(1.0);
            let open2 = LowerBoundOpen::new(2.0);

            assert!(closed1 < closed2);
            assert!(open1 < open2);
            assert!(closed1 < open2);
            assert!(open1 < closed2);
            assert!(closed1 < open1); // closed < open if same value
            assert!(open2 > closed1);
            assert!(closed1 <= closed1);
            assert!(open2 >= open2);
            assert!(!(closed1 == open1));
        }

        #[test]
        fn partial_ord_upper_bound_structs() {
            let closed1 = UpperBoundClosed::new(1.0);
            let closed2 = UpperBoundClosed::new(2.0);
            let open1 = UpperBoundOpen::new(1.0);
            let open2 = UpperBoundOpen::new(2.0);

            assert!(closed1 < closed2);
            assert!(open1 < open2);
            assert!(closed1 < open2);
            assert!(open1 < closed2);
            assert!(open1 < closed1); // open < closed if same value
            assert!(closed2 > open1);
            assert!(closed1 <= closed1);
            assert!(open2 >= open2);
            assert!(!(closed1 == open1));
        }

        #[test]
        fn partial_ord_interval_lower_bound_enum() {
            let closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let open = LowerBoundRuntime::Open(LowerBoundOpen::new(2.0));

            assert_eq!(closed.partial_cmp(&open), Some(std::cmp::Ordering::Less));
            assert_eq!(open.partial_cmp(&closed), Some(std::cmp::Ordering::Greater));
            assert_eq!(closed.partial_cmp(&closed), Some(std::cmp::Ordering::Equal));
            assert_eq!(open.partial_cmp(&open), Some(std::cmp::Ordering::Equal));
        }

        #[test]
        fn partial_ord_interval_upper_bound_enum() {
            let closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
            let open = UpperBoundRuntime::Open(UpperBoundOpen::new(2.0));

            assert_eq!(closed.partial_cmp(&open), Some(std::cmp::Ordering::Less));
            assert_eq!(open.partial_cmp(&closed), Some(std::cmp::Ordering::Greater));
            assert_eq!(closed.partial_cmp(&closed), Some(std::cmp::Ordering::Equal));
            assert_eq!(open.partial_cmp(&open), Some(std::cmp::Ordering::Equal));
        }

        #[test]
        fn partial_ord_interval_lower_bound_enum_same_value() {
            let closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(1.0));
            let open = LowerBoundRuntime::Open(LowerBoundOpen::new(1.0));
            assert_eq!(closed.partial_cmp(&open), Some(std::cmp::Ordering::Less));
            assert_eq!(open.partial_cmp(&closed), Some(std::cmp::Ordering::Greater));
        }

        #[test]
        fn partial_ord_interval_upper_bound_enum_same_value() {
            let closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(1.0));
            let open = UpperBoundRuntime::Open(UpperBoundOpen::new(1.0));
            assert_eq!(open.partial_cmp(&closed), Some(std::cmp::Ordering::Less));
            assert_eq!(closed.partial_cmp(&open), Some(std::cmp::Ordering::Greater));
        }
    }

    mod bounds_comparisons {
        use super::*;
        use try_create::TryNew;

        type Real = f64;

        /// Test PartialOrd implementation for LowerBoundRuntime
        #[test]
        fn test_interval_lower_bound_comparison() {
            // Create test bounds
            let lower_bound_closed_5 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
            let lower_bound_open_5 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
            let lower_bound_closed_3 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
            let lower_bound_open_3 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(3.0).unwrap()));
            let lower_bound_closed_7 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(7.0).unwrap()));

            // Test basic ordering by value
            assert_eq!(
                lower_bound_closed_3.partial_cmp(&lower_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_closed_5.partial_cmp(&lower_bound_closed_3),
                Some(Ordering::Greater)
            );
            assert_eq!(
                lower_bound_closed_5.partial_cmp(&lower_bound_closed_5),
                Some(Ordering::Equal)
            );

            // Test ordering between closed and open bounds with same value
            // For lower bounds: closed < open at same value (closed is more restrictive for lower)
            assert_eq!(
                lower_bound_closed_5.partial_cmp(&lower_bound_open_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_open_5.partial_cmp(&lower_bound_closed_5),
                Some(Ordering::Greater)
            );

            // Test mixed value and boundary type comparisons
            assert_eq!(
                lower_bound_closed_3.partial_cmp(&lower_bound_open_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_open_3.partial_cmp(&lower_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_closed_5.partial_cmp(&lower_bound_open_3),
                Some(Ordering::Greater)
            );

            // Test transitivity
            assert_eq!(
                lower_bound_closed_3.partial_cmp(&lower_bound_closed_7),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_open_3.partial_cmp(&lower_bound_closed_7),
                Some(Ordering::Less)
            );
        }

        /// Test PartialOrd implementation for UpperBoundRuntime
        #[test]
        fn test_interval_upper_bound_comparison() {
            // Create test bounds
            let upper_bound_closed_5 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
            let upper_bound_open_5 =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));
            let upper_bound_closed_3 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(3.0).unwrap()));
            let upper_bound_open_3 =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(3.0).unwrap()));
            let upper_bound_closed_7 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(7.0).unwrap()));

            // Test basic ordering by value
            assert_eq!(
                upper_bound_closed_3.partial_cmp(&upper_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_closed_5.partial_cmp(&upper_bound_closed_3),
                Some(Ordering::Greater)
            );
            assert_eq!(
                upper_bound_closed_5.partial_cmp(&upper_bound_closed_5),
                Some(Ordering::Equal)
            );

            // Test ordering between closed and open bounds with same value
            // For upper bounds: open < closed at same value (open is more restrictive for upper)
            assert_eq!(
                upper_bound_open_5.partial_cmp(&upper_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_closed_5.partial_cmp(&upper_bound_open_5),
                Some(Ordering::Greater)
            );

            // Test mixed value and boundary type comparisons
            assert_eq!(
                upper_bound_closed_3.partial_cmp(&upper_bound_open_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_open_3.partial_cmp(&upper_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_closed_5.partial_cmp(&upper_bound_open_3),
                Some(Ordering::Greater)
            );

            // Test transitivity
            assert_eq!(
                upper_bound_closed_3.partial_cmp(&upper_bound_closed_7),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_open_3.partial_cmp(&upper_bound_closed_7),
                Some(Ordering::Less)
            );
        }

        /// Test boundary type semantics for lower bounds
        #[test]
        fn test_lower_bound_semantics() {
            let closed_5 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
            let open_5 = LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));

            // For lower bounds, closed is more restrictive (smaller) than open at same value
            // This is because [5,b) contains 5, while (5,b) does not
            more_asserts::assert_lt!(closed_5, open_5);
            more_asserts::assert_ge!(open_5, closed_5);
            assert_ne!(closed_5, open_5);
        }

        /// Test boundary type semantics for upper bounds
        #[test]
        fn test_upper_bound_semantics() {
            let closed_5 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
            let open_5 = UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));

            // For upper bounds, open is more restrictive (smaller) than closed at same value
            // This is because [a,5) excludes 5, while [a,5] includes 5
            more_asserts::assert_lt!(open_5, closed_5);
            more_asserts::assert_ge!(closed_5, open_5);
            assert_ne!(open_5, closed_5);
        }

        /// Test consistency with mathematical interval ordering
        #[test]
        fn test_mathematical_consistency() {
            // Create bounds that would represent valid intervals
            let lower_closed_1 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(1.0).unwrap()));
            let lower_open_1 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(1.0).unwrap()));
            let upper_open_2 =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(2.0).unwrap()));
            let upper_closed_2 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(2.0).unwrap()));

            // Mathematical consistency checks:
            // [1,2) should have closed lower bound and open upper bound
            // (1,2] should have open lower bound and closed upper bound
            // [1,2] should have closed bounds
            // (1,2) should have open bounds

            // Verify ordering is consistent with interval containment
            // [1,x] contains more points than (1,x] at the same x
            assert!(lower_closed_1 < lower_open_1);

            // [x,2) contains fewer points than [x,2] at the same x
            assert!(upper_open_2 < upper_closed_2);
        }

        /// Test reflexivity property
        #[test]
        fn test_reflexivity() {
            let lower_closed =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
            let lower_open =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
            let upper_closed =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
            let upper_open =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));

            // Reflexivity: x.partial_cmp(&x) == Some(Ordering::Equal)
            assert_eq!(
                lower_closed.partial_cmp(&lower_closed),
                Some(Ordering::Equal)
            );
            assert_eq!(lower_open.partial_cmp(&lower_open), Some(Ordering::Equal));
            assert_eq!(
                upper_closed.partial_cmp(&upper_closed),
                Some(Ordering::Equal)
            );
            assert_eq!(upper_open.partial_cmp(&upper_open), Some(Ordering::Equal));
        }

        /// Test antisymmetry property
        #[test]
        fn test_antisymmetry() {
            let lower_closed_3 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
            let lower_closed_5 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));

            // Antisymmetry: if x <= y and y <= x, then x == y
            if lower_closed_3.partial_cmp(&lower_closed_5) == Some(Ordering::Less) {
                assert_eq!(
                    lower_closed_5.partial_cmp(&lower_closed_3),
                    Some(Ordering::Greater)
                );
            }
        }

        /// Test transitivity property
        #[test]
        fn test_transitivity() {
            let lower_closed_1 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(1.0).unwrap()));
            let lower_open_3 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(3.0).unwrap()));
            let lower_closed_5 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));

            // Transitivity: if x <= y and y <= z, then x <= z
            let ord_1_3 = lower_closed_1.partial_cmp(&lower_open_3);
            let ord_3_5 = lower_open_3.partial_cmp(&lower_closed_5);
            let ord_1_5 = lower_closed_1.partial_cmp(&lower_closed_5);

            if ord_1_3 == Some(Ordering::Less) && ord_3_5 == Some(Ordering::Less) {
                assert_eq!(ord_1_5, Some(Ordering::Less));
            }
        }

        /// Test edge cases with same values but different boundary types
        #[test]
        fn test_edge_cases_same_values() {
            let value = Real::try_new(42.0).unwrap();

            let lower_closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(value));
            let lower_open = LowerBoundRuntime::Open(LowerBoundOpen::new(value));
            let upper_closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(value));
            let upper_open = UpperBoundRuntime::Open(UpperBoundOpen::new(value));

            // Test that boundary type matters even with same value
            assert_ne!(lower_closed.partial_cmp(&lower_open), Some(Ordering::Equal));
            assert_ne!(upper_closed.partial_cmp(&upper_open), Some(Ordering::Equal));

            // Verify specific ordering relationships
            assert_eq!(lower_closed.partial_cmp(&lower_open), Some(Ordering::Less));
            assert_eq!(upper_open.partial_cmp(&upper_closed), Some(Ordering::Less));
        }

        /// Test with extreme values
        #[test]
        fn test_extreme_values() {
            let min_val = Real::try_new(f64::MIN).unwrap();
            let max_val = Real::try_new(f64::MAX).unwrap();

            let lower_min_closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(min_val));
            let lower_max_open = LowerBoundRuntime::Open(LowerBoundOpen::new(max_val));
            let upper_min_open = UpperBoundRuntime::Open(UpperBoundOpen::new(min_val));
            let upper_max_closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(max_val));

            // Test that extreme values still follow ordering rules
            assert_eq!(
                lower_min_closed.partial_cmp(&lower_max_open),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_min_open.partial_cmp(&upper_max_closed),
                Some(Ordering::Less)
            );
        }

        /// Test helper functions min_lower_bound and max_lower_bound
        #[test]
        fn test_min_max_lower_bound() {
            let lower_closed_3 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
            let lower_open_5 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));

            // Test min_lower_bound
            let min_result = min_lower_bound(lower_closed_3.clone(), lower_open_5.clone());
            assert_eq!(min_result, lower_closed_3);

            // Test max_lower_bound
            let max_result = max_lower_bound(lower_closed_3.clone(), lower_open_5.clone());
            assert_eq!(max_result, lower_open_5);
        }

        /// Test helper functions min_upper_bound and max_upper_bound
        #[test]
        fn test_min_max_upper_bound() {
            let upper_open_3 =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(3.0).unwrap()));
            let upper_closed_5 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));

            // Test min_upper_bound
            let min_result = min_upper_bound(upper_open_3.clone(), upper_closed_5.clone());
            assert_eq!(min_result, upper_open_3);

            // Test max_upper_bound
            let max_result = max_upper_bound(upper_open_3.clone(), upper_closed_5.clone());
            assert_eq!(max_result, upper_closed_5);
        }

        /// Test new_open and new_closed constructors for LowerBoundRuntime
        #[test]
        fn test_lower_bound_runtime_constructors() {
            let value = Real::try_new(5.0).unwrap();

            // Test new_open
            let open_bound = LowerBoundRuntime::new_open(value);
            assert!(open_bound.is_open());
            assert!(open_bound.is_open_variant());
            assert!(!open_bound.is_closed());
            assert!(!open_bound.is_closed_variant());
            assert_eq!(open_bound.as_ref(), &value);

            // Test new_closed
            let closed_bound = LowerBoundRuntime::new_closed(value);
            assert!(closed_bound.is_closed());
            assert!(closed_bound.is_closed_variant());
            assert!(!closed_bound.is_open());
            assert!(!closed_bound.is_open_variant());
            assert_eq!(closed_bound.as_ref(), &value);

            // Test constraint semantics for open bound
            assert!(!open_bound.value_within_bound(&value)); // 5 > 5 → false
            assert!(open_bound.value_within_bound(&Real::try_new(5.1).unwrap())); // 5.1 > 5 → true
            assert!(!open_bound.value_within_bound(&Real::try_new(4.9).unwrap())); // 4.9 > 5 → false

            // Test constraint semantics for closed bound
            assert!(closed_bound.value_within_bound(&value)); // 5 ≥ 5 → true
            assert!(closed_bound.value_within_bound(&Real::try_new(5.1).unwrap())); // 5.1 ≥ 5 → true
            assert!(!closed_bound.value_within_bound(&Real::try_new(4.9).unwrap())); // 4.9 ≥ 5 → false
        }

        /// Test new_open and new_closed constructors for UpperBoundRuntime
        #[test]
        fn test_upper_bound_runtime_constructors() {
            let value = Real::try_new(10.0).unwrap();

            // Test new_open
            let open_bound = UpperBoundRuntime::new_open(value);
            assert!(open_bound.is_open());
            assert!(open_bound.is_open_variant());
            assert!(!open_bound.is_closed());
            assert!(!open_bound.is_closed_variant());
            assert_eq!(open_bound.as_ref(), &value);

            // Test new_closed
            let closed_bound = UpperBoundRuntime::new_closed(value);
            assert!(closed_bound.is_closed());
            assert!(closed_bound.is_closed_variant());
            assert!(!closed_bound.is_open());
            assert!(!closed_bound.is_open_variant());
            assert_eq!(closed_bound.as_ref(), &value);

            // Test constraint semantics for open bound
            assert!(!open_bound.value_within_bound(&value)); // 10 < 10 → false
            assert!(open_bound.value_within_bound(&Real::try_new(9.9).unwrap())); // 9.9 < 10 → true
            assert!(!open_bound.value_within_bound(&Real::try_new(10.1).unwrap())); // 10.1 < 10 → false

            // Test constraint semantics for closed bound
            assert!(closed_bound.value_within_bound(&value)); // 10 ≤ 10 → true
            assert!(closed_bound.value_within_bound(&Real::try_new(9.9).unwrap())); // 9.9 ≤ 10 → true
            assert!(!closed_bound.value_within_bound(&Real::try_new(10.1).unwrap())); // 10.1 ≤ 10 → false
        }

        /// Test equivalence between convenience constructors and manual construction
        #[test]
        fn test_constructor_equivalence() {
            let value = Real::try_new(7.5).unwrap();

            // Lower bounds
            let lower_open_convenience = LowerBoundRuntime::new_open(value);
            let lower_open_manual = LowerBoundRuntime::Open(LowerBoundOpen::new(value));
            assert_eq!(lower_open_convenience, lower_open_manual);

            let lower_closed_convenience = LowerBoundRuntime::new_closed(value);
            let lower_closed_manual = LowerBoundRuntime::Closed(LowerBoundClosed::new(value));
            assert_eq!(lower_closed_convenience, lower_closed_manual);

            // Upper bounds
            let upper_open_convenience = UpperBoundRuntime::new_open(value);
            let upper_open_manual = UpperBoundRuntime::Open(UpperBoundOpen::new(value));
            assert_eq!(upper_open_convenience, upper_open_manual);

            let upper_closed_convenience = UpperBoundRuntime::new_closed(value);
            let upper_closed_manual = UpperBoundRuntime::Closed(UpperBoundClosed::new(value));
            assert_eq!(upper_closed_convenience, upper_closed_manual);
        }

        /// Test is_open_variant and is_closed_variant consistency
        #[test]
        fn test_variant_check_consistency() {
            let value = Real::try_new(3.5).unwrap();

            // Lower bounds
            let lower_open = LowerBoundRuntime::new_open(value);
            let lower_closed = LowerBoundRuntime::new_closed(value);

            // Verify is_open_variant matches is_open() from trait
            assert_eq!(lower_open.is_open_variant(), lower_open.is_open());
            assert_eq!(lower_closed.is_open_variant(), lower_closed.is_open());

            // Verify is_closed_variant matches is_closed() from trait
            assert_eq!(lower_open.is_closed_variant(), lower_open.is_closed());
            assert_eq!(lower_closed.is_closed_variant(), lower_closed.is_closed());

            // Verify complementary relationship
            assert_eq!(
                lower_open.is_open_variant(),
                !lower_open.is_closed_variant()
            );
            assert_eq!(
                lower_closed.is_open_variant(),
                !lower_closed.is_closed_variant()
            );

            // Upper bounds
            let upper_open = UpperBoundRuntime::new_open(value);
            let upper_closed = UpperBoundRuntime::new_closed(value);

            assert_eq!(upper_open.is_open_variant(), upper_open.is_open());
            assert_eq!(upper_closed.is_open_variant(), upper_closed.is_open());
            assert_eq!(upper_open.is_closed_variant(), upper_open.is_closed());
            assert_eq!(upper_closed.is_closed_variant(), upper_closed.is_closed());
            assert_eq!(
                upper_open.is_open_variant(),
                !upper_open.is_closed_variant()
            );
            assert_eq!(
                upper_closed.is_open_variant(),
                !upper_closed.is_closed_variant()
            );
        }

        /// Test variant checks for filtering and categorization
        #[test]
        fn test_variant_checks_for_filtering() {
            let bounds = [
                LowerBoundRuntime::new_open(Real::try_new(1.0).unwrap()),
                LowerBoundRuntime::new_closed(Real::try_new(2.0).unwrap()),
                LowerBoundRuntime::new_open(Real::try_new(3.0).unwrap()),
                LowerBoundRuntime::new_closed(Real::try_new(4.0).unwrap()),
                LowerBoundRuntime::new_open(Real::try_new(5.0).unwrap()),
            ];

            // Filter by variant type
            let open_bounds: Vec<_> = bounds.iter().filter(|b| b.is_open_variant()).collect();
            let closed_bounds: Vec<_> = bounds.iter().filter(|b| b.is_closed_variant()).collect();

            assert_eq!(open_bounds.len(), 3);
            assert_eq!(closed_bounds.len(), 2);

            // Verify all categorized correctly
            for bound in &open_bounds {
                assert!(bound.is_open_variant());
                assert!(!bound.is_closed_variant());
            }
            for bound in &closed_bounds {
                assert!(bound.is_closed_variant());
                assert!(!bound.is_open_variant());
            }
        }

        /// Test variant checks are non-consuming
        #[test]
        fn test_variant_checks_non_consuming() {
            let bound = LowerBoundRuntime::new_open(Real::try_new(42.0).unwrap());

            // Can check multiple times without consuming
            assert!(bound.is_open_variant());
            assert!(bound.is_open_variant());
            assert!(!bound.is_closed_variant());
            assert!(!bound.is_closed_variant());

            // Can still use the bound after checks
            assert!(bound.value_within_bound(&Real::try_new(50.0).unwrap()));
            assert_eq!(bound.as_ref(), &Real::try_new(42.0).unwrap());
        }

        /// Test constructors with different scalar types
        #[test]
        fn test_constructors_with_different_scalars() {
            // Test with f64
            let f64_open = LowerBoundRuntime::new_open(5.0_f64);
            let f64_closed = LowerBoundRuntime::new_closed(5.0_f64);
            assert!(f64_open.is_open_variant());
            assert!(f64_closed.is_closed_variant());

            // Test with validated scalar
            let validated_value = Real::try_new(10.0).unwrap();
            let validated_open = UpperBoundRuntime::new_open(validated_value);
            let validated_closed = UpperBoundRuntime::new_closed(validated_value);
            assert!(validated_open.is_open_variant());
            assert!(validated_closed.is_closed_variant());
        }

        /// Test constructors in dynamic interval creation scenarios
        #[test]
        fn test_constructors_dynamic_interval_creation() {
            let create_bound_from_config =
                |value: f64, inclusive: bool| -> LowerBoundRuntime<Real> {
                    let real_value = Real::try_new(value).unwrap();
                    if inclusive {
                        LowerBoundRuntime::new_closed(real_value)
                    } else {
                        LowerBoundRuntime::new_open(real_value)
                    }
                };

            // Test inclusive bound
            let inclusive_bound = create_bound_from_config(0.0, true);
            assert!(inclusive_bound.is_closed_variant());
            assert!(inclusive_bound.value_within_bound(&Real::try_new(0.0).unwrap()));

            // Test exclusive bound
            let exclusive_bound = create_bound_from_config(0.0, false);
            assert!(exclusive_bound.is_open_variant());
            assert!(!exclusive_bound.value_within_bound(&Real::try_new(0.0).unwrap()));
        }

        /// Test that constructors maintain proper ordering relationships
        #[test]
        fn test_constructor_ordering() {
            let value = Real::try_new(5.0).unwrap();

            // For lower bounds: closed < open at same value
            let lower_closed = LowerBoundRuntime::new_closed(value);
            let lower_open = LowerBoundRuntime::new_open(value);
            assert!(lower_closed < lower_open);

            // For upper bounds: open < closed at same value
            let upper_open = UpperBoundRuntime::new_open(value);
            let upper_closed = UpperBoundRuntime::new_closed(value);
            assert!(upper_open < upper_closed);
        }
    }

    /// Tests for new helper functions for hull computation with optional bounds
    mod maybe_unbounded_helpers {
        use super::*;
        use num_valid::RealNative64StrictFiniteInDebug;
        use try_create::TryNew;

        type Real = RealNative64StrictFiniteInDebug;

        /// Test min_lower_bound_maybe_unbounded with both bounds present (closed wins)
        #[test]
        fn test_min_lower_bound_both_present_closed_wins() {
            let value = Real::try_new(5.0).unwrap();
            let closed = LowerBoundRuntime::new_closed(value);
            let open = LowerBoundRuntime::new_open(value);

            let result = min_lower_bound_maybe_unbounded(Some(closed), Some(open));

            assert!(result.is_some());
            assert!(
                result.unwrap().is_closed_variant(),
                "Closed should win over open at same value"
            );
        }

        /// Test min_lower_bound_maybe_unbounded with different values
        #[test]
        fn test_min_lower_bound_different_values() {
            let value1 = Real::try_new(3.0).unwrap();
            let value2 = Real::try_new(7.0).unwrap();
            let bound1 = LowerBoundRuntime::new_closed(value1);
            let bound2 = LowerBoundRuntime::new_open(value2);

            let result = min_lower_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2));

            assert!(result.is_some());
            let result_bound = result.unwrap();
            assert_eq!(result_bound.as_ref(), &3.0, "Should select minimum value");
            assert!(result_bound.is_closed_variant());
        }

        /// Test min_lower_bound_maybe_unbounded with first None (unbounded wins)
        #[test]
        fn test_min_lower_bound_first_none() {
            let value = Real::try_new(5.0).unwrap();
            let bound = LowerBoundRuntime::new_closed(value);

            let result = min_lower_bound_maybe_unbounded(None, Some(bound));

            assert!(result.is_none(), "None (unbounded) should win");
        }

        /// Test min_lower_bound_maybe_unbounded with second None (unbounded wins)
        #[test]
        fn test_min_lower_bound_second_none() {
            let value = Real::try_new(5.0).unwrap();
            let bound = LowerBoundRuntime::new_closed(value);

            let result = min_lower_bound_maybe_unbounded(Some(bound), None);

            assert!(result.is_none(), "None (unbounded) should win");
        }

        /// Test min_lower_bound_maybe_unbounded with both None
        #[test]
        fn test_min_lower_bound_both_none() {
            let result = min_lower_bound_maybe_unbounded::<Real>(None, None);

            assert!(result.is_none());
        }

        /// Test max_upper_bound_maybe_unbounded with both bounds present (closed wins)
        #[test]
        fn test_max_upper_bound_both_present_closed_wins() {
            let value = Real::try_new(5.0).unwrap();
            let closed = UpperBoundRuntime::new_closed(value);
            let open = UpperBoundRuntime::new_open(value);

            let result = max_upper_bound_maybe_unbounded(Some(closed.clone()), Some(open.clone()));

            assert!(result.is_some());
            assert!(
                result.unwrap().is_closed_variant(),
                "Closed should win over open at same value"
            );
        }

        /// Test max_upper_bound_maybe_unbounded with different values
        #[test]
        fn test_max_upper_bound_different_values() {
            let value1 = Real::try_new(3.0).unwrap();
            let value2 = Real::try_new(7.0).unwrap();
            let bound1 = UpperBoundRuntime::new_open(value1);
            let bound2 = UpperBoundRuntime::new_closed(value2);

            let result = max_upper_bound_maybe_unbounded(Some(bound1), Some(bound2.clone()));

            assert!(result.is_some());
            let result_bound = result.unwrap();
            assert_eq!(result_bound.as_ref(), &7.0, "Should select maximum value");
            assert!(result_bound.is_closed_variant());
        }

        /// Test max_upper_bound_maybe_unbounded with first None (unbounded wins)
        #[test]
        fn test_max_upper_bound_first_none() {
            let value = Real::try_new(5.0).unwrap();
            let bound = UpperBoundRuntime::new_closed(value);

            let result = max_upper_bound_maybe_unbounded(None, Some(bound));

            assert!(result.is_none(), "None (unbounded) should win");
        }

        /// Test max_upper_bound_maybe_unbounded with second None (unbounded wins)
        #[test]
        fn test_max_upper_bound_second_none() {
            let value = Real::try_new(5.0).unwrap();
            let bound = UpperBoundRuntime::new_closed(value);

            let result = max_upper_bound_maybe_unbounded(Some(bound), None);

            assert!(result.is_none(), "None (unbounded) should win");
        }

        /// Test max_upper_bound_maybe_unbounded with both None
        #[test]
        fn test_max_upper_bound_both_none() {
            let result = max_upper_bound_maybe_unbounded::<Real>(None, None);

            assert!(result.is_none());
        }

        /// Test symmetry: swapping arguments doesn't change result
        #[test]
        fn test_min_lower_bound_symmetry() {
            let value1 = Real::try_new(3.0).unwrap();
            let value2 = Real::try_new(7.0).unwrap();
            let bound1 = LowerBoundRuntime::new_closed(value1);
            let bound2 = LowerBoundRuntime::new_open(value2);

            let result1 =
                min_lower_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2.clone()));
            let result2 = min_lower_bound_maybe_unbounded(Some(bound2), Some(bound1));

            assert_eq!(result1, result2, "Operation should be commutative");
        }

        /// Test symmetry for upper bounds
        #[test]
        fn test_max_upper_bound_symmetry() {
            let value1 = Real::try_new(3.0).unwrap();
            let value2 = Real::try_new(7.0).unwrap();
            let bound1 = UpperBoundRuntime::new_closed(value1);
            let bound2 = UpperBoundRuntime::new_open(value2);

            let result1 =
                max_upper_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2.clone()));
            let result2 = max_upper_bound_maybe_unbounded(Some(bound2), Some(bound1));

            assert_eq!(result1, result2, "Operation should be commutative");
        }

        /// Test interaction with min_lower_bound (existing function)
        #[test]
        fn test_consistency_with_existing_min_lower_bound() {
            let value1 = Real::try_new(3.0).unwrap();
            let value2 = Real::try_new(7.0).unwrap();
            let bound1 = LowerBoundRuntime::new_closed(value1);
            let bound2 = LowerBoundRuntime::new_open(value2);

            // Using the new maybe_unbounded function with Some
            let result_maybe =
                min_lower_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2.clone()))
                    .unwrap();

            // Using the existing function
            let result_direct = min_lower_bound(bound1, bound2);

            assert_eq!(
                result_maybe, result_direct,
                "Should be consistent with existing function"
            );
        }

        /// Test interaction with max_upper_bound (existing function)
        #[test]
        fn test_consistency_with_existing_max_upper_bound() {
            let value1 = Real::try_new(3.0).unwrap();
            let value2 = Real::try_new(7.0).unwrap();
            let bound1 = UpperBoundRuntime::new_closed(value1);
            let bound2 = UpperBoundRuntime::new_open(value2);

            // Using the new maybe_unbounded function with Some
            let result_maybe =
                max_upper_bound_maybe_unbounded(Some(bound1.clone()), Some(bound2.clone()))
                    .unwrap();

            // Using the existing function
            let result_direct = max_upper_bound(bound1, bound2);

            assert_eq!(
                result_maybe, result_direct,
                "Should be consistent with existing function"
            );
        }

        /// Test with multiple calls (associativity)
        #[test]
        fn test_min_lower_bound_associativity() {
            let v1 = Real::try_new(1.0).unwrap();
            let v2 = Real::try_new(2.0).unwrap();
            let v3 = Real::try_new(3.0).unwrap();
            let b1 = LowerBoundRuntime::new_closed(v1);
            let b2 = LowerBoundRuntime::new_open(v2);
            let b3 = LowerBoundRuntime::new_closed(v3);

            // (b1 min b2) min b3
            let temp = min_lower_bound_maybe_unbounded(Some(b1.clone()), Some(b2.clone()));
            let result1 = min_lower_bound_maybe_unbounded(temp, Some(b3.clone()));

            // b1 min (b2 min b3)
            let temp = min_lower_bound_maybe_unbounded(Some(b2), Some(b3));
            let result2 = min_lower_bound_maybe_unbounded(Some(b1), temp);

            assert_eq!(result1, result2, "Operation should be associative");
        }
    }

    // Tests for IntervalBoundRuntime::flip_bound_type() and flip_bound_side()
    mod transformations {
        use super::*;

        /// Test flip_bound_type() on LowerBoundRuntime variants
        #[test]
        fn flip_bound_type_lower_open_to_closed() {
            let lower_open = LowerBoundRuntime::new_open(5.0);
            let lower_closed = lower_open.flip_bound_type();

            assert!(lower_closed.is_closed_variant());
            assert!(!lower_closed.is_open_variant());
            assert_eq!(*lower_closed.as_ref(), 5.0);
        }

        #[test]
        fn flip_bound_type_lower_closed_to_open() {
            let lower_closed = LowerBoundRuntime::new_closed(10.0);
            let lower_open = lower_closed.flip_bound_type();

            assert!(lower_open.is_open_variant());
            assert!(!lower_open.is_closed_variant());
            assert_eq!(*lower_open.as_ref(), 10.0);
        }

        /// Test flip_bound_type() on UpperBoundRuntime variants
        #[test]
        fn flip_bound_type_upper_open_to_closed() {
            let upper_open = UpperBoundRuntime::new_open(20.0);
            let upper_closed = upper_open.flip_bound_type();

            assert!(upper_closed.is_closed_variant());
            assert!(!upper_closed.is_open_variant());
            assert_eq!(*upper_closed.as_ref(), 20.0);
        }

        #[test]
        fn flip_bound_type_upper_closed_to_open() {
            let upper_closed = UpperBoundRuntime::new_closed(15.0);
            let upper_open = upper_closed.flip_bound_type();

            assert!(upper_open.is_open_variant());
            assert!(!upper_open.is_closed_variant());
            assert_eq!(*upper_open.as_ref(), 15.0);
        }

        /// Test that flipping bound type twice returns to original
        #[test]
        fn flip_bound_type_idempotent() {
            // Lower bounds
            let lower_open_original = LowerBoundRuntime::new_open(3.0);
            let lower_open_roundtrip = lower_open_original
                .clone()
                .flip_bound_type()
                .flip_bound_type();
            assert_eq!(lower_open_original, lower_open_roundtrip);

            let lower_closed_original = LowerBoundRuntime::new_closed(7.0);
            let lower_closed_roundtrip = lower_closed_original
                .clone()
                .flip_bound_type()
                .flip_bound_type();
            assert_eq!(lower_closed_original, lower_closed_roundtrip);

            // Upper bounds
            let upper_open_original = UpperBoundRuntime::new_open(12.0);
            let upper_open_roundtrip = upper_open_original
                .clone()
                .flip_bound_type()
                .flip_bound_type();
            assert_eq!(upper_open_original, upper_open_roundtrip);

            let upper_closed_original = UpperBoundRuntime::new_closed(18.0);
            let upper_closed_roundtrip = upper_closed_original
                .clone()
                .flip_bound_type()
                .flip_bound_type();
            assert_eq!(upper_closed_original, upper_closed_roundtrip);
        }

        /// Test flip_bound_side() from lower to upper bounds
        #[test]
        fn flip_bound_side_lower_open_to_upper_open() {
            let lower_open = LowerBoundRuntime::new_open(5.0);
            let upper_open: UpperBoundRuntime<f64> = lower_open.flip_bound_side();

            assert!(upper_open.is_open_variant());
            assert_eq!(*upper_open.as_ref(), 5.0);
        }

        #[test]
        fn flip_bound_side_lower_closed_to_upper_closed() {
            let lower_closed = LowerBoundRuntime::new_closed(10.0);
            let upper_closed: UpperBoundRuntime<f64> = lower_closed.flip_bound_side();

            assert!(upper_closed.is_closed_variant());
            assert_eq!(*upper_closed.as_ref(), 10.0);
        }

        /// Test flip_bound_side() from upper to lower bounds
        #[test]
        fn flip_bound_side_upper_open_to_lower_open() {
            let upper_open = UpperBoundRuntime::new_open(20.0);
            let lower_open: LowerBoundRuntime<f64> = upper_open.flip_bound_side();

            assert!(lower_open.is_open_variant());
            assert_eq!(*lower_open.as_ref(), 20.0);
        }

        #[test]
        fn flip_bound_side_upper_closed_to_lower_closed() {
            let upper_closed = UpperBoundRuntime::new_closed(15.0);
            let lower_closed: LowerBoundRuntime<f64> = upper_closed.flip_bound_side();

            assert!(lower_closed.is_closed_variant());
            assert_eq!(*lower_closed.as_ref(), 15.0);
        }

        /// Test that flipping bound side twice returns to original side
        #[test]
        fn flip_bound_side_roundtrip() {
            // Lower to upper to lower
            let lower_open_original = LowerBoundRuntime::new_open(3.0);
            let upper_open: UpperBoundRuntime<f64> = lower_open_original.clone().flip_bound_side();
            let lower_open_back: LowerBoundRuntime<f64> = upper_open.flip_bound_side();
            assert_eq!(lower_open_original, lower_open_back);

            let lower_closed_original = LowerBoundRuntime::new_closed(7.0);
            let upper_closed: UpperBoundRuntime<f64> =
                lower_closed_original.clone().flip_bound_side();
            let lower_closed_back: LowerBoundRuntime<f64> = upper_closed.flip_bound_side();
            assert_eq!(lower_closed_original, lower_closed_back);

            // Upper to lower to upper
            let upper_open_original = UpperBoundRuntime::new_open(12.0);
            let lower_open_temp: LowerBoundRuntime<f64> =
                upper_open_original.clone().flip_bound_side();
            let upper_open_back: UpperBoundRuntime<f64> = lower_open_temp.flip_bound_side();
            assert_eq!(upper_open_original, upper_open_back);

            let upper_closed_original = UpperBoundRuntime::new_closed(18.0);
            let lower_closed_temp: LowerBoundRuntime<f64> =
                upper_closed_original.clone().flip_bound_side();
            let upper_closed_back: UpperBoundRuntime<f64> = lower_closed_temp.flip_bound_side();
            assert_eq!(upper_closed_original, upper_closed_back);
        }

        /// Test combining flip_bound_side() and flip_bound_type()
        #[test]
        fn combined_flip_lower_closed_to_upper_open() {
            let lower_closed = LowerBoundRuntime::new_closed(3.0);
            let upper_open: UpperBoundRuntime<f64> = lower_closed
                .flip_bound_side() // Lower Closed -> Upper Closed
                .flip_bound_type(); // Upper Closed -> Upper Open

            assert!(upper_open.is_open_variant());
            assert_eq!(*upper_open.as_ref(), 3.0);
        }

        #[test]
        fn combined_flip_lower_open_to_upper_closed() {
            let lower_open = LowerBoundRuntime::new_open(8.0);
            let upper_closed: UpperBoundRuntime<f64> = lower_open
                .flip_bound_side() // Lower Open -> Upper Open
                .flip_bound_type(); // Upper Open -> Upper Closed

            assert!(upper_closed.is_closed_variant());
            assert_eq!(*upper_closed.as_ref(), 8.0);
        }

        #[test]
        fn combined_flip_upper_closed_to_lower_open() {
            let upper_closed = UpperBoundRuntime::new_closed(15.0);
            let lower_open: LowerBoundRuntime<f64> = upper_closed
                .flip_bound_side() // Upper Closed -> Lower Closed
                .flip_bound_type(); // Lower Closed -> Lower Open

            assert!(lower_open.is_open_variant());
            assert_eq!(*lower_open.as_ref(), 15.0);
        }

        #[test]
        fn combined_flip_upper_open_to_lower_closed() {
            let upper_open = UpperBoundRuntime::new_open(22.0);
            let lower_closed: LowerBoundRuntime<f64> = upper_open
                .flip_bound_side() // Upper Open -> Lower Open
                .flip_bound_type(); // Lower Open -> Lower Closed

            assert!(lower_closed.is_closed_variant());
            assert_eq!(*lower_closed.as_ref(), 22.0);
        }

        /// Test flip_bound_type() preserves value with negative numbers
        #[test]
        fn flip_bound_type_negative_values() {
            let lower_open = LowerBoundRuntime::new_open(-5.0);
            let lower_closed = lower_open.flip_bound_type();
            assert_eq!(*lower_closed.as_ref(), -5.0);
            assert!(lower_closed.is_closed_variant());

            let upper_closed = UpperBoundRuntime::new_closed(-10.0);
            let upper_open = upper_closed.flip_bound_type();
            assert_eq!(*upper_open.as_ref(), -10.0);
            assert!(upper_open.is_open_variant());
        }

        /// Test flip_bound_side() preserves value with negative numbers
        #[test]
        fn flip_bound_side_negative_values() {
            let lower_open = LowerBoundRuntime::new_open(-3.0);
            let upper_open: UpperBoundRuntime<f64> = lower_open.flip_bound_side();
            assert_eq!(*upper_open.as_ref(), -3.0);
            assert!(upper_open.is_open_variant());

            let upper_closed = UpperBoundRuntime::new_closed(-7.0);
            let lower_closed: LowerBoundRuntime<f64> = upper_closed.flip_bound_side();
            assert_eq!(*lower_closed.as_ref(), -7.0);
            assert!(lower_closed.is_closed_variant());
        }

        /// Test with zero values
        #[test]
        fn transformations_with_zero() {
            let lower_zero_open = LowerBoundRuntime::new_open(0.0);
            let lower_zero_closed = lower_zero_open.flip_bound_type();
            assert_eq!(*lower_zero_closed.as_ref(), 0.0);
            assert!(lower_zero_closed.is_closed_variant());

            let upper_zero_closed = UpperBoundRuntime::new_closed(0.0);
            let lower_zero_from_upper: LowerBoundRuntime<f64> = upper_zero_closed.flip_bound_side();
            assert_eq!(*lower_zero_from_upper.as_ref(), 0.0);
            assert!(lower_zero_from_upper.is_closed_variant());
        }

        /// Test with very small positive values (edge case)
        #[test]
        fn transformations_with_small_values() {
            let tiny_value = 1e-100;

            let lower_open = LowerBoundRuntime::new_open(tiny_value);
            let lower_closed = lower_open.flip_bound_type();
            assert_eq!(*lower_closed.as_ref(), tiny_value);

            let upper_open = UpperBoundRuntime::new_open(tiny_value);
            let lower_open_from_upper: LowerBoundRuntime<f64> = upper_open.flip_bound_side();
            assert_eq!(*lower_open_from_upper.as_ref(), tiny_value);
        }

        /// Test with very large values
        #[test]
        fn transformations_with_large_values() {
            let large_value = 1e100;

            let upper_closed = UpperBoundRuntime::new_closed(large_value);
            let upper_open = upper_closed.flip_bound_type();
            assert_eq!(*upper_open.as_ref(), large_value);
            assert!(upper_open.is_open_variant());

            let lower_closed = LowerBoundRuntime::new_closed(large_value);
            let upper_closed_from_lower: UpperBoundRuntime<f64> = lower_closed.flip_bound_side();
            assert_eq!(*upper_closed_from_lower.as_ref(), large_value);
            assert!(upper_closed_from_lower.is_closed_variant());
        }

        /// Test commutativity: order of flip_bound_side and flip_bound_type shouldn't matter
        #[test]
        fn flip_operations_commute() {
            let original = LowerBoundRuntime::new_closed(5.0);

            // Side first, then type
            let result1: UpperBoundRuntime<f64> = original
                .clone()
                .flip_bound_side() // Lower Closed -> Upper Closed
                .flip_bound_type(); // Upper Closed -> Upper Open

            // Type first, then side
            let result2: UpperBoundRuntime<f64> = original
                .flip_bound_type() // Lower Closed -> Lower Open
                .flip_bound_side(); // Lower Open -> Upper Open

            assert_eq!(result1, result2);
            assert!(result1.is_open_variant());
            assert_eq!(*result1.as_ref(), 5.0);
        }

        /// Test that flip_bound_side preserves the type (open/closed)
        #[test]
        fn flip_bound_side_preserves_type() {
            // Open bounds stay open
            let lower_open = LowerBoundRuntime::new_open(5.0);
            let upper_open: UpperBoundRuntime<f64> = lower_open.flip_bound_side();
            assert!(upper_open.is_open_variant());

            let upper_open2 = UpperBoundRuntime::new_open(10.0);
            let lower_open2: LowerBoundRuntime<f64> = upper_open2.flip_bound_side();
            assert!(lower_open2.is_open_variant());

            // Closed bounds stay closed
            let lower_closed = LowerBoundRuntime::new_closed(15.0);
            let upper_closed: UpperBoundRuntime<f64> = lower_closed.flip_bound_side();
            assert!(upper_closed.is_closed_variant());

            let upper_closed2 = UpperBoundRuntime::new_closed(20.0);
            let lower_closed2: LowerBoundRuntime<f64> = upper_closed2.flip_bound_side();
            assert!(lower_closed2.is_closed_variant());
        }

        /// Test that flip_bound_type preserves the side (lower/upper)
        #[test]
        fn flip_bound_type_preserves_side() {
            // Lower bounds stay lower (test by trying to use as lower bounds)
            let lower_open = LowerBoundRuntime::new_open(5.0);
            let lower_closed = lower_open.flip_bound_type();
            // If this compiles and runs, the type is still LowerBoundRuntime
            assert_eq!(*lower_closed.as_ref(), 5.0);

            // Upper bounds stay upper
            let upper_closed = UpperBoundRuntime::new_closed(10.0);
            let upper_open = upper_closed.flip_bound_type();
            // If this compiles and runs, the type is still UpperBoundRuntime
            assert_eq!(*upper_open.as_ref(), 10.0);
        }

        /// Test use case: interval difference computation
        /// When computing A \ B, we need to flip bounds appropriately
        #[test]
        fn interval_difference_use_case() {
            // A = [0, 10], B = [5, 7]
            // Result should be [0, 5) ∪ (7, 10]

            // B's lower bound [5 needs to become upper bound )5 for left part
            let b_lower = LowerBoundRuntime::new_closed(5.0);
            let left_upper: UpperBoundRuntime<f64> = b_lower
                .flip_bound_side() // Lower Closed -> Upper Closed
                .flip_bound_type(); // Upper Closed -> Upper Open

            assert!(left_upper.is_open_variant());
            assert_eq!(*left_upper.as_ref(), 5.0);
            // This creates the upper bound )5 for interval [0, 5)

            // B's upper bound ]7 needs to become lower bound (7 for right part
            let b_upper = UpperBoundRuntime::new_closed(7.0);
            let right_lower: LowerBoundRuntime<f64> = b_upper
                .flip_bound_side() // Upper Closed -> Lower Closed
                .flip_bound_type(); // Lower Closed -> Lower Open

            assert!(right_lower.is_open_variant());
            assert_eq!(*right_lower.as_ref(), 7.0);
            // This creates the lower bound (7 for interval (7, 10]
        }

        /// Test with validated scalar types
        #[test]
        fn transformations_with_validated_types() {
            use num_valid::RealNative64StrictFiniteInDebug;
            use try_create::TryNew;

            let value = RealNative64StrictFiniteInDebug::try_new(5.0).unwrap();

            let lower_open = LowerBoundRuntime::new_open(value);
            let lower_closed = lower_open.flip_bound_type();
            assert!(lower_closed.is_closed_variant());
            assert_eq!(*lower_closed.as_ref(), value);

            let upper_closed = UpperBoundRuntime::new_closed(value);
            let lower_closed_from_upper: LowerBoundRuntime<_> = upper_closed.flip_bound_side();
            assert!(lower_closed_from_upper.is_closed_variant());
            assert_eq!(*lower_closed_from_upper.as_ref(), value);
        }

        /// Test multiple sequential transformations
        #[test]
        fn multiple_sequential_transformations() {
            let original = LowerBoundRuntime::new_open(10.0);

            // Apply transformations in sequence
            let step1 = original.flip_bound_type(); // Lower Open -> Lower Closed
            let step2: UpperBoundRuntime<f64> = step1.flip_bound_side(); // Lower Closed -> Upper Closed
            let step3 = step2.flip_bound_type(); // Upper Closed -> Upper Open
            let step4: LowerBoundRuntime<f64> = step3.flip_bound_side(); // Upper Open -> Lower Open

            // Should return to same type as original
            assert!(step4.is_open_variant());
            assert_eq!(*step4.as_ref(), 10.0);
        }

        /// Test flip_bound_side_and_type method on IntervalBound
        #[test]
        fn test_flip_bound_side_and_type() {
            let lower_closed = IntervalBound::<f64, Lower, Closed>::new(5.0);
            let upper_open: IntervalBound<f64, Upper, Open> =
                lower_closed.flip_bound_side_and_type();
            assert_eq!(*upper_open.as_ref(), 5.0);

            let upper_open2 = IntervalBound::<f64, Upper, Open>::new(10.0);
            let lower_closed2: IntervalBound<f64, Lower, Closed> =
                upper_open2.flip_bound_side_and_type();
            assert_eq!(*lower_closed2.as_ref(), 10.0);

            let lower_open = IntervalBound::<f64, Lower, Open>::new(3.0);
            let upper_closed: IntervalBound<f64, Upper, Closed> =
                lower_open.flip_bound_side_and_type();
            assert_eq!(*upper_closed.as_ref(), 3.0);

            let upper_closed2 = IntervalBound::<f64, Upper, Closed>::new(7.0);
            let lower_open2: IntervalBound<f64, Lower, Open> =
                upper_closed2.flip_bound_side_and_type();
            assert_eq!(*lower_open2.as_ref(), 7.0);
        }

        /// Test BoundSide::is_lower() method
        #[test]
        fn test_bound_side() {
            assert!(Upper::is_upper());
            assert!(!Upper::is_lower());
            assert!(!Lower::is_upper());
            assert!(Lower::is_lower());
        }

        /// Test BoundSideChecks trait methods
        #[test]
        fn test_bound_side_checks() {
            let lower = LowerBoundRuntime::new_closed(5.0);
            assert!(!lower.is_upper_bound());

            let upper = UpperBoundRuntime::new_open(10.0);
            assert!(upper.is_upper_bound());
        }

        /// Test IntoInner trait on IntervalBoundRuntime
        #[test]
        fn test_interval_bound_runtime_into_inner() {
            let lower_open = LowerBoundRuntime::new_open(5.0);
            let value = lower_open.into_inner();
            assert_eq!(value, 5.0);

            let lower_closed = LowerBoundRuntime::new_closed(7.0);
            let value2 = lower_closed.into_inner();
            assert_eq!(value2, 7.0);

            let upper_open = UpperBoundRuntime::new_open(3.0);
            let value3 = upper_open.into_inner();
            assert_eq!(value3, 3.0);

            let upper_closed = UpperBoundRuntime::new_closed(9.0);
            let value4 = upper_closed.into_inner();
            assert_eq!(value4, 9.0);
        }

        /// Test BoundType::is_open() method
        #[test]
        fn test_bound_type_is_open() {
            // is_open() is defined as !includes_boundary()
            // Ensure it compiles and works
            assert!(Closed::includes_boundary() != Closed::is_open());
            assert!(Open::is_open());
            assert!(!Closed::is_open());
        }
    }

    mod comparisons {
        use super::*;
        use try_create::TryNew;

        type Real = f64;

        /// Test PartialOrd implementation for LowerBoundRuntime
        #[test]
        fn test_interval_lower_bound_comparison() {
            // Create test bounds
            let lower_bound_closed_5 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
            let lower_bound_open_5 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
            let lower_bound_closed_3 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
            let lower_bound_open_3 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(3.0).unwrap()));
            let lower_bound_closed_7 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(7.0).unwrap()));

            // Test basic ordering by value
            assert_eq!(
                lower_bound_closed_3.partial_cmp(&lower_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_closed_5.partial_cmp(&lower_bound_closed_3),
                Some(Ordering::Greater)
            );
            assert_eq!(
                lower_bound_closed_5.partial_cmp(&lower_bound_closed_5),
                Some(Ordering::Equal)
            );

            // Test ordering between closed and open bounds with same value
            // For lower bounds: closed < open at same value (closed is more restrictive for lower)
            assert_eq!(
                lower_bound_closed_5.partial_cmp(&lower_bound_open_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_open_5.partial_cmp(&lower_bound_closed_5),
                Some(Ordering::Greater)
            );

            // Test mixed value and boundary type comparisons
            assert_eq!(
                lower_bound_closed_3.partial_cmp(&lower_bound_open_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_open_3.partial_cmp(&lower_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_closed_5.partial_cmp(&lower_bound_open_3),
                Some(Ordering::Greater)
            );

            // Test transitivity
            assert_eq!(
                lower_bound_closed_3.partial_cmp(&lower_bound_closed_7),
                Some(Ordering::Less)
            );
            assert_eq!(
                lower_bound_open_3.partial_cmp(&lower_bound_closed_7),
                Some(Ordering::Less)
            );
        }

        /// Test PartialOrd implementation for UpperBoundRuntime
        #[test]
        fn test_interval_upper_bound_comparison() {
            // Create test bounds
            let upper_bound_closed_5 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
            let upper_bound_open_5 =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));
            let upper_bound_closed_3 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(3.0).unwrap()));
            let upper_bound_open_3 =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(3.0).unwrap()));
            let upper_bound_closed_7 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(7.0).unwrap()));

            // Test basic ordering by value
            assert_eq!(
                upper_bound_closed_3.partial_cmp(&upper_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_closed_5.partial_cmp(&upper_bound_closed_3),
                Some(Ordering::Greater)
            );
            assert_eq!(
                upper_bound_closed_5.partial_cmp(&upper_bound_closed_5),
                Some(Ordering::Equal)
            );

            // Test ordering between closed and open bounds with same value
            // For upper bounds: open < closed at same value (open is more restrictive for upper)
            assert_eq!(
                upper_bound_open_5.partial_cmp(&upper_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_closed_5.partial_cmp(&upper_bound_open_5),
                Some(Ordering::Greater)
            );

            // Test mixed value and boundary type comparisons
            assert_eq!(
                upper_bound_closed_3.partial_cmp(&upper_bound_open_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_open_3.partial_cmp(&upper_bound_closed_5),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_closed_5.partial_cmp(&upper_bound_open_3),
                Some(Ordering::Greater)
            );

            // Test transitivity
            assert_eq!(
                upper_bound_closed_3.partial_cmp(&upper_bound_closed_7),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_bound_open_3.partial_cmp(&upper_bound_closed_7),
                Some(Ordering::Less)
            );
        }

        /// Test boundary type semantics for lower bounds
        #[test]
        fn test_lower_bound_semantics() {
            let closed_5 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
            let open_5 = LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));

            // For lower bounds, closed is more restrictive (smaller) than open at same value
            // This is because [5,b) contains 5, while (5,b) does not
            more_asserts::assert_lt!(closed_5, open_5);
            more_asserts::assert_ge!(open_5, closed_5);
            assert_ne!(closed_5, open_5);
        }

        /// Test boundary type semantics for upper bounds
        #[test]
        fn test_upper_bound_semantics() {
            let closed_5 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
            let open_5 = UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));

            // For upper bounds, open is more restrictive (smaller) than closed at same value
            // This is because [a,5) excludes 5, while [a,5] includes 5
            more_asserts::assert_lt!(open_5, closed_5);
            more_asserts::assert_ge!(closed_5, open_5);
            assert_ne!(open_5, closed_5);
        }

        /// Test consistency with mathematical interval ordering
        #[test]
        fn test_mathematical_consistency() {
            // Create bounds that would represent valid intervals
            let lower_closed_1 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(1.0).unwrap()));
            let lower_open_1 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(1.0).unwrap()));
            let upper_open_2 =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(2.0).unwrap()));
            let upper_closed_2 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(2.0).unwrap()));

            // Mathematical consistency checks:
            // [1,2) should have closed lower bound and open upper bound
            // (1,2] should have open lower bound and closed upper bound
            // [1,2] should have closed bounds
            // (1,2) should have open bounds

            // Verify ordering is consistent with interval containment
            // [1,x] contains more points than (1,x] at the same x
            assert!(lower_closed_1 < lower_open_1);

            // [x,2) contains fewer points than [x,2] at the same x
            assert!(upper_open_2 < upper_closed_2);
        }

        /// Test reflexivity property
        #[test]
        fn test_reflexivity() {
            let lower_closed =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));
            let lower_open =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));
            let upper_closed =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));
            let upper_open =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(5.0).unwrap()));

            // Reflexivity: x.partial_cmp(&x) == Some(Ordering::Equal)
            assert_eq!(
                lower_closed.partial_cmp(&lower_closed),
                Some(Ordering::Equal)
            );
            assert_eq!(lower_open.partial_cmp(&lower_open), Some(Ordering::Equal));
            assert_eq!(
                upper_closed.partial_cmp(&upper_closed),
                Some(Ordering::Equal)
            );
            assert_eq!(upper_open.partial_cmp(&upper_open), Some(Ordering::Equal));
        }

        /// Test antisymmetry property
        #[test]
        fn test_antisymmetry() {
            let lower_closed_3 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
            let lower_closed_5 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));

            // Antisymmetry: if x <= y and y <= x, then x == y
            if lower_closed_3.partial_cmp(&lower_closed_5) == Some(Ordering::Less) {
                assert_eq!(
                    lower_closed_5.partial_cmp(&lower_closed_3),
                    Some(Ordering::Greater)
                );
            }
        }

        /// Test transitivity property
        #[test]
        fn test_transitivity() {
            let lower_closed_1 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(1.0).unwrap()));
            let lower_open_3 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(3.0).unwrap()));
            let lower_closed_5 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(5.0).unwrap()));

            // Transitivity: if x <= y and y <= z, then x <= z
            let ord_1_3 = lower_closed_1.partial_cmp(&lower_open_3);
            let ord_3_5 = lower_open_3.partial_cmp(&lower_closed_5);
            let ord_1_5 = lower_closed_1.partial_cmp(&lower_closed_5);

            if ord_1_3 == Some(Ordering::Less) && ord_3_5 == Some(Ordering::Less) {
                assert_eq!(ord_1_5, Some(Ordering::Less));
            }
        }

        /// Test edge cases with same values but different boundary types
        #[test]
        fn test_edge_cases_same_values() {
            let value = Real::try_new(42.0).unwrap();

            let lower_closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(value));
            let lower_open = LowerBoundRuntime::Open(LowerBoundOpen::new(value));
            let upper_closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(value));
            let upper_open = UpperBoundRuntime::Open(UpperBoundOpen::new(value));

            // Test that boundary type matters even with same value
            assert_ne!(lower_closed.partial_cmp(&lower_open), Some(Ordering::Equal));
            assert_ne!(upper_closed.partial_cmp(&upper_open), Some(Ordering::Equal));

            // Verify specific ordering relationships
            assert_eq!(lower_closed.partial_cmp(&lower_open), Some(Ordering::Less));
            assert_eq!(upper_open.partial_cmp(&upper_closed), Some(Ordering::Less));
        }

        /// Test with extreme values
        #[test]
        fn test_extreme_values() {
            let min_val = Real::try_new(f64::MIN).unwrap();
            let max_val = Real::try_new(f64::MAX).unwrap();

            let lower_min_closed = LowerBoundRuntime::Closed(LowerBoundClosed::new(min_val));
            let lower_max_open = LowerBoundRuntime::Open(LowerBoundOpen::new(max_val));
            let upper_min_open = UpperBoundRuntime::Open(UpperBoundOpen::new(min_val));
            let upper_max_closed = UpperBoundRuntime::Closed(UpperBoundClosed::new(max_val));

            // Test that extreme values still follow ordering rules
            assert_eq!(
                lower_min_closed.partial_cmp(&lower_max_open),
                Some(Ordering::Less)
            );
            assert_eq!(
                upper_min_open.partial_cmp(&upper_max_closed),
                Some(Ordering::Less)
            );
        }

        /// Test helper functions min_lower_bound and max_lower_bound
        #[test]
        fn test_min_max_lower_bound() {
            let lower_closed_3 =
                LowerBoundRuntime::Closed(LowerBoundClosed::new(Real::try_new(3.0).unwrap()));
            let lower_open_5 =
                LowerBoundRuntime::Open(LowerBoundOpen::new(Real::try_new(5.0).unwrap()));

            // Test min_lower_bound
            let min_result = min_lower_bound(lower_closed_3.clone(), lower_open_5.clone());
            assert_eq!(min_result, lower_closed_3);

            // Test max_lower_bound
            let max_result = max_lower_bound(lower_closed_3.clone(), lower_open_5.clone());
            assert_eq!(max_result, lower_open_5);
        }

        /// Test helper functions min_upper_bound and max_upper_bound
        #[test]
        fn test_min_max_upper_bound() {
            let upper_open_3 =
                UpperBoundRuntime::Open(UpperBoundOpen::new(Real::try_new(3.0).unwrap()));
            let upper_closed_5 =
                UpperBoundRuntime::Closed(UpperBoundClosed::new(Real::try_new(5.0).unwrap()));

            // Test min_upper_bound
            let min_result = min_upper_bound(upper_open_3.clone(), upper_closed_5.clone());
            assert_eq!(min_result, upper_open_3);

            // Test max_upper_bound
            let max_result = max_upper_bound(upper_open_3.clone(), upper_closed_5.clone());
            assert_eq!(max_result, upper_closed_5);
        }
    }
}