Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
// Do not include this file directly. Please include "onnxruntime_cxx_api.h" instead.
// If interested in trying out features of the new experimental C++ API, include "experimental_onnxruntime_cxx_api.h" instead.
//
// These are the inline implementations of the C++ header APIs. They're in this separate file as to not clutter
// the main C++ file with implementation details.
 
#include <algorithm>
#include <functional>
#include <iterator>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
 
// Convert OrtStatus to Ort::Status and return
// instead of throwing
#define ORT_CXX_RETURN_ON_API_FAIL(expression) \
  {                                            \
    auto ort_status = (expression);            \
    if (ort_status) {                          \
      return Ort::Status(ort_status);          \
    }                                          \
  }
 
#ifdef __cpp_if_constexpr
#define ORT_CXX_IF_CONSTEXPR if constexpr
#else
#define ORT_CXX_IF_CONSTEXPR if
#endif
 
namespace Ort {
 
namespace detail {
inline void ThrowStatus(const Status& st) {
  std::string error_message = st.GetErrorMessage();
  OrtErrorCode error_code = st.GetErrorCode();
  ORT_CXX_API_THROW(std::move(error_message), error_code);
}
}  // namespace detail
 
inline void ThrowOnError(OrtStatus* ort_status) {
  if (ort_status) {
    Ort::Status st(ort_status);
    detail::ThrowStatus(st);
  }
}
 
inline void ThrowOnError(const Status& st) {
  if (st) {
    detail::ThrowStatus(st);
  }
}
 
inline Status::Status(OrtStatus* status) noexcept : detail::Base<OrtStatus>{status} {
}
 
inline Status::Status(const std::exception& e) {
  p_ = GetApi().CreateStatus(ORT_FAIL, e.what());
}
 
inline Status::Status(const Exception& e) {
  p_ = GetApi().CreateStatus(e.GetOrtErrorCode(), e.what());
}
 
inline Status::Status(const char* message, OrtErrorCode code) {
  p_ = GetApi().CreateStatus(code, message);
}
 
inline std::string Status::GetErrorMessage() const {
  std::string message(GetApi().GetErrorMessage(p_));
  return message;
}
 
inline OrtErrorCode Status::GetErrorCode() const {
  return GetApi().GetErrorCode(p_);
}
 
inline bool Status::IsOK() const noexcept {
  return (p_ == nullptr);
}
 
// This template converts a C++ type into it's ONNXTensorElementDataType
template <typename T>
struct TypeToTensorType;
template <>
struct TypeToTensorType<float> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT;
};
template <>
struct TypeToTensorType<Float16_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16;
};
template <>
struct TypeToTensorType<BFloat16_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16;
};
template <>
struct TypeToTensorType<double> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE;
};
template <>
struct TypeToTensorType<int8_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8;
};
template <>
struct TypeToTensorType<int16_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16;
};
template <>
struct TypeToTensorType<int32_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32;
};
template <>
struct TypeToTensorType<int64_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
};
template <>
struct TypeToTensorType<uint8_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8;
};
template <>
struct TypeToTensorType<uint16_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16;
};
template <>
struct TypeToTensorType<uint32_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32;
};
template <>
struct TypeToTensorType<uint64_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64;
};
template <>
struct TypeToTensorType<bool> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL;
};
 
template <>
struct TypeToTensorType<Float8E4M3FN_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN;
};
template <>
struct TypeToTensorType<Float8E4M3FNUZ_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ;
};
template <>
struct TypeToTensorType<Float8E5M2_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2;
};
template <>
struct TypeToTensorType<Float8E5M2FNUZ_t> {
  static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ;
};
 
inline bool BFloat16_t::operator==(const BFloat16_t& rhs) const noexcept {
  if (IsNaN() || rhs.IsNaN()) {
    // IEEE defines that NaN is not equal to anything, including itself.
    return false;
  }
  return val == rhs.val;
}
 
inline bool BFloat16_t::operator<(const BFloat16_t& rhs) const noexcept {
  if (IsNaN() || rhs.IsNaN()) {
    // IEEE defines that NaN is unordered with respect to everything, including itself.
    return false;
  }
 
  const bool left_is_negative = IsNegative();
  if (left_is_negative != rhs.IsNegative()) {
    // When the signs of left and right differ, we know that left is less than right if it is
    // the negative value. The exception to this is if both values are zero, in which case IEEE
    // says they should be equal, even if the signs differ.
    return left_is_negative && !AreZero(*this, rhs);
  }
  return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative);
}
 
inline MemoryAllocation::MemoryAllocation(OrtAllocator* allocator, void* p, size_t size)
    : allocator_(allocator), p_(p), size_(size) {
}
 
inline MemoryAllocation::~MemoryAllocation() {
  if (p_ != nullptr) {
    // We do not throw out of destructor
    auto ret = GetApi().AllocatorFree(allocator_, p_);
    static_cast<void>(ret);
  }
}
 
inline MemoryAllocation::MemoryAllocation(MemoryAllocation&& o) noexcept : allocator_(nullptr), p_(nullptr), size_(0) {
  *this = std::move(o);
}
 
inline MemoryAllocation& MemoryAllocation::operator=(MemoryAllocation&& o) noexcept {
  OrtAllocator* alloc = nullptr;
  void* p = nullptr;
  size_t sz = 0;
 
  // Swap out this
  std::swap(alloc, allocator_);
  std::swap(p, p_);
  std::swap(sz, size_);
 
  // Swap with incoming
  std::swap(allocator_, o.allocator_);
  std::swap(p_, o.p_);
  std::swap(size_, o.size_);
 
  // Destroy this instance if needed
  MemoryAllocation this_alloc(alloc, p, sz);
  return *this;
}
 
namespace detail {
 
template <typename T>
inline void* AllocatorImpl<T>::Alloc(size_t size) {
  void* out;
  ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out));
  return out;
}
 
template <typename T>
inline void* AllocatorImpl<T>::Reserve(size_t size) {
  // Reserve was added in version 18. For older allocators the field may be
  // uninitialized, so we must not dereference it.
  if (this->p_->version >= 18 && this->p_->Reserve) {
    return this->p_->Reserve(this->p_, size);
  }
  // Fall back to Alloc() for allocators that don't implement Reserve,
  // matching the ORT-core adapter behavior (IAllocatorImplWrappingOrtAllocator,
  // IArenaImplWrappingOrtAllocator).
  return this->p_->Alloc(this->p_, size);
}
 
template <typename T>
inline MemoryAllocation AllocatorImpl<T>::GetAllocation(size_t size) {
  void* out;
  ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out));
  MemoryAllocation result(this->p_, out, size);
  return result;
}
 
template <typename T>
inline void AllocatorImpl<T>::Free(void* p) {
  ThrowOnError(GetApi().AllocatorFree(this->p_, p));
}
 
template <typename T>
inline ConstMemoryInfo AllocatorImpl<T>::GetInfo() const {
  const OrtMemoryInfo* out;
  ThrowOnError(GetApi().AllocatorGetInfo(this->p_, &out));
  return ConstMemoryInfo{out};
}
 
template <typename T>
inline KeyValuePairs AllocatorImpl<T>::GetStats() const {
  OrtKeyValuePairs* out;
  ThrowOnError(GetApi().AllocatorGetStats(this->p_, &out));
  return KeyValuePairs(out);
}
 
template <typename T>
inline void AllocatorImpl<T>::Shrink() {
  // Shrink was added in version 25. For older allocators the field may be
  // uninitialized, so we must not dereference it.
  if (this->p_->version >= 25 && this->p_->Shrink) {
    ThrowOnError(this->p_->Shrink(this->p_));
  }
}
}  // namespace detail
 
inline AllocatorWithDefaultOptions::AllocatorWithDefaultOptions() {
  ThrowOnError(GetApi().GetAllocatorWithDefaultOptions(&this->p_));
}
 
inline Allocator::Allocator(const Session& sess, const OrtMemoryInfo* mem_info) {
  ThrowOnError(GetApi().CreateAllocator(sess, mem_info, &this->p_));
}
 
namespace detail {
 
template <typename T>
inline std::string MemoryInfoImpl<T>::GetAllocatorName() const {
  const char* name = nullptr;
  ThrowOnError(GetApi().MemoryInfoGetName(this->p_, &name));
  return std::string(name);
}
 
template <typename T>
inline OrtAllocatorType MemoryInfoImpl<T>::GetAllocatorType() const {
  OrtAllocatorType type;
  ThrowOnError(GetApi().MemoryInfoGetType(this->p_, &type));
  return type;
}
 
template <typename T>
inline int MemoryInfoImpl<T>::GetDeviceId() const {
  int id = 0;
  ThrowOnError(GetApi().MemoryInfoGetId(this->p_, &id));
  return id;
}
 
template <typename T>
inline OrtMemoryInfoDeviceType MemoryInfoImpl<T>::GetDeviceType() const {
  OrtMemoryInfoDeviceType type;
  GetApi().MemoryInfoGetDeviceType(this->p_, &type);
  return type;
}
 
template <typename T>
inline OrtMemType MemoryInfoImpl<T>::GetMemoryType() const {
  OrtMemType type;
  ThrowOnError(GetApi().MemoryInfoGetMemType(this->p_, &type));
  return type;
}
 
template <typename T>
inline OrtDeviceMemoryType MemoryInfoImpl<T>::GetDeviceMemoryType() const {
  return GetApi().MemoryInfoGetDeviceMemType(this->p_);
}
 
template <typename T>
inline uint32_t MemoryInfoImpl<T>::GetVendorId() const {
  return GetApi().MemoryInfoGetVendorId(this->p_);
}
 
template <typename T>
template <typename U>
inline bool MemoryInfoImpl<T>::operator==(const MemoryInfoImpl<U>& o) const {
  int comp_result = 0;
  ThrowOnError(Ort::GetApi().CompareMemoryInfo(this->p_, o, &comp_result));
  return comp_result == 0;
}
 
}  // namespace detail
 
inline MemoryInfo MemoryInfo::CreateCpu(OrtAllocatorType type, OrtMemType mem_type) {
  OrtMemoryInfo* p;
  ThrowOnError(GetApi().CreateCpuMemoryInfo(type, mem_type, &p));
  return MemoryInfo(p);
}
 
inline MemoryInfo::MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type) {
  ThrowOnError(GetApi().CreateMemoryInfo(name, type, id, mem_type, &this->p_));
}
 
inline MemoryInfo::MemoryInfo(const char* name, OrtMemoryInfoDeviceType device_type, uint32_t vendor_id, uint32_t device_id,
                              OrtDeviceMemoryType mem_type, size_t alignment, OrtAllocatorType allocator_type) {
  ThrowOnError(GetApi().CreateMemoryInfo_V2(name, device_type, vendor_id, device_id, mem_type, alignment,
                                            allocator_type, &this->p_));
}
 
namespace detail {
template <typename T>
inline std::vector<std::string> ConstIoBindingImpl<T>::GetOutputNames() const {
  AllocatorWithDefaultOptions allocator;
  return binding_utils::GetOutputNamesHelper(this->p_, allocator);
}
 
template <typename T>
inline std::vector<std::string> ConstIoBindingImpl<T>::GetOutputNames(OrtAllocator* allocator) const {
  return binding_utils::GetOutputNamesHelper(this->p_, allocator);
}
 
template <typename T>
inline std::vector<Value> ConstIoBindingImpl<T>::GetOutputValues() const {
  AllocatorWithDefaultOptions allocator;
  return binding_utils::GetOutputValuesHelper(this->p_, allocator);
}
 
template <typename T>
inline std::vector<Value> ConstIoBindingImpl<T>::GetOutputValues(OrtAllocator* allocator) const {
  return binding_utils::GetOutputValuesHelper(this->p_, allocator);
}
 
template <typename T>
inline void IoBindingImpl<T>::BindInput(const char* name, const Value& value) {
  ThrowOnError(GetApi().BindInput(this->p_, name, value));
}
 
template <typename T>
inline void IoBindingImpl<T>::BindOutput(const char* name, const Value& value) {
  ThrowOnError(GetApi().BindOutput(this->p_, name, value));
}
 
template <typename T>
inline void IoBindingImpl<T>::BindOutput(const char* name, const OrtMemoryInfo* mem_info) {
  ThrowOnError(GetApi().BindOutputToDevice(this->p_, name, mem_info));
}
 
template <typename T>
inline void IoBindingImpl<T>::ClearBoundInputs() {
  GetApi().ClearBoundInputs(this->p_);
}
 
template <typename T>
inline void IoBindingImpl<T>::ClearBoundOutputs() {
  GetApi().ClearBoundOutputs(this->p_);
}
 
template <typename T>
inline void IoBindingImpl<T>::SynchronizeInputs() {
  ThrowOnError(GetApi().SynchronizeBoundInputs(this->p_));
}
 
template <typename T>
inline void IoBindingImpl<T>::SynchronizeOutputs() {
  ThrowOnError(GetApi().SynchronizeBoundOutputs(this->p_));
}
 
namespace binding_utils {
inline std::vector<std::string> GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) {
  std::vector<std::string> result;
  auto free_fn = detail::AllocatedFree(allocator);
  using Ptr = std::unique_ptr<void, decltype(free_fn)>;
 
  char* buffer = nullptr;
  size_t* lengths = nullptr;
  size_t count = 0;
  ThrowOnError(GetApi().GetBoundOutputNames(binding, allocator, &buffer, &lengths, &count));
 
  if (count == 0) {
    return result;
  }
 
  Ptr buffer_g(buffer, free_fn);
  Ptr lengths_g(lengths, free_fn);
 
  result.reserve(count);
  for (size_t i = 0; i < count; ++i) {
    auto sz = *lengths;
    result.emplace_back(buffer, sz);
    buffer += sz;
    ++lengths;
  }
  return result;
}
 
inline std::vector<Value> GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) {
  std::vector<Value> result;
  size_t output_count = 0;
 
  OrtValue** output_buffer = nullptr;
  ThrowOnError(GetApi().GetBoundOutputValues(binding, allocator, &output_buffer, &output_count));
  if (output_count == 0) {
    return result;
  }
 
  std::unique_ptr<void, AllocatedFree> buffer_g(output_buffer, AllocatedFree(allocator));
 
  result.reserve(output_count);
  for (size_t i = 0; i < output_count; ++i) {
    result.emplace_back(output_buffer[i]);
  }
  return result;
}
 
}  // namespace binding_utils
}  // namespace detail
 
inline IoBinding::IoBinding(Session& session) {
  ThrowOnError(GetApi().CreateIoBinding(session, &this->p_));
}
 
inline ArenaCfg::ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk) {
  ThrowOnError(GetApi().CreateArenaCfg(max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, &p_));
}
 
inline ArenaCfg::ArenaCfg(const std::unordered_map<std::string, size_t>& arena_config) {
  std::vector<const char*> keys;
  std::vector<size_t> values;
  keys.reserve(arena_config.size());
  values.reserve(arena_config.size());
  for (const auto& kv : arena_config) {
    keys.push_back(kv.first.c_str());
    values.push_back(kv.second);
  }
  ThrowOnError(GetApi().CreateArenaCfgV2(keys.data(), values.data(), arena_config.size(), &p_));
}
 
inline ThreadingOptions::ThreadingOptions() {
  ThrowOnError(GetApi().CreateThreadingOptions(&p_));
}
 
inline ThreadingOptions& ThreadingOptions::SetGlobalIntraOpNumThreads(int intra_op_num_threads) {
  ThrowOnError(GetApi().SetGlobalIntraOpNumThreads(p_, intra_op_num_threads));
  return *this;
}
 
inline ThreadingOptions& ThreadingOptions::SetGlobalInterOpNumThreads(int inter_op_num_threads) {
  ThrowOnError(GetApi().SetGlobalInterOpNumThreads(p_, inter_op_num_threads));
  return *this;
}
 
inline ThreadingOptions& ThreadingOptions::SetGlobalSpinControl(int allow_spinning) {
  ThrowOnError(GetApi().SetGlobalSpinControl(p_, allow_spinning));
  return *this;
}
 
inline ThreadingOptions& ThreadingOptions::SetGlobalDenormalAsZero() {
  ThrowOnError(GetApi().SetGlobalDenormalAsZero(p_));
  return *this;
}
 
inline ThreadingOptions& ThreadingOptions::SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) {
  ThrowOnError(GetApi().SetGlobalCustomCreateThreadFn(p_, ort_custom_create_thread_fn));
  return *this;
}
 
inline ThreadingOptions& ThreadingOptions::SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options) {
  ThrowOnError(GetApi().SetGlobalCustomThreadCreationOptions(p_, ort_custom_thread_creation_options));
  return *this;
}
 
inline ThreadingOptions& ThreadingOptions::SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) {
  ThrowOnError(GetApi().SetGlobalCustomJoinThreadFn(p_, ort_custom_join_thread_fn));
  return *this;
}
 
inline TensorRTProviderOptions::TensorRTProviderOptions() {
  ThrowOnError(GetApi().CreateTensorRTProviderOptions(&this->p_));
}
 
inline void TensorRTProviderOptions::Update(const std::unordered_map<std::string, std::string>& options) {
  std::vector<const char*> keys;
  std::vector<const char*> values;
  keys.reserve(options.size());
  values.reserve(options.size());
  for (const auto& kv : options) {
    keys.push_back(kv.first.c_str());
    values.push_back(kv.second.c_str());
  }
  ThrowOnError(GetApi().UpdateTensorRTProviderOptions(p_, keys.data(), values.data(), options.size()));
}
 
inline void TensorRTProviderOptions::UpdateWithValue(const char* key, void* value) {
  ThrowOnError(GetApi().UpdateTensorRTProviderOptionsWithValue(p_, key, value));
}
 
inline void* TensorRTProviderOptions::GetOptionByName(const char* name) const {
  void* value = nullptr;
  ThrowOnError(GetApi().GetTensorRTProviderOptionsByName(p_, name, &value));
  return value;
}
 
inline std::string TensorRTProviderOptions::GetTensorRTProviderOptionsAsString() const {
  AllocatorWithDefaultOptions allocator;
  char* options_str = nullptr;
  ThrowOnError(GetApi().GetTensorRTProviderOptionsAsString(p_, allocator, &options_str));
  std::unique_ptr<void, detail::AllocatedFree> options_str_g(options_str, detail::AllocatedFree(allocator));
  return std::string(options_str);
}
 
inline CUDAProviderOptions::CUDAProviderOptions() {
  ThrowOnError(GetApi().CreateCUDAProviderOptions(&this->p_));
}
 
inline void CUDAProviderOptions::Update(const std::unordered_map<std::string, std::string>& options) {
  std::vector<const char*> keys;
  std::vector<const char*> values;
  keys.reserve(options.size());
  values.reserve(options.size());
  for (const auto& kv : options) {
    keys.push_back(kv.first.c_str());
    values.push_back(kv.second.c_str());
  }
  ThrowOnError(GetApi().UpdateCUDAProviderOptions(p_, keys.data(), values.data(), options.size()));
}
 
inline std::string CUDAProviderOptions::GetCUDAProviderOptionsAsString() const {
  AllocatorWithDefaultOptions allocator;
  char* options_str = nullptr;
  ThrowOnError(GetApi().GetCUDAProviderOptionsAsString(p_, allocator, &options_str));
  std::unique_ptr<void, detail::AllocatedFree> options_str_g(options_str, detail::AllocatedFree(allocator));
  return std::string(options_str);
}
 
inline void CUDAProviderOptions::UpdateWithValue(const char* key, void* value) {
  ThrowOnError(GetApi().UpdateCUDAProviderOptionsWithValue(p_, key, value));
}
 
inline void* CUDAProviderOptions::GetOptionByName(const char* name) const {
  void* value = nullptr;
  ThrowOnError(GetApi().GetCUDAProviderOptionsByName(p_, name, &value));
  return value;
}
 
inline PrepackedWeightsContainer::PrepackedWeightsContainer() {
  ThrowOnError(GetApi().CreatePrepackedWeightsContainer(&this->p_));
}
 
namespace detail {
 
template <typename T>
inline const std::basic_string<ORTCHAR_T> ConstExternalInitializerInfoImpl<T>::GetFilePath() const {
  return GetApi().ExternalInitializerInfo_GetFilePath(this->p_);
}
 
template <typename T>
inline int64_t ConstExternalInitializerInfoImpl<T>::GetFileOffset() const {
  return GetApi().ExternalInitializerInfo_GetFileOffset(this->p_);
}
 
template <typename T>
inline size_t ConstExternalInitializerInfoImpl<T>::GetByteSize() const {
  return GetApi().ExternalInitializerInfo_GetByteSize(this->p_);
}
}  // namespace detail
 
inline ExternalInitializerInfo::ExternalInitializerInfo(const ORTCHAR_T* filepath, int64_t file_offset,
                                                        size_t byte_size) {
  ThrowOnError(GetApi().CreateExternalInitializerInfo(filepath, file_offset, byte_size, &this->p_));
}
 
inline Status ExternalInitializerInfo::Create(const ORTCHAR_T* filepath, int64_t file_offset, size_t byte_size,
                                              /*out*/ ExternalInitializerInfo& out) {
  OrtExternalInitializerInfo* info = nullptr;
  OrtStatus* status = GetApi().CreateExternalInitializerInfo(filepath, file_offset, byte_size, &info);
  if (status != nullptr) {
    return Status{status};
  }
 
  out = ExternalInitializerInfo(info);
 
  return Status{nullptr};
}
 
namespace detail {
template <typename T>
inline const char* KeyValuePairsImpl<T>::GetValue(const char* key) const {
  return GetApi().GetKeyValue(this->p_, key);
}
 
template <typename T>
inline std::unordered_map<std::string, std::string> KeyValuePairsImpl<T>::GetKeyValuePairs() const {
  std::unordered_map<std::string, std::string> out;
 
  size_t num_pairs = 0;
  const char* const* keys = nullptr;
  const char* const* values = nullptr;
  GetApi().GetKeyValuePairs(this->p_, &keys, &values, &num_pairs);
  if (num_pairs > 0) {
    out.reserve(num_pairs);
    for (size_t i = 0; i < num_pairs; ++i) {
      out.emplace(keys[i], values[i]);
    }
  }
 
  return out;
}
 
template <typename T>
inline void KeyValuePairsImpl<T>::GetKeyValuePairs(std::vector<const char*>& keys,
                                                   std::vector<const char*>& values) const {
  keys.clear();
  values.clear();
 
  size_t num_pairs = 0;
  const char* const* keys_ptr = nullptr;
  const char* const* values_ptr = nullptr;
  GetApi().GetKeyValuePairs(this->p_, &keys_ptr, &values_ptr, &num_pairs);
  if (num_pairs > 0) {
    keys.resize(num_pairs);
    values.resize(num_pairs);
    std::copy(keys_ptr, keys_ptr + num_pairs, keys.begin());
    std::copy(values_ptr, values_ptr + num_pairs, values.begin());
  }
}
}  // namespace detail
 
inline KeyValuePairs::KeyValuePairs() {
  GetApi().CreateKeyValuePairs(&p_);
}
 
inline KeyValuePairs::KeyValuePairs(const std::unordered_map<std::string, std::string>& kv_pairs) {
  GetApi().CreateKeyValuePairs(&p_);
  for (const auto& kv : kv_pairs) {
    GetApi().AddKeyValuePair(this->p_, kv.first.c_str(), kv.second.c_str());
  }
}
 
inline void KeyValuePairs::Add(const char* key, const char* value) {
  GetApi().AddKeyValuePair(this->p_, key, value);
}
 
inline void KeyValuePairs::Remove(const char* key) {
  GetApi().RemoveKeyValuePair(this->p_, key);
}
 
namespace detail {
template <typename T>
inline void* SyncStreamImpl<T>::GetHandle() {
  return GetApi().SyncStream_GetHandle(this->p_);
}
}  // namespace detail
 
namespace detail {
template <typename T>
inline OrtHardwareDeviceType HardwareDeviceImpl<T>::Type() const {
  return GetApi().HardwareDevice_Type(this->p_);
}
 
template <typename T>
inline uint32_t HardwareDeviceImpl<T>::VendorId() const {
  return GetApi().HardwareDevice_VendorId(this->p_);
}
 
template <typename T>
inline uint32_t HardwareDeviceImpl<T>::DeviceId() const {
  return GetApi().HardwareDevice_DeviceId(this->p_);
}
 
template <typename T>
inline const char* HardwareDeviceImpl<T>::Vendor() const {
  return GetApi().HardwareDevice_Vendor(this->p_);
}
 
template <typename T>
inline ConstKeyValuePairs HardwareDeviceImpl<T>::Metadata() const {
  return ConstKeyValuePairs{GetApi().HardwareDevice_Metadata(this->p_)};
}
 
template <typename T>
inline const char* EpDeviceImpl<T>::EpName() const {
  return GetApi().EpDevice_EpName(this->p_);
}
 
template <typename T>
inline const char* EpDeviceImpl<T>::EpVendor() const {
  return GetApi().EpDevice_EpVendor(this->p_);
}
 
template <typename T>
inline ConstKeyValuePairs EpDeviceImpl<T>::EpMetadata() const {
  return ConstKeyValuePairs(GetApi().EpDevice_EpMetadata(this->p_));
}
 
template <typename T>
inline ConstKeyValuePairs EpDeviceImpl<T>::EpOptions() const {
  return ConstKeyValuePairs(GetApi().EpDevice_EpOptions(this->p_));
}
 
template <typename T>
inline ConstHardwareDevice EpDeviceImpl<T>::Device() const {
  return ConstHardwareDevice(GetApi().EpDevice_Device(this->p_));
}
 
template <typename T>
inline ConstMemoryInfo EpDeviceImpl<T>::GetMemoryInfo(OrtDeviceMemoryType memory_type) const {
  const auto* mem_info = GetApi().EpDevice_MemoryInfo(this->p_, memory_type);
  return ConstMemoryInfo{mem_info};
}
 
template <typename T>
inline SyncStream EpDeviceImpl<T>::CreateSyncStream(ConstKeyValuePairs stream_options) const {
  OrtSyncStream* stream = nullptr;
  ThrowOnError(GetApi().CreateSyncStreamForEpDevice(this->p_, stream_options, &stream));
  return SyncStream{stream};
}
}  // namespace detail
 
inline EpDevice::EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device,
                          ConstKeyValuePairs ep_metadata, ConstKeyValuePairs ep_options) {
  ThrowOnError(GetEpApi().CreateEpDevice(&ep_factory, hardware_device, ep_metadata, ep_options, &p_));
}
 
namespace detail {
template <typename T>
inline std::string EpAssignedSubgraphImpl<T>::GetEpName() const {
  const char* ep_name = nullptr;
 
  // Returned null-terminated string will not be null if API function returns successfully.
  ThrowOnError(GetApi().EpAssignedSubgraph_GetEpName(this->p_, &ep_name));
  return std::string(ep_name);
}
 
template <typename T>
inline std::vector<ConstEpAssignedNode> EpAssignedSubgraphImpl<T>::GetNodes() const {
  size_t num_ep_nodes = 0;
  const OrtEpAssignedNode* const* ep_node_ptrs = nullptr;
  ThrowOnError(GetApi().EpAssignedSubgraph_GetNodes(this->p_, &ep_node_ptrs, &num_ep_nodes));
 
  std::vector<ConstEpAssignedNode> ep_nodes;
  if (num_ep_nodes > 0) {
    ep_nodes.reserve(num_ep_nodes);
    for (size_t i = 0; i < num_ep_nodes; ++i) {
      ep_nodes.emplace_back(ep_node_ptrs[i]);
    }
  }
 
  return ep_nodes;
}
 
template <typename T>
inline std::string EpAssignedNodeImpl<T>::GetName() const {
  const char* node_name = nullptr;
 
  // Returned null-terminated string will not be null if API function returns successfully.
  ThrowOnError(GetApi().EpAssignedNode_GetName(this->p_, &node_name));
  return std::string(node_name);
}
 
template <typename T>
inline std::string EpAssignedNodeImpl<T>::GetDomain() const {
  const char* domain = nullptr;
 
  // Returned null-terminated string will not be null if API function returns successfully.
  ThrowOnError(GetApi().EpAssignedNode_GetDomain(this->p_, &domain));
  return std::string(domain);
}
 
template <typename T>
inline std::string EpAssignedNodeImpl<T>::GetOperatorType() const {
  const char* op_type = nullptr;
 
  // Returned null-terminated string will not be null if API function returns successfully.
  ThrowOnError(GetApi().EpAssignedNode_GetOperatorType(this->p_, &op_type));
  return std::string(op_type);
}
}  // namespace detail
 
// ProfilingEvent implementations
namespace detail {
template <typename T>
inline OrtProfilingEventCategory ConstProfilingEventImpl<T>::GetCategory() const {
  OrtProfilingEventCategory out{};
  ThrowOnError(GetEpApi().ProfilingEvent_GetCategory(this->p_, &out));
  return out;
}
 
template <typename T>
inline const char* ConstProfilingEventImpl<T>::GetName() const {
  const char* name = nullptr;
  ThrowOnError(GetEpApi().ProfilingEvent_GetName(this->p_, &name));
  return name;
}
 
template <typename T>
inline int64_t ConstProfilingEventImpl<T>::GetTimestampUs() const {
  int64_t out = 0;
  ThrowOnError(GetEpApi().ProfilingEvent_GetTimestampUs(this->p_, &out));
  return out;
}
 
template <typename T>
inline int64_t ConstProfilingEventImpl<T>::GetDurationUs() const {
  int64_t out = 0;
  ThrowOnError(GetEpApi().ProfilingEvent_GetDurationUs(this->p_, &out));
  return out;
}
 
template <typename T>
inline const char* ConstProfilingEventImpl<T>::GetArgValue(const char* key) const {
  const char* value = nullptr;
  ThrowOnError(GetEpApi().ProfilingEvent_GetArgValue(this->p_, key, &value));
  return value;
}
}  // namespace detail
 
inline ProfilingEvent::ProfilingEvent(OrtProfilingEventCategory category,
                                      int32_t process_id,
                                      int32_t thread_id,
                                      const char* event_name,
                                      int64_t timestamp_us,
                                      int64_t duration_us,
                                      const std::unordered_map<std::string, std::string>& args) {
  const size_t num_args = args.size();
  std::vector<const char*> arg_keys;
  std::vector<const char*> arg_vals;
 
  arg_keys.reserve(num_args);
  arg_vals.reserve(num_args);
  for (const auto& [k, v] : args) {
    arg_keys.push_back(k.c_str());
    arg_vals.push_back(v.c_str());
  }
 
  ThrowOnError(GetEpApi().CreateProfilingEvent(category, process_id, thread_id, event_name,
                                               timestamp_us, duration_us,
                                               arg_keys.data(), arg_vals.data(), num_args, &p_));
}
 
inline ProfilingEvent::ProfilingEvent(OrtProfilingEventCategory category,
                                      int32_t process_id,
                                      int32_t thread_id,
                                      const char* event_name,
                                      int64_t timestamp_us,
                                      int64_t duration_us,
                                      const char* const* arg_keys,
                                      const char* const* arg_values,
                                      size_t num_args) {
  ThrowOnError(GetEpApi().CreateProfilingEvent(category, process_id, thread_id, event_name,
                                               timestamp_us, duration_us,
                                               arg_keys, arg_values, num_args, &p_));
}
 
// ProfilingEventsContainer implementations
namespace detail {
template <typename T>
inline Status ProfilingEventsContainerImpl<T>::AddEvents(const OrtProfilingEvent* const* events, size_t num_events) {
  return Status{GetEpApi().ProfilingEventsContainer_AddEvents(this->p_, events, num_events)};
}
 
template <typename T>
inline Status ProfilingEventsContainerImpl<T>::AddEvents(const std::vector<ProfilingEvent>& events) {
  static_assert(sizeof(ProfilingEvent) == sizeof(OrtProfilingEvent*) &&
                    alignof(ProfilingEvent) == alignof(OrtProfilingEvent*),
                "ProfilingEvent must have the same size and alignment as a raw pointer for reinterpret_cast");
  const auto* event_ptrs = reinterpret_cast<const OrtProfilingEvent* const*>(events.data());
  return AddEvents(event_ptrs, events.size());
}
}  // namespace detail
 
inline Env::Env(OrtLoggingLevel logging_level, _In_ const char* logid) {
  ThrowOnError(GetApi().CreateEnv(logging_level, logid, &p_));
  if (strcmp(logid, "onnxruntime-node") == 0) {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
  } else {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
  }
}
 
inline Env::Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param) {
  ThrowOnError(GetApi().CreateEnvWithCustomLogger(logging_function, logger_param, logging_level, logid, &p_));
  if (strcmp(logid, "onnxruntime-node") == 0) {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
  } else {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
  }
}
 
inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level, _In_ const char* logid) {
  ThrowOnError(GetApi().CreateEnvWithGlobalThreadPools(logging_level, logid, tp_options, &p_));
  if (strcmp(logid, "onnxruntime-node") == 0) {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
  } else {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
  }
}
 
inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param,
                OrtLoggingLevel logging_level, _In_ const char* logid) {
  ThrowOnError(GetApi().CreateEnvWithCustomLoggerAndGlobalThreadPools(logging_function, logger_param, logging_level, logid, tp_options, &p_));
  if (strcmp(logid, "onnxruntime-node") == 0) {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
  } else {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
  }
}
 
inline Env::Env(const OrtEnvCreationOptions* options) {
  ThrowOnError(GetApi().CreateEnvWithOptions(options, &p_));
  if (strcmp(options->log_id, "onnxruntime-node") == 0) {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS));
  } else {
    ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS));
  }
}
 
inline Env& Env::EnableTelemetryEvents() {
  ThrowOnError(GetApi().EnableTelemetryEvents(p_));
  return *this;
}
 
inline Env& Env::DisableTelemetryEvents() {
  ThrowOnError(GetApi().DisableTelemetryEvents(p_));
  return *this;
}
 
inline Env& Env::UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level) {
  ThrowOnError(GetApi().UpdateEnvWithCustomLogLevel(p_, log_severity_level));
  return *this;
}
 
inline Env& Env::CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg) {
  ThrowOnError(GetApi().CreateAndRegisterAllocator(p_, mem_info, arena_cfg));
  return *this;
}
 
inline Env& Env::CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, const std::unordered_map<std::string, std::string>& options, const OrtArenaCfg* arena_cfg) {
  std::vector<const char*> keys, values;
  auto num_entries = options.size();
  if (num_entries > 0) {
    keys.reserve(num_entries);
    values.reserve(num_entries);
    for (const auto& entry : options) {
      keys.push_back(entry.first.c_str());
      values.push_back(entry.second.c_str());
    }
  }
  ThrowOnError(GetApi().CreateAndRegisterAllocatorV2(p_, provider_type.c_str(), mem_info, arena_cfg, keys.data(), values.data(), num_entries));
  return *this;
}
 
inline Env& Env::RegisterAllocator(OrtAllocator* allocator) {
  ThrowOnError(GetApi().RegisterAllocator(p_, allocator));
  return *this;
}
 
inline Env& Env::UnregisterAllocator(const OrtMemoryInfo* mem_info) {
  ThrowOnError(GetApi().UnregisterAllocator(p_, mem_info));
  return *this;
}
 
inline Env& Env::RegisterExecutionProviderLibrary(const char* registration_name,
                                                  const std::basic_string<ORTCHAR_T>& path) {
  ThrowOnError(GetApi().RegisterExecutionProviderLibrary(p_, registration_name, path.c_str()));
  return *this;
}
 
inline Env& Env::UnregisterExecutionProviderLibrary(const char* registration_name) {
  ThrowOnError(GetApi().UnregisterExecutionProviderLibrary(p_, registration_name));
  return *this;
}
 
inline Env& Env::SetPerSessionThreadPoolCallbacks(const OrtThreadPoolCallbacksConfig& config) {
  ThrowOnError(GetApi().SetPerSessionThreadPoolCallbacks(p_, &config));
  return *this;
}
 
inline std::vector<ConstEpDevice> Env::GetEpDevices() const {
  size_t num_devices = 0;
  const OrtEpDevice* const* device_ptrs = nullptr;
  ThrowOnError(GetApi().GetEpDevices(p_, &device_ptrs, &num_devices));
 
  std::vector<ConstEpDevice> devices;
  if (num_devices > 0) {
    devices.reserve(num_devices);
    for (size_t i = 0; i < num_devices; ++i) {
      devices.emplace_back(device_ptrs[i]);
    }
  }
 
  return devices;
}
 
inline size_t Env::GetNumHardwareDevices() const {
  size_t num_devices = 0;
  ThrowOnError(GetApi().GetNumHardwareDevices(p_, &num_devices));
  return num_devices;
}
 
inline std::vector<ConstHardwareDevice> Env::GetHardwareDevices() const {
  size_t num_devices = 0;
  ThrowOnError(GetApi().GetNumHardwareDevices(p_, &num_devices));
 
  std::vector<ConstHardwareDevice> devices;
  if (num_devices > 0) {
    std::vector<const OrtHardwareDevice*> device_ptrs(num_devices);
    ThrowOnError(GetApi().GetHardwareDevices(p_, device_ptrs.data(), num_devices));
    devices.reserve(num_devices);
    for (size_t i = 0; i < num_devices; ++i) {
      devices.emplace_back(device_ptrs[i]);
    }
  }
 
  return devices;
}
 
inline DeviceEpIncompatibilityDetails Env::GetHardwareDeviceEpIncompatibilityDetails(
    const char* ep_name, ConstHardwareDevice hw) const {
  OrtDeviceEpIncompatibilityDetails* details = nullptr;
  ThrowOnError(GetApi().GetHardwareDeviceEpIncompatibilityDetails(p_, ep_name, hw, &details));
  return DeviceEpIncompatibilityDetails{details};
}
 
template <typename T>
inline uint32_t detail::DeviceEpIncompatibilityDetailsImpl<T>::GetReasonsBitmask() const {
  uint32_t reasons_bitmask = 0;
  ThrowOnError(GetApi().DeviceEpIncompatibilityDetails_GetReasonsBitmask(this->p_, &reasons_bitmask));
  return reasons_bitmask;
}
 
template <typename T>
inline const char* detail::DeviceEpIncompatibilityDetailsImpl<T>::GetNotes() const {
  const char* notes = nullptr;
  ThrowOnError(GetApi().DeviceEpIncompatibilityDetails_GetNotes(this->p_, &notes));
  return notes;
}
 
template <typename T>
inline int32_t detail::DeviceEpIncompatibilityDetailsImpl<T>::GetErrorCode() const {
  int32_t error_code = 0;
  ThrowOnError(GetApi().DeviceEpIncompatibilityDetails_GetErrorCode(this->p_, &error_code));
  return error_code;
}
 
inline Status Env::CopyTensors(const std::vector<Value>& src_tensors,
                               const std::vector<Value>& dst_tensors,
                               OrtSyncStream* stream) const {
  if (src_tensors.size() != dst_tensors.size()) {
    return Status("Source and destination tensor vectors must have the same size", ORT_INVALID_ARGUMENT);
  }
  if (src_tensors.empty()) {
    return Status(nullptr);
  }
 
  const OrtValue* const* src_tensors_ptr = reinterpret_cast<const OrtValue* const*>(src_tensors.data());
  OrtValue* const* dst_tensors_ptr = reinterpret_cast<OrtValue* const*>(dst_tensors.data());
  OrtStatus* status = GetApi().CopyTensors(p_, src_tensors_ptr, dst_tensors_ptr, stream, src_tensors.size());
  return Status(status);
}
 
inline Status Env::CopyTensor(const OrtValue* src_tensor, OrtValue* dst_tensor, OrtSyncStream* stream) const {
  OrtStatus* status = GetApi().CopyTensors(p_, &src_tensor, &dst_tensor, stream, 1);
  return Status(status);
}
 
inline UnownedAllocator Env::CreateSharedAllocator(const OrtEpDevice* ep_device, OrtDeviceMemoryType mem_type,
                                                   OrtAllocatorType allocator_type,
                                                   const OrtKeyValuePairs* allocator_options) {
  OrtAllocator* p;
  ThrowOnError(GetApi().CreateSharedAllocator(p_, ep_device, mem_type, allocator_type, allocator_options, &p));
  return UnownedAllocator{p};
}
 
inline UnownedAllocator Env::GetSharedAllocator(const OrtMemoryInfo* mem_info) {
  OrtAllocator* p;
  ThrowOnError(GetApi().GetSharedAllocator(p_, mem_info, &p));
  return UnownedAllocator{p};
}
 
inline void Env::ReleaseSharedAllocator(const OrtEpDevice* ep_device,
                                        OrtDeviceMemoryType mem_type) {
  ThrowOnError(GetApi().ReleaseSharedAllocator(p_, ep_device, mem_type));
}
 
inline CustomOpDomain::CustomOpDomain(const char* domain) {
  ThrowOnError(GetApi().CreateCustomOpDomain(domain, &p_));
}
 
inline void CustomOpDomain::Add(const OrtCustomOp* op) {
  ThrowOnError(GetApi().CustomOpDomain_Add(p_, op));
}
 
inline OrtCompiledModelCompatibility GetModelCompatibilityForEpDevices(
    const std::vector<ConstEpDevice>& ep_devices,
    const char* compatibility_info) {
  if (ep_devices.empty()) {
    ORT_CXX_API_THROW("ep_devices is empty", ORT_INVALID_ARGUMENT);
  }
 
  std::vector<const OrtEpDevice*> ptrs;
  ptrs.reserve(ep_devices.size());
  for (const auto& d : ep_devices) ptrs.push_back(d);
 
  OrtCompiledModelCompatibility status = OrtCompiledModelCompatibility_EP_NOT_APPLICABLE;
  ThrowOnError(GetApi().GetModelCompatibilityForEpDevices(
      reinterpret_cast<const OrtEpDevice* const*>(ptrs.data()),
      ptrs.size(),
      compatibility_info,
      &status));
  return status;
}
 
inline AllocatedStringPtr GetCompatibilityInfoFromModelAllocated(const ORTCHAR_T* model_path, const char* ep_type,
                                                                 OrtAllocator* allocator) {
  char* compat_info = nullptr;
  ThrowOnError(GetApi().GetCompatibilityInfoFromModel(model_path, ep_type, allocator, &compat_info));
  return AllocatedStringPtr(compat_info, detail::AllocatedFree(allocator));
}
 
inline AllocatedStringPtr GetCompatibilityInfoFromModelBytesAllocated(const void* model_data, size_t model_data_length,
                                                                      const char* ep_type, OrtAllocator* allocator) {
  char* compat_info = nullptr;
  ThrowOnError(GetApi().GetCompatibilityInfoFromModelBytes(model_data, model_data_length, ep_type, allocator, &compat_info));
  return AllocatedStringPtr(compat_info, detail::AllocatedFree(allocator));
}
 
inline LoraAdapter LoraAdapter::CreateLoraAdapter(const std::basic_string<ORTCHAR_T>& adapter_path,
                                                  OrtAllocator* allocator) {
  OrtLoraAdapter* p;
  ThrowOnError(GetApi().CreateLoraAdapter(adapter_path.c_str(), allocator, &p));
  return LoraAdapter{p};
}
 
inline LoraAdapter LoraAdapter::CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes,
                                                           OrtAllocator* allocator) {
  OrtLoraAdapter* p;
  ThrowOnError(GetApi().CreateLoraAdapterFromArray(bytes, num_bytes, allocator, &p));
  return LoraAdapter{p};
}
 
inline RunOptions::RunOptions() {
  ThrowOnError(GetApi().CreateRunOptions(&p_));
}
 
inline RunOptions& RunOptions::SetRunLogVerbosityLevel(int level) {
  ThrowOnError(GetApi().RunOptionsSetRunLogVerbosityLevel(p_, level));
  return *this;
}
 
inline RunOptions& RunOptions::SetRunLogSeverityLevel(int level) {
  ThrowOnError(GetApi().RunOptionsSetRunLogSeverityLevel(p_, level));
  return *this;
}
 
inline int RunOptions::GetRunLogVerbosityLevel() const {
  int out;
  ThrowOnError(GetApi().RunOptionsGetRunLogVerbosityLevel(p_, &out));
  return out;
}
 
inline int RunOptions::GetRunLogSeverityLevel() const {
  int out;
  ThrowOnError(GetApi().RunOptionsGetRunLogSeverityLevel(p_, &out));
  return out;
}
 
inline RunOptions& RunOptions::SetRunTag(const char* run_tag) {
  ThrowOnError(GetApi().RunOptionsSetRunTag(p_, run_tag));
  return *this;
}
 
inline const char* RunOptions::GetRunTag() const {
  const char* out;
  ThrowOnError(GetApi().RunOptionsGetRunTag(p_, &out));
  return out;
}
 
inline RunOptions& RunOptions::AddConfigEntry(const char* config_key, const char* config_value) {
  ThrowOnError(GetApi().AddRunConfigEntry(p_, config_key, config_value));
  return *this;
}
 
inline const char* RunOptions::GetConfigEntry(const char* config_key) {
  return GetApi().GetRunConfigEntry(p_, config_key);
}
 
inline RunOptions& RunOptions::SetTerminate() {
  ThrowOnError(GetApi().RunOptionsSetTerminate(p_));
  return *this;
}
 
inline RunOptions& RunOptions::UnsetTerminate() {
  ThrowOnError(GetApi().RunOptionsUnsetTerminate(p_));
  return *this;
}
 
inline RunOptions& RunOptions::AddActiveLoraAdapter(const LoraAdapter& adapter) {
  ThrowOnError(GetApi().RunOptionsAddActiveLoraAdapter(p_, adapter));
  return *this;
}
 
inline RunOptions& RunOptions::SetSyncStream(OrtSyncStream* stream) {
  GetApi().RunOptionsSetSyncStream(p_, stream);
  return *this;
}
 
inline RunOptions& RunOptions::EnableProfiling(const ORTCHAR_T* profile_file_prefix) {
  ThrowOnError(GetApi().RunOptionsEnableProfiling(p_, profile_file_prefix));
  return *this;
}
 
inline RunOptions& RunOptions::DisableProfiling() {
  ThrowOnError(GetApi().RunOptionsDisableProfiling(p_));
  return *this;
}
 
inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, const SessionOptions& session_options) {
  ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_));
}
 
inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, ConstSessionOptions session_options) {
  ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_));
}
 
inline Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options) {
  return Ort::Status(GetCompileApi().CompileModel(env, model_compilation_options));
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelPath(
    const ORTCHAR_T* input_model_path) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelPath(this->p_, input_model_path));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelFromBuffer(
    const void* input_model_data, size_t input_model_data_size) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelFromBuffer(this->p_, input_model_data,
                                                                                    input_model_data_size));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelPath(
    const ORTCHAR_T* output_model_path) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelPath(this->p_, output_model_path));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetEpContextBinaryInformation(
    const ORTCHAR_T* output_directory, const ORTCHAR_T* model_name) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetEpContextBinaryInformation(
      this->p_,
      output_directory,
      model_name));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelExternalInitializersFile(
    const ORTCHAR_T* file_path, size_t initializer_size_threshold) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelExternalInitializersFile(
      this->p_,
      file_path,
      initializer_size_threshold));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelExternalInitializersBuffer(
    const ORTCHAR_T* logical_file_name, size_t initializer_size_threshold, OrtAllocator* allocator,
    void** output_buffer_ptr, size_t* output_buffer_size_ptr) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelExternalInitializersBuffer(
      this->p_, logical_file_name, initializer_size_threshold, allocator, output_buffer_ptr, output_buffer_size_ptr));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelExternalInitializersAlignment(
    size_t alignment, size_t minimum_size) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelExternalInitializersAlignment(
      this->p_, alignment, minimum_size));
  return *this;
}
 
inline ModelCompilationOptions&
ModelCompilationOptions::SetOutputModelGetInitializerLocationFunc(
    OrtGetInitializerLocationFunc get_initializer_location_func, void* state) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelGetInitializerLocationFunc(
      this->p_,
      get_initializer_location_func,
      state));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelBuffer(
    OrtAllocator* allocator, void** output_model_buffer_ptr, size_t* output_model_buffer_size_ptr) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelBuffer(this->p_, allocator,
                                                                                 output_model_buffer_ptr,
                                                                                 output_model_buffer_size_ptr));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelWriteFunc(OrtWriteBufferFunc write_func,
                                                                                 void* state) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelWriteFunc(this->p_, write_func, state));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetEpContextDataWriteFunc(
    OrtWriteNamedBufferFunc write_func, void* state) {
  Ort::ThrowOnError(
      GetCompileApi().ModelCompilationOptions_SetEpContextDataWriteFunc(this->p_, write_func, state));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetEpContextEmbedMode(
    bool embed_ep_context_in_model) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetEpContextEmbedMode(
      this->p_,
      embed_ep_context_in_model));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetFlags(uint32_t flags) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetFlags(this->p_, flags));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetGraphOptimizationLevel(
    GraphOptimizationLevel graph_optimization_level) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetGraphOptimizationLevel(this->p_,
                                                                                      graph_optimization_level));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetInputModel(const OrtModel* model) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModel(this->p_, model));
  return *this;
}
 
inline ModelCompilationOptions& ModelCompilationOptions::SetWeightlessEnabled(bool use_weightless) {
  Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetWeightlessEnabled(this->p_, use_weightless));
  return *this;
}
 
inline ModelPackageOptions::ModelPackageOptions(const Env& env, const SessionOptions& session_options) {
  ThrowOnError(GetModelPackageApi().CreateModelPackageOptionsFromSessionOptions(env, session_options, &this->p_));
}
 
inline ModelPackageOptions::ModelPackageOptions(const Env& env, ConstSessionOptions session_options) {
  ThrowOnError(GetModelPackageApi().CreateModelPackageOptionsFromSessionOptions(env, session_options, &this->p_));
}
 
inline ModelPackageContext::ModelPackageContext(const ORTCHAR_T* package_root) {
  ThrowOnError(GetModelPackageApi().CreateModelPackageContext(package_root, &this->p_));
}
 
inline int64_t ModelPackageContext::GetSchemaVersion() const {
  int64_t version = 0;
  ThrowOnError(GetModelPackageApi().ModelPackage_GetSchemaVersion(this->p_, &version));
  return version;
}
 
inline size_t ModelPackageContext::GetComponentCount() const {
  size_t count = 0;
  ThrowOnError(GetModelPackageApi().ModelPackage_GetComponentCount(this->p_, &count));
  return count;
}
 
inline std::vector<std::string> ModelPackageContext::GetComponentNames() const {
  const char* const* names = nullptr;
  size_t count = 0;
  ThrowOnError(GetModelPackageApi().ModelPackage_GetComponentNames(this->p_, &names, &count));
  std::vector<std::string> result;
  result.reserve(count);
  for (size_t i = 0; i < count; ++i) {
    result.emplace_back(names[i]);
  }
  return result;
}
 
inline size_t ModelPackageContext::GetVariantCount(const char* component_name) const {
  size_t count = 0;
  ThrowOnError(GetModelPackageApi().ModelPackage_GetVariantCount(this->p_, component_name, &count));
  return count;
}
 
inline std::vector<std::string> ModelPackageContext::GetVariantNames(const char* component_name) const {
  const char* const* names = nullptr;
  size_t count = 0;
  ThrowOnError(GetModelPackageApi().ModelPackage_GetVariantNames(this->p_, component_name, &names, &count));
  std::vector<std::string> result;
  result.reserve(count);
  for (size_t i = 0; i < count; ++i) {
    result.emplace_back(names[i]);
  }
  return result;
}
 
inline const char* ModelPackageContext::GetVariantEpName(const char* component_name,
                                                         const char* variant_name) const {
  const char* ep = nullptr;
  ThrowOnError(GetModelPackageApi().ModelPackage_GetVariantEpName(
      this->p_, component_name, variant_name, &ep));
  return ep;
}
 
inline std::string ModelPackageContext::ResolveStringRef(const char* base_dir, const char* input,
                                                         bool must_exist) const {
  const char* path = nullptr;
  ThrowOnError(GetModelPackageApi().ModelPackage_ResolveStringRef(
      this->p_, base_dir, input, must_exist ? 1 : 0, &path));
  return std::string{path};
}
 
inline ModelPackageComponentContext ModelPackageContext::SelectComponent(
    const char* component_name, const ModelPackageOptions& options) const {
  OrtModelPackageComponentContext* out = nullptr;
  ThrowOnError(GetModelPackageApi().SelectComponent(this->p_, component_name, options, &out));
  return ModelPackageComponentContext{out};
}
 
inline std::string ModelPackageComponentContext::GetSelectedVariantName() const {
  const char* name = nullptr;
  ThrowOnError(GetModelPackageApi().ModelPackageComponent_GetSelectedVariantName(this->p_, &name));
  return std::string{name};
}
 
inline std::basic_string<ORTCHAR_T> ModelPackageComponentContext::GetSelectedVariantFolderPath() const {
  const ORTCHAR_T* path = nullptr;
  ThrowOnError(GetModelPackageApi().ModelPackageComponent_GetSelectedVariantFolderPath(this->p_, &path));
  return std::basic_string<ORTCHAR_T>{path};
}
 
inline Session ModelPackageComponentContext::CreateSession(const Env& env) {
  OrtSession* out = nullptr;
  ThrowOnError(GetModelPackageApi().CreateSession(env, this->p_, nullptr, &out));
  return Session{out};
}
 
inline Session ModelPackageComponentContext::CreateSession(const Env& env,
                                                           const SessionOptions& session_options) {
  OrtSession* out = nullptr;
  ThrowOnError(GetModelPackageApi().CreateSession(env, this->p_, session_options, &out));
  return Session{out};
}
 
inline Session ModelPackageComponentContext::CreateSession(const Env& env,
                                                           ConstSessionOptions session_options) {
  OrtSession* out = nullptr;
  ThrowOnError(GetModelPackageApi().CreateSession(env, this->p_, session_options, &out));
  return Session{out};
}
 
inline EpContextConfig::EpContextConfig(const SessionOptions& session_options)
    : EpContextConfig{session_options.GetConst()} {}
 
inline EpContextConfig::EpContextConfig(ConstSessionOptions session_options) {
  ThrowOnError(GetEpApi().SessionOptionsGetEpContextConfig(session_options, &this->p_));
}
 
inline void EpContextConfig::GetReadFunc(OrtReadNamedBufferFunc& read_func, void*& state) const {
  ThrowOnError(GetEpApi().EpContextConfigGetEpContextDataReadFunc(this->p_, &read_func, &state));
}
 
inline void EpContextConfig::GetWriteFunc(OrtWriteNamedBufferFunc& write_func, void*& state) const {
  ThrowOnError(GetEpApi().EpContextConfigGetEpContextDataWriteFunc(this->p_, &write_func, &state));
}
 
namespace detail {
 
template <typename T>
inline Ort::SessionOptions ConstSessionOptionsImpl<T>::Clone() const {
  OrtSessionOptions* out;
  ThrowOnError(GetApi().CloneSessionOptions(this->p_, &out));
  return SessionOptions{out};
}
 
template <typename T>
inline std::string ConstSessionOptionsImpl<T>::GetConfigEntry(const char* config_key) const {
  size_t size = 0;
  // Feed nullptr for the data buffer to query the true size of the string value
  Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, nullptr, &size));
 
  std::string out;
  out.resize(size);
  Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, &out[0], &size));
  out.resize(size - 1);  // remove the terminating character '\0'
 
  return out;
}
 
template <typename T>
inline bool ConstSessionOptionsImpl<T>::HasConfigEntry(const char* config_key) const {
  int out = 0;
  Ort::ThrowOnError(GetApi().HasSessionConfigEntry(this->p_, config_key, &out));
  return static_cast<bool>(out);
}
 
template <typename T>
inline std::string ConstSessionOptionsImpl<T>::GetConfigEntryOrDefault(const char* config_key,
                                                                       const std::string& def) const {
  if (!this->HasConfigEntry(config_key)) {
    return def;
  }
 
  return this->GetConfigEntry(config_key);
}
 
template <typename T>
inline bool ConstSessionOptionsImpl<T>::GetMemPatternEnabled() const {
  int out = 0;
  ThrowOnError(GetApi().GetMemPatternEnabled(this->p_, &out));
  return out != 0;
}
 
template <typename T>
inline ExecutionMode ConstSessionOptionsImpl<T>::GetExecutionMode() const {
  ExecutionMode out{};
  ThrowOnError(GetApi().GetSessionExecutionMode(this->p_, &out));
  return out;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetIntraOpNumThreads(int intra_op_num_threads) {
  ThrowOnError(GetApi().SetIntraOpNumThreads(this->p_, intra_op_num_threads));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetInterOpNumThreads(int inter_op_num_threads) {
  ThrowOnError(GetApi().SetInterOpNumThreads(this->p_, inter_op_num_threads));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level) {
  ThrowOnError(GetApi().SetSessionGraphOptimizationLevel(this->p_, graph_optimization_level));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetDeterministicCompute(bool value) {
  ThrowOnError(GetApi().SetDeterministicCompute(this->p_, value));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_filepath) {
  ThrowOnError(GetApi().SetOptimizedModelFilePath(this->p_, optimized_model_filepath));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableProfiling(const ORTCHAR_T* profile_file_prefix) {
  ThrowOnError(GetApi().EnableProfiling(this->p_, profile_file_prefix));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisableProfiling() {
  ThrowOnError(GetApi().DisableProfiling(this->p_));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableOrtCustomOps() {
  ThrowOnError(GetApi().EnableOrtCustomOps(this->p_));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableMemPattern() {
  ThrowOnError(GetApi().EnableMemPattern(this->p_));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisableMemPattern() {
  ThrowOnError(GetApi().DisableMemPattern(this->p_));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::EnableCpuMemArena() {
  ThrowOnError(GetApi().EnableCpuMemArena(this->p_));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisableCpuMemArena() {
  ThrowOnError(GetApi().DisableCpuMemArena(this->p_));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetExecutionMode(ExecutionMode execution_mode) {
  ThrowOnError(GetApi().SetSessionExecutionMode(this->p_, execution_mode));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetLoadCancellationFlag(bool value) {
  ThrowOnError(GetApi().SessionOptionsSetLoadCancellationFlag(this->p_, value));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetLogId(const char* logid) {
  ThrowOnError(GetApi().SetSessionLogId(this->p_, logid));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetLogSeverityLevel(int level) {
  ThrowOnError(GetApi().SetSessionLogSeverityLevel(this->p_, level));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::Add(OrtCustomOpDomain* custom_op_domain) {
  ThrowOnError(GetApi().AddCustomOpDomain(this->p_, custom_op_domain));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddConfigEntry(const char* config_key, const char* config_value) {
  ThrowOnError(GetApi().AddSessionConfigEntry(this->p_, config_key, config_value));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetEpContextDataReadFunc(
    OrtReadNamedBufferFunc read_func, void* state) {
  ThrowOnError(GetApi().SessionOptionsSetEpContextDataReadFunc(this->p_, read_func, state));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::ClearEpContextDataReadFunc() {
  ThrowOnError(GetApi().SessionOptionsSetEpContextDataReadFunc(this->p_, nullptr, nullptr));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddInitializer(const char* name, const OrtValue* ort_val) {
  ThrowOnError(GetApi().AddInitializer(this->p_, name, ort_val));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::DisablePerSessionThreads() {
  ThrowOnError(GetApi().DisablePerSessionThreads(this->p_));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddExternalInitializers(const std::vector<std::string>& names,
                                                                             const std::vector<Value>& ort_values) {
  const size_t inputs_num = names.size();
  if (inputs_num != ort_values.size()) {
    ORT_CXX_API_THROW("Expecting names and ort_values to have the same length", ORT_INVALID_ARGUMENT);
  }
  std::vector<const char*> names_ptr;
  std::vector<const OrtValue*> ort_values_ptrs;
  names_ptr.reserve(inputs_num);
  ort_values_ptrs.reserve(inputs_num);
  for (size_t i = 0; i < inputs_num; ++i) {
    names_ptr.push_back(names[i].c_str());
    ort_values_ptrs.push_back(ort_values[i]);
  }
  ThrowOnError(GetApi().AddExternalInitializers(this->p_, names_ptr.data(), ort_values_ptrs.data(), inputs_num));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddExternalInitializersFromFilesInMemory(const std::vector<std::basic_string<ORTCHAR_T>>& file_names,
                                                                                              const std::vector<char*>& buffer_array,
                                                                                              const std::vector<size_t>& file_lengths) {
  const size_t inputs_num = file_names.size();
  if (inputs_num != buffer_array.size()) {
    ORT_CXX_API_THROW("Expecting names and buffer_array to have the same length", ORT_INVALID_ARGUMENT);
  }
  if (inputs_num != file_lengths.size()) {
    ORT_CXX_API_THROW("Expecting names and file_lengths to have the same length", ORT_INVALID_ARGUMENT);
  }
  std::vector<const ORTCHAR_T*> names_ptr;
  names_ptr.reserve(inputs_num);
  for (size_t i = 0; i < inputs_num; ++i) {
    names_ptr.push_back(file_names[i].c_str());
  }
  ThrowOnError(GetApi().AddExternalInitializersFromFilesInMemory(this->p_, names_ptr.data(), buffer_array.data(),
                                                                 file_lengths.data(), inputs_num));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CPU(int use_arena) {
  ThrowOnError(OrtSessionOptionsAppendExecutionProvider_CPU(this->p_, use_arena));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options) {
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA(this->p_, &provider_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options) {
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA_V2(this->p_, &provider_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options) {
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_ROCM(this->p_, &provider_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options) {
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT(this->p_, &provider_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options) {
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT_V2(this->p_, &provider_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options) {
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_MIGraphX(this->p_, &provider_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options) {
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CANN(this->p_, &provider_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options) {
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_Dnnl(this->p_, &provider_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider(
    const std::string& provider_name,
    const std::unordered_map<std::string, std::string>& provider_options) {
  auto num_entries = provider_options.size();
  std::vector<const char*> keys, values;
  if (num_entries > 0) {
    keys.reserve(num_entries);
    values.reserve(num_entries);
 
    for (const auto& entry : provider_options) {
      keys.push_back(entry.first.c_str());
      values.push_back(entry.second.c_str());
    }
  }
 
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider(this->p_, provider_name.c_str(),
                                                              keys.data(), values.data(), num_entries));
 
  return *this;
}
 
namespace {
template <typename T>
void SessionOptionsAppendEP(detail::SessionOptionsImpl<T>& session_options,
                            Env& env, const std::vector<ConstEpDevice>& ep_devices,
                            const std::vector<const char*>& ep_options_keys,
                            const std::vector<const char*>& ep_options_values) {
  std::vector<const OrtEpDevice*> ep_devices_ptrs;
  ep_devices_ptrs.reserve(ep_devices.size());
  for (const auto& ep_device : ep_devices) {
    ep_devices_ptrs.push_back(ep_device);
  }
 
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_V2(
      session_options, env, ep_devices_ptrs.data(), ep_devices_ptrs.size(),
      ep_options_keys.data(), ep_options_values.data(), ep_options_keys.size()));
}
}  // namespace
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_V2(
    Env& env, const std::vector<ConstEpDevice>& ep_devices, const KeyValuePairs& ep_options) {
  std::vector<const char*> ep_options_keys, ep_options_values;
  ep_options.GetKeyValuePairs(ep_options_keys, ep_options_values);
 
  SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values);
 
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_V2(
    Env& env, const std::vector<ConstEpDevice>& ep_devices,
    const std::unordered_map<std::string, std::string>& ep_options) {
  std::vector<const char*> ep_options_keys, ep_options_values;
  ep_options_keys.reserve(ep_options.size());
  ep_options_values.reserve(ep_options.size());
 
  for (const auto& [key, value] : ep_options) {
    ep_options_keys.push_back(key.c_str());
    ep_options_values.push_back(value.c_str());
  }
 
  SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values);
 
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy) {
  ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicy(this->p_, policy));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state) {
  ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicyDelegate(this->p_, delegate, state));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) {
  ThrowOnError(GetApi().SessionOptionsSetCustomCreateThreadFn(this->p_, ort_custom_create_thread_fn));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options) {
  ThrowOnError(GetApi().SessionOptionsSetCustomThreadCreationOptions(this->p_, ort_custom_thread_creation_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) {
  ThrowOnError(GetApi().SessionOptionsSetCustomJoinThreadFn(this->p_, ort_custom_join_thread_fn));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options) {
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO(this->p_, &provider_options));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_OpenVINO_V2(const std::unordered_map<std::string, std::string>& provider_options) {
  auto num_entries = provider_options.size();
  std::vector<const char*> keys, values;
  if (num_entries > 0) {
    keys.reserve(num_entries);
    values.reserve(num_entries);
 
    for (const auto& entry : provider_options) {
      keys.push_back(entry.first.c_str());
      values.push_back(entry.second.c_str());
    }
  }
 
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO_V2(this->p_,
                                                                          keys.data(), values.data(), num_entries));
 
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AppendExecutionProvider_VitisAI(const std::unordered_map<std::string, std::string>& provider_options) {
  auto num_entries = provider_options.size();
  std::vector<const char*> keys, values;
  if (num_entries > 0) {
    keys.reserve(num_entries);
    values.reserve(num_entries);
 
    for (const auto& entry : provider_options) {
      keys.push_back(entry.first.c_str());
      values.push_back(entry.second.c_str());
    }
  }
 
  ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_VitisAI(this->p_, keys.data(), values.data(), num_entries));
 
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::RegisterCustomOpsLibrary(const ORTCHAR_T* library_name,
                                                                              const CustomOpConfigs& custom_op_configs) {
  // Add custom op config entries before registering the custom op library. Otherwise, the config entries _may_ be ignored by
  // the custom op library.
  for (const auto& config_iter : custom_op_configs.GetFlattenedConfigs()) {
    AddConfigEntry(config_iter.first.c_str(), config_iter.second.c_str());
  }
 
  ThrowOnError(GetApi().RegisterCustomOpsLibrary_V2(this->p_, library_name));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::RegisterCustomOpsUsingFunction(const char* registration_function_name) {
  ThrowOnError(GetApi().RegisterCustomOpsUsingFunction(this->p_, registration_function_name));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddFreeDimensionOverride(const char* dim_denotation, int64_t dim_value) {
  ThrowOnError(GetApi().AddFreeDimensionOverrideByName(this->p_, dim_denotation, dim_value));
  return *this;
}
 
template <typename T>
inline SessionOptionsImpl<T>& SessionOptionsImpl<T>::AddFreeDimensionOverrideByName(const char* dim_name, int64_t dim_value) {
  ThrowOnError(GetApi().AddFreeDimensionOverrideByName(this->p_, dim_name, dim_value));
  return *this;
}
 
/// Session
template <typename T>
inline size_t ConstSessionImpl<T>::GetInputCount() const {
  size_t out;
  ThrowOnError(GetApi().SessionGetInputCount(this->p_, &out));
  return out;
}
 
template <typename T>
inline size_t ConstSessionImpl<T>::GetOutputCount() const {
  size_t out;
  ThrowOnError(GetApi().SessionGetOutputCount(this->p_, &out));
  return out;
}
 
template <typename T>
inline size_t ConstSessionImpl<T>::GetOverridableInitializerCount() const {
  size_t out;
  ThrowOnError(GetApi().SessionGetOverridableInitializerCount(this->p_, &out));
  return out;
}
 
template <typename T>
inline std::vector<std::string> ConstSessionImpl<T>::GetInputNames() const {
  AllocatorWithDefaultOptions allocator;
 
  auto num_inputs = GetInputCount();
  std::vector<std::string> input_names;
  input_names.reserve(num_inputs);
 
  for (size_t i = 0; i < num_inputs; ++i) {
    char* name;
    ThrowOnError(GetApi().SessionGetInputName(this->p_, i, allocator, &name));
    input_names.emplace_back(name);
    allocator.Free(name);
  }
 
  return input_names;
}
 
template <typename T>
inline std::vector<std::string> ConstSessionImpl<T>::GetOutputNames() const {
  AllocatorWithDefaultOptions allocator;
 
  auto num_inputs = GetOutputCount();
  std::vector<std::string> output_names;
  output_names.reserve(num_inputs);
 
  for (size_t i = 0; i < num_inputs; ++i) {
    char* name;
    ThrowOnError(GetApi().SessionGetOutputName(this->p_, i, allocator, &name));
    output_names.emplace_back(name);
    allocator.Free(name);
  }
 
  return output_names;
}
 
template <typename T>
inline std::vector<std::string> ConstSessionImpl<T>::GetOverridableInitializerNames() const {
  AllocatorWithDefaultOptions allocator;
 
  auto num_initializers = GetOverridableInitializerCount();
  std::vector<std::string> initializer_names;
  initializer_names.reserve(num_initializers);
 
  for (size_t i = 0; i < num_initializers; ++i) {
    char* name;
    ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, i, allocator, &name));
    initializer_names.emplace_back(name);
    allocator.Free(name);
  }
 
  return initializer_names;
}
 
template <typename T>
inline std::vector<ConstMemoryInfo> ConstSessionImpl<T>::GetMemoryInfoForInputs() const {
  static_assert(sizeof(ConstMemoryInfo) == sizeof(OrtMemoryInfo*),
                "ConstMemoryInfo must be compatible with OrtMemoryInfo*");
 
  auto num_inputs = GetInputCount();
  std::vector<ConstMemoryInfo> mem_infos;
  if (num_inputs > 0) {
    mem_infos.resize(num_inputs);
 
    ThrowOnError(GetApi().SessionGetMemoryInfoForInputs(this->p_,
                                                        reinterpret_cast<const OrtMemoryInfo**>(mem_infos.data()),
                                                        num_inputs));
  }
 
  return mem_infos;
}
 
template <typename T>
inline std::vector<ConstMemoryInfo> ConstSessionImpl<T>::GetMemoryInfoForOutputs() const {
  static_assert(sizeof(ConstMemoryInfo) == sizeof(OrtMemoryInfo*),
                "ConstMemoryInfo must be compatible with OrtMemoryInfo*");
 
  auto num_outputs = GetOutputCount();
  std::vector<ConstMemoryInfo> mem_infos;
  if (num_outputs > 0) {
    mem_infos.resize(num_outputs);
 
    ThrowOnError(GetApi().SessionGetMemoryInfoForOutputs(this->p_,
                                                         reinterpret_cast<const OrtMemoryInfo**>(mem_infos.data()),
                                                         num_outputs));
  }
  return mem_infos;
}
 
template <typename T>
inline AllocatedStringPtr ConstSessionImpl<T>::GetInputNameAllocated(size_t index, OrtAllocator* allocator) const {
  char* out;
  ThrowOnError(GetApi().SessionGetInputName(this->p_, index, allocator, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
template <typename T>
inline AllocatedStringPtr ConstSessionImpl<T>::GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const {
  char* out;
  ThrowOnError(GetApi().SessionGetOutputName(this->p_, index, allocator, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
template <typename T>
inline AllocatedStringPtr ConstSessionImpl<T>::GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const {
  char* out;
  ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, index, allocator, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
template <typename T>
inline std::vector<ConstEpDevice> ConstSessionImpl<T>::GetEpDeviceForInputs() const {
  auto num_inputs = GetInputCount();
  std::vector<ConstEpDevice> input_devices;
  if (num_inputs > 0) {
    input_devices.resize(num_inputs);
    ThrowOnError(GetApi().SessionGetEpDeviceForInputs(this->p_,
                                                      reinterpret_cast<const OrtEpDevice**>(input_devices.data()),
                                                      num_inputs));
  }
  return input_devices;
}
 
template <typename T>
inline std::vector<ConstEpDevice> ConstSessionImpl<T>::GetEpDeviceForOutputs() const {
  auto num_outputs = GetOutputCount();
  std::vector<ConstEpDevice> output_devices;
  if (num_outputs > 0) {
    output_devices.resize(num_outputs);
    ThrowOnError(GetApi().SessionGetEpDeviceForOutputs(this->p_,
                                                       reinterpret_cast<const OrtEpDevice**>(output_devices.data()),
                                                       num_outputs));
  }
  return output_devices;
}
 
template <typename T>
inline uint64_t ConstSessionImpl<T>::GetProfilingStartTimeNs() const {
  uint64_t out;
  ThrowOnError(GetApi().SessionGetProfilingStartTimeNs(this->p_, &out));
  return out;
}
 
template <typename T>
inline ModelMetadata ConstSessionImpl<T>::GetModelMetadata() const {
  OrtModelMetadata* out;
  ThrowOnError(GetApi().SessionGetModelMetadata(this->p_, &out));
  return ModelMetadata{out};
}
 
template <typename T>
inline TypeInfo ConstSessionImpl<T>::GetInputTypeInfo(size_t index) const {
  OrtTypeInfo* out;
  ThrowOnError(GetApi().SessionGetInputTypeInfo(this->p_, index, &out));
  return TypeInfo{out};
}
 
template <typename T>
inline TypeInfo ConstSessionImpl<T>::GetOutputTypeInfo(size_t index) const {
  OrtTypeInfo* out;
  ThrowOnError(GetApi().SessionGetOutputTypeInfo(this->p_, index, &out));
  return TypeInfo{out};
}
 
template <typename T>
inline TypeInfo ConstSessionImpl<T>::GetOverridableInitializerTypeInfo(size_t index) const {
  OrtTypeInfo* out;
  ThrowOnError(GetApi().SessionGetOverridableInitializerTypeInfo(this->p_, index, &out));
  return TypeInfo{out};
}
 
#if !defined(ORT_MINIMAL_BUILD)
template <typename T>
inline int ConstSessionImpl<T>::GetOpset(const std::string& domain) const {
  int opset;
  ThrowOnError(GetModelEditorApi().SessionGetOpsetForDomain(this->p_, domain.c_str(), &opset));
  return opset;
}
#endif  // !defined(ORT_MINIMAL_BUILD)
 
template <typename T>
std::vector<ValueInfo> ConstSessionImpl<T>::GetInputs() const {
  const std::vector<std::string> input_names = GetInputNames();
 
  std::vector<ValueInfo> inputs;
  inputs.reserve(input_names.size());
 
  for (size_t i = 0; i < input_names.size(); ++i) {
    auto type_info = GetInputTypeInfo(i);
    inputs.emplace_back(ValueInfo{input_names[i], type_info.GetConst()});
  }
 
  return inputs;
}
 
template <typename T>
std::vector<ValueInfo> ConstSessionImpl<T>::GetOutputs() const {
  const std::vector<std::string> output_names = GetOutputNames();
 
  std::vector<ValueInfo> outputs;
  outputs.reserve(output_names.size());
 
  for (size_t i = 0; i < output_names.size(); ++i) {
    auto type_info = GetOutputTypeInfo(i);
    outputs.emplace_back(ValueInfo{output_names[i], type_info.GetConst()});
  }
 
  return outputs;
}
 
template <typename T>
inline std::vector<ConstEpAssignedSubgraph> ConstSessionImpl<T>::GetEpGraphAssignmentInfo() const {
  size_t num_ep_subgraphs = 0;
  const OrtEpAssignedSubgraph* const* ep_subgraph_ptrs = nullptr;
  ThrowOnError(GetApi().Session_GetEpGraphAssignmentInfo(this->p_, &ep_subgraph_ptrs, &num_ep_subgraphs));
 
  std::vector<ConstEpAssignedSubgraph> ep_subgraphs;
  if (num_ep_subgraphs > 0) {
    ep_subgraphs.reserve(num_ep_subgraphs);
    for (size_t i = 0; i < num_ep_subgraphs; ++i) {
      ep_subgraphs.emplace_back(ep_subgraph_ptrs[i]);
    }
  }
 
  return ep_subgraphs;
}
 
template <typename T>
inline std::vector<Value> SessionImpl<T>::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
                                              const char* const* output_names, size_t output_count) {
  std::vector<Value> output_values;
  output_values.reserve(output_count);
  for (size_t i = 0; i < output_count; i++)
    output_values.emplace_back(nullptr);
  Run(run_options, input_names, input_values, input_count, output_names, output_values.data(), output_count);
  return output_values;
}
 
template <typename T>
inline void SessionImpl<T>::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
                                const char* const* output_names, Value* output_values, size_t output_count) {
  static_assert(sizeof(Value) == sizeof(OrtValue*), "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely");
  auto ort_input_values = reinterpret_cast<const OrtValue* const*>(input_values);
  auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
  ThrowOnError(GetApi().Run(this->p_, run_options, input_names, ort_input_values, input_count, output_names, output_count, ort_output_values));
}
 
template <typename T>
inline void SessionImpl<T>::Run(const RunOptions& run_options, const IoBinding& io_binding) {
  ThrowOnError(GetApi().RunWithBinding(this->p_, run_options, io_binding));
}
 
template <typename T>
inline void SessionImpl<T>::RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count,
                                     const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data) {
  auto ort_input_values = reinterpret_cast<const OrtValue* const*>(input_values);
  auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
  ThrowOnError(GetApi().RunAsync(this->p_, run_options, input_names,
                                 ort_input_values, input_count, output_names, output_count,
                                 ort_output_values, callback, user_data));
}
 
template <typename T>
inline AllocatedStringPtr SessionImpl<T>::EndProfilingAllocated(OrtAllocator* allocator) {
  char* out = nullptr;
  ThrowOnError(GetApi().SessionEndProfiling(this->p_, allocator, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
template <typename T>
inline void SessionImpl<T>::SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len) {
  ThrowOnError(GetApi().SetEpDynamicOptions(this->p_, keys, values, kv_len));
}
 
#if !defined(ORT_MINIMAL_BUILD)
template <typename T>
inline void SessionImpl<T>::FinalizeModelEditorSession(const Model& model, const SessionOptions& options,
                                                       OrtPrepackedWeightsContainer* prepacked_weights_container) {
  ThrowOnError(GetModelEditorApi().ApplyModelToModelEditorSession(this->p_, model));
  ThrowOnError(GetModelEditorApi().FinalizeModelEditorSession(this->p_, options, prepacked_weights_container));
}
#endif  // #if !defined(ORT_MINIMAL_BUILD)
 
template <typename T>
inline void SessionImpl<T>::ReleaseCapturedGraph(int graph_annotation_id) {
  ThrowOnError(GetApi().SessionReleaseCapturedGraph(this->p_, graph_annotation_id));
}
 
}  // namespace detail
 
inline SessionOptions::SessionOptions() {
  ThrowOnError(GetApi().CreateSessionOptions(&this->p_));
}
 
/// CustomOpConfigs
inline std::string detail::MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config) {
  std::string config_key = "custom_op.";
 
  config_key += custom_op_name;
  config_key += ".";
  config_key += config;
 
  return config_key;
}
 
inline CustomOpConfigs& CustomOpConfigs::AddConfig(const char* custom_op_name, const char* config_key, const char* config_value) {
  const std::string full_flat_key = detail::MakeCustomOpConfigEntryKey(custom_op_name, config_key);
  flat_configs_[full_flat_key] = config_value;
  return *this;
}
 
inline const std::unordered_map<std::string, std::string>& CustomOpConfigs::GetFlattenedConfigs() const {
  return flat_configs_;
}
 
inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options) {
  ThrowOnError(GetApi().CreateSession(env, model_path, options, &this->p_));
}
 
inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options,
                        OrtPrepackedWeightsContainer* prepacked_weights_container) {
  ThrowOnError(GetApi().CreateSessionWithPrepackedWeightsContainer(env, model_path, options, prepacked_weights_container, &this->p_));
}
 
inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options) {
  ThrowOnError(GetApi().CreateSessionFromArray(env, model_data, model_data_length, options, &this->p_));
}
 
inline Session::Session(const Env& env, const void* model_data, size_t model_data_length,
                        const SessionOptions& options, OrtPrepackedWeightsContainer* prepacked_weights_container) {
  ThrowOnError(GetApi().CreateSessionFromArrayWithPrepackedWeightsContainer(env, model_data, model_data_length, options,
                                                                            prepacked_weights_container, &this->p_));
}
 
#if !defined(ORT_MINIMAL_BUILD)
inline Session::Session(const Env& env, const Model& model, const SessionOptions& options) {
  ThrowOnError(GetModelEditorApi().CreateSessionFromModel(env, model, options, &this->p_));
}
 
// static
inline Session Session::CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path,
                                                 const SessionOptions& options) {
  OrtSession* session = nullptr;
  ThrowOnError(GetModelEditorApi().CreateModelEditorSession(env, model_path, options, &session));
  return Session(session);
}
 
// static
inline Session Session::CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length,
                                                 const SessionOptions& options) {
  OrtSession* session = nullptr;
  ThrowOnError(GetModelEditorApi().CreateModelEditorSessionFromArray(env, model_data, model_data_length, options,
                                                                     &session));
  return Session(session);
}
 
void FinalizeModelEditorSession(const Model& model, const SessionOptions& options,
                                OrtPrepackedWeightsContainer* prepacked_weights_container);
#endif  // #if !defined(ORT_MINIMAL_BUILD)
 
inline AllocatedStringPtr ModelMetadata::GetProducerNameAllocated(OrtAllocator* allocator) const {
  char* out;
  ThrowOnError(GetApi().ModelMetadataGetProducerName(p_, allocator, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
inline AllocatedStringPtr ModelMetadata::GetGraphNameAllocated(OrtAllocator* allocator) const {
  char* out;
  ThrowOnError(GetApi().ModelMetadataGetGraphName(p_, allocator, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
inline AllocatedStringPtr ModelMetadata::GetDomainAllocated(OrtAllocator* allocator) const {
  char* out;
  ThrowOnError(GetApi().ModelMetadataGetDomain(p_, allocator, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
inline AllocatedStringPtr Ort::ModelMetadata::GetDescriptionAllocated(OrtAllocator* allocator) const {
  char* out;
  ThrowOnError(GetApi().ModelMetadataGetDescription(p_, allocator, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
inline AllocatedStringPtr ModelMetadata::GetGraphDescriptionAllocated(OrtAllocator* allocator) const {
  char* out;
  ThrowOnError(GetApi().ModelMetadataGetGraphDescription(p_, allocator, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
inline AllocatedStringPtr ModelMetadata::LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const {
  char* out;
  ThrowOnError(GetApi().ModelMetadataLookupCustomMetadataMap(p_, allocator, key, &out));
  return AllocatedStringPtr(out, detail::AllocatedFree(allocator));
}
 
inline std::vector<AllocatedStringPtr> ModelMetadata::GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const {
  auto deletor = detail::AllocatedFree(allocator);
  std::vector<AllocatedStringPtr> result;
 
  char** out = nullptr;
  int64_t num_keys = 0;
  ThrowOnError(GetApi().ModelMetadataGetCustomMetadataMapKeys(p_, allocator, &out, &num_keys));
  if (num_keys <= 0) {
    return result;
  }
 
  // array of pointers will be freed
  std::unique_ptr<void, decltype(deletor)> array_guard(out, deletor);
  // reserve may throw
  auto strings_deletor = [&deletor, num_keys](char** out) { for(int64_t i = 0; i < num_keys; ++i) deletor(out[i]); };
  std::unique_ptr<char*, decltype(strings_deletor)> strings_guard(out, strings_deletor);
  result.reserve(static_cast<size_t>(num_keys));
  strings_guard.release();
  for (int64_t i = 0; i < num_keys; ++i) {
    result.push_back(AllocatedStringPtr(out[i], deletor));
  }
 
  return result;
}
 
inline int64_t ModelMetadata::GetVersion() const {
  int64_t out;
  ThrowOnError(GetApi().ModelMetadataGetVersion(p_, &out));
  return out;
}
 
inline TensorTypeAndShapeInfo::TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type,
                                                      const std::vector<int64_t>& dims,
                                                      const std::vector<std::string>* symbolic_dims) {
  ThrowOnError(GetApi().CreateTensorTypeAndShapeInfo(&p_));
  ThrowOnError(GetApi().SetTensorElementType(p_, element_type));
  ThrowOnError(GetApi().SetDimensions(p_, dims.data(), dims.size()));
 
  if (symbolic_dims) {
    std::vector<const char*> symbolic_dims_cstr;
    symbolic_dims_cstr.reserve(symbolic_dims->size());
    std::transform(symbolic_dims->begin(), symbolic_dims->end(), std::back_inserter(symbolic_dims_cstr),
                   [](const std::string& s) { return s.c_str(); });
    ThrowOnError(GetApi().SetSymbolicDimensions(p_, symbolic_dims_cstr.data(), symbolic_dims_cstr.size()));
  }
}
 
#if !defined(ORT_MINIMAL_BUILD)
// static
inline TypeInfo TypeInfo::CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_type_and_shape_info) {
  OrtTypeInfo* output = nullptr;
  ThrowOnError(GetModelEditorApi().CreateTensorTypeInfo(tensor_type_and_shape_info, &output));
  return TypeInfo{output};
}
 
// static
inline TypeInfo TypeInfo::CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_type_and_shape_info) {
  OrtTypeInfo* output = nullptr;
  ThrowOnError(GetModelEditorApi().CreateSparseTensorTypeInfo(sparse_tensor_type_and_shape_info, &output));
  return TypeInfo{output};
}
 
// static
inline TypeInfo TypeInfo::CreateSequenceTypeInfo(ConstTypeInfo sequence_type) {
  OrtTypeInfo* output;
  ThrowOnError(GetModelEditorApi().CreateSequenceTypeInfo(sequence_type, &output));
  return TypeInfo{output};
}
 
// static
inline TypeInfo TypeInfo::CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type) {
  OrtTypeInfo* output;
  ThrowOnError(GetModelEditorApi().CreateMapTypeInfo(key_type, value_type, &output));
  return TypeInfo{output};
}
 
// static
inline TypeInfo TypeInfo::CreateOptionalTypeInfo(ConstTypeInfo contained_type) {
  OrtTypeInfo* output;
  ThrowOnError(GetModelEditorApi().CreateOptionalTypeInfo(contained_type, &output));
  return TypeInfo{output};
}
#endif  // #if !defined(ORT_MINIMAL_BUILD)
 
namespace detail {
 
template <typename T>
inline ONNXTensorElementDataType TensorTypeAndShapeInfoImpl<T>::GetElementType() const {
  ONNXTensorElementDataType out;
  ThrowOnError(GetApi().GetTensorElementType(this->p_, &out));
  return out;
}
 
template <typename T>
inline size_t TensorTypeAndShapeInfoImpl<T>::GetElementCount() const {
  size_t out;
  ThrowOnError(GetApi().GetTensorShapeElementCount(this->p_, &out));
  return out;
}
 
template <typename T>
inline bool TensorTypeAndShapeInfoImpl<T>::HasShape() const {
  return GetApi().TensorTypeAndShape_HasShape(this->p_);
}
 
template <typename T>
inline size_t TensorTypeAndShapeInfoImpl<T>::GetDimensionsCount() const {
  size_t out;
  ThrowOnError(GetApi().GetDimensionsCount(this->p_, &out));
  return out;
}
 
template <typename T>
inline void TensorTypeAndShapeInfoImpl<T>::GetDimensions(int64_t* values, size_t values_count) const {
  ThrowOnError(GetApi().GetDimensions(this->p_, values, values_count));
}
 
template <typename T>
inline void TensorTypeAndShapeInfoImpl<T>::GetSymbolicDimensions(const char** values, size_t values_count) const {
  ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, values, values_count));
}
 
template <typename T>
inline std::vector<const char*> TensorTypeAndShapeInfoImpl<T>::GetSymbolicDimensions() const {
  std::vector<const char*> out;
  size_t dim_count = GetDimensionsCount();
  if (dim_count > 0) {
    out.resize(dim_count, nullptr);
    ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, out.data(), out.size()));
  }
  return out;
}
 
template <typename T>
inline std::vector<int64_t> TensorTypeAndShapeInfoImpl<T>::GetShape() const {
  std::vector<int64_t> out(GetDimensionsCount(), -1);
  ThrowOnError(GetApi().GetDimensions(this->p_, out.data(), out.size()));
  return out;
}
 
template <typename T>
inline ConstTensorTypeAndShapeInfo TypeInfoImpl<T>::GetTensorTypeAndShapeInfo() const {
  const OrtTensorTypeAndShapeInfo* out;
  ThrowOnError(GetApi().CastTypeInfoToTensorInfo(this->p_, &out));
  return ConstTensorTypeAndShapeInfo{out};
}
 
template <typename T>
inline ConstSequenceTypeInfo TypeInfoImpl<T>::GetSequenceTypeInfo() const {
  const OrtSequenceTypeInfo* out;
  ThrowOnError(GetApi().CastTypeInfoToSequenceTypeInfo(this->p_, &out));
  return ConstSequenceTypeInfo{out};
}
 
template <typename T>
inline ConstMapTypeInfo TypeInfoImpl<T>::GetMapTypeInfo() const {
  const OrtMapTypeInfo* out;
  ThrowOnError(GetApi().CastTypeInfoToMapTypeInfo(this->p_, &out));
  return ConstMapTypeInfo{out};
}
 
template <typename T>
inline ONNXType TypeInfoImpl<T>::GetONNXType() const {
  ONNXType out;
  ThrowOnError(GetApi().GetOnnxTypeFromTypeInfo(this->p_, &out));
  return out;
}
 
template <typename T>
inline TypeInfo SequenceTypeInfoImpl<T>::GetSequenceElementType() const {
  OrtTypeInfo* output;
  ThrowOnError(GetApi().GetSequenceElementType(this->p_, &output));
  return TypeInfo{output};
}
 
template <typename T>
inline TypeInfo OptionalTypeInfoImpl<T>::GetOptionalElementType() const {
  OrtTypeInfo* info;
  ThrowOnError(GetApi().GetOptionalContainedTypeInfo(this->p_, &info));
  return TypeInfo{info};
}
 
template <typename T>
inline ONNXTensorElementDataType MapTypeInfoImpl<T>::GetMapKeyType() const {
  ONNXTensorElementDataType out;
  ThrowOnError(GetApi().GetMapKeyType(this->p_, &out));
  return out;
}
 
template <typename T>
inline TypeInfo MapTypeInfoImpl<T>::GetMapValueType() const {
  OrtTypeInfo* output;
  ThrowOnError(GetApi().GetMapValueType(this->p_, &output));
  return TypeInfo{output};
}
 
template <typename T>
inline ConstOptionalTypeInfo TypeInfoImpl<T>::GetOptionalTypeInfo() const {
  const OrtOptionalTypeInfo* info;
  ThrowOnError(GetApi().CastTypeInfoToOptionalTypeInfo(this->p_, &info));
  return ConstOptionalTypeInfo{info};
}
 
}  // namespace detail
 
namespace detail {
 
template <typename T>
template <typename R>
inline void ConstValueImpl<T>::GetOpaqueData(const char* domain, const char* type_name, R& out) const {
  ThrowOnError(GetApi().GetOpaqueValue(domain, type_name, this->p_, &out, sizeof(R)));
}
 
template <typename T>
inline bool ConstValueImpl<T>::IsTensor() const {
  int out;
  ThrowOnError(GetApi().IsTensor(this->p_, &out));
  return out != 0;
}
 
template <typename T>
inline bool ConstValueImpl<T>::HasValue() const {
  int out;
  ThrowOnError(GetApi().HasValue(this->p_, &out));
  return out != 0;
}
 
template <typename T>
inline size_t ConstValueImpl<T>::GetCount() const {
  size_t out;
  ThrowOnError(GetApi().GetValueCount(this->p_, &out));
  return out;
}
 
template <typename T>
inline Value ConstValueImpl<T>::GetValue(int index, OrtAllocator* allocator) const {
  OrtValue* out;
  ThrowOnError(GetApi().GetValue(this->p_, index, allocator, &out));
  return Value{out};
}
 
template <typename T>
inline size_t ConstValueImpl<T>::GetStringTensorDataLength() const {
  size_t out;
  ThrowOnError(GetApi().GetStringTensorDataLength(this->p_, &out));
  return out;
}
 
template <typename T>
inline size_t ConstValueImpl<T>::GetStringTensorElementLength(size_t element_index) const {
  size_t out;
  ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &out));
  return out;
}
 
template <typename T>
inline size_t ConstValueImpl<T>::GetTensorSizeInBytes() const {
  size_t out;
  ThrowOnError(GetApi().GetTensorSizeInBytes(this->p_, &out));
  return out;
}
 
template <typename T>
template <typename R>
inline const R* ConstValueImpl<T>::GetTensorData() const {
  const R* out;
  ThrowOnError(GetApi().GetTensorData(this->p_, reinterpret_cast<const void**>(&out)));
  return out;
}
 
template <typename T>
inline const void* ConstValueImpl<T>::GetTensorRawData() const {
  const void* out;
  ThrowOnError(GetApi().GetTensorData(this->p_, &out));
  return out;
}
 
template <typename T>
inline TypeInfo ConstValueImpl<T>::GetTypeInfo() const {
  OrtTypeInfo* output;
  ThrowOnError(GetApi().GetTypeInfo(this->p_, &output));
  return TypeInfo{output};
}
 
template <typename T>
inline TensorTypeAndShapeInfo ConstValueImpl<T>::GetTensorTypeAndShapeInfo() const {
  OrtTensorTypeAndShapeInfo* output;
  ThrowOnError(GetApi().GetTensorTypeAndShape(this->p_, &output));
  return TensorTypeAndShapeInfo{output};
}
 
template <typename T>
inline ConstMemoryInfo ConstValueImpl<T>::GetTensorMemoryInfo() const {
  const OrtMemoryInfo* mem_info;
  ThrowOnError(GetApi().GetTensorMemoryInfo(this->p_, &mem_info));
  return ConstMemoryInfo(mem_info);
}
 
template <typename T>
inline void ConstValueImpl<T>::GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const {
  ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, buffer));
}
 
template <typename T>
inline std::string ConstValueImpl<T>::GetStringTensorElement(size_t element_index) const {
  size_t buffer_length;
  ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &buffer_length));
 
  std::string s;
  s.resize(buffer_length);
  ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, &s[0]));
  return s;
}
 
template <typename T>
inline void ConstValueImpl<T>::GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const {
  ThrowOnError(GetApi().GetStringTensorContent(this->p_, buffer, buffer_length, offsets, offsets_count));
}
 
#if !defined(DISABLE_SPARSE_TENSORS)
template <typename T>
inline OrtSparseFormat ConstValueImpl<T>::GetSparseFormat() const {
  OrtSparseFormat format;
  ThrowOnError(GetApi().GetSparseTensorFormat(this->p_, &format));
  return format;
}
 
template <typename T>
inline TensorTypeAndShapeInfo ConstValueImpl<T>::GetSparseTensorValuesTypeAndShapeInfo() const {
  OrtTensorTypeAndShapeInfo* output;
  ThrowOnError(GetApi().GetSparseTensorValuesTypeAndShape(this->p_, &output));
  return TensorTypeAndShapeInfo{output};
}
 
template <typename T>
inline TensorTypeAndShapeInfo ConstValueImpl<T>::GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat indices_format) const {
  OrtTensorTypeAndShapeInfo* output;
  ThrowOnError(GetApi().GetSparseTensorIndicesTypeShape(this->p_, indices_format, &output));
  return TensorTypeAndShapeInfo{output};
}
 
template <typename T>
template <typename R>
inline const R* ConstValueImpl<T>::GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const {
  const void* out;
  ThrowOnError(GetApi().GetSparseTensorIndices(this->p_, indices_format, &num_indices, &out));
  return reinterpret_cast<const R*>(out);
}
 
template <typename T>
inline bool ConstValueImpl<T>::IsSparseTensor() const {
  int out;
  ThrowOnError(GetApi().IsSparseTensor(this->p_, &out));
  return out != 0;
}
 
template <typename T>
template <typename R>
inline const R* ConstValueImpl<T>::GetSparseTensorValues() const {
  const void* out;
  ThrowOnError(GetApi().GetSparseTensorValues(this->p_, &out));
  return reinterpret_cast<const R*>(out);
}
 
#endif
 
template <typename T>
void ConstValueImpl<T>::GetTensorElementTypeAndShapeDataReference(ONNXTensorElementDataType& elem_type,
                                                                  Shape& shape) const {
  ThrowOnError(GetApi().GetTensorElementTypeAndShapeDataReference(this->p_, &elem_type, &shape.shape,
                                                                  &shape.shape_len));
}
 
template <typename T>
void ValueImpl<T>::FillStringTensor(const char* const* s, size_t s_len) {
  ThrowOnError(GetApi().FillStringTensor(this->p_, s, s_len));
}
 
template <typename T>
void ValueImpl<T>::FillStringTensorElement(const char* s, size_t index) {
  ThrowOnError(GetApi().FillStringTensorElement(this->p_, s, index));
}
 
template <typename T>
inline char* ValueImpl<T>::GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length) {
  char* result;
  ThrowOnError(GetApi().GetResizedStringTensorElementBuffer(this->p_, index, buffer_length, &result));
  return result;
}
 
template <typename T>
void* ValueImpl<T>::GetTensorMutableRawData() {
  void* out;
  ThrowOnError(GetApi().GetTensorMutableData(this->p_, &out));
  return out;
}
 
template <typename T>
template <typename R>
R* ValueImpl<T>::GetTensorMutableData() {
  R* out;
  ThrowOnError(GetApi().GetTensorMutableData(this->p_, (void**)&out));
  return out;
}
 
template <typename T>
template <typename R>
R& ValueImpl<T>::At(const std::vector<int64_t>& location) {
  static_assert(!std::is_same<T, std::string>::value, "this api does not support std::string");
  R* out;
  ThrowOnError(GetApi().TensorAt(this->p_, location.data(), location.size(), (void**)&out));
  return *out;
}
 
#if !defined(DISABLE_SPARSE_TENSORS)
template <typename T>
void ValueImpl<T>::UseCooIndices(int64_t* indices_data, size_t indices_num) {
  ThrowOnError(GetApi().UseCooIndices(this->p_, indices_data, indices_num));
}
 
template <typename T>
void ValueImpl<T>::UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num) {
  ThrowOnError(GetApi().UseCsrIndices(this->p_, inner_data, inner_num, outer_data, outer_num));
}
 
template <typename T>
void ValueImpl<T>::UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data) {
  ThrowOnError(GetApi().UseBlockSparseIndices(this->p_, indices_shape.shape, indices_shape.shape_len, indices_data));
}
 
template <typename T>
void ValueImpl<T>::FillSparseTensorCoo(const OrtMemoryInfo* mem_info, const OrtSparseValuesParam& values_param,
                                       const int64_t* indices_data, size_t indices_num) {
  ThrowOnError(GetApi().FillSparseTensorCoo(this->p_, mem_info, values_param.values_shape,
                                            values_param.values_shape_len, values_param.data.p_data,
                                            indices_data, indices_num));
}
 
template <typename T>
void ValueImpl<T>::FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info,
                                       const OrtSparseValuesParam& values,
                                       const int64_t* inner_indices_data, size_t inner_indices_num,
                                       const int64_t* outer_indices_data, size_t outer_indices_num) {
  ThrowOnError(GetApi().FillSparseTensorCsr(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data,
                                            inner_indices_data, inner_indices_num,
                                            outer_indices_data, outer_indices_num));
}
 
template <typename T>
void ValueImpl<T>::FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info,
                                               const OrtSparseValuesParam& values,
                                               const Shape& indices_shape,
                                               const int32_t* indices_data) {
  ThrowOnError(GetApi().FillSparseTensorBlockSparse(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data,
                                                    indices_shape.shape, indices_shape.shape_len,
                                                    indices_data));
}
 
#endif  // !defined(DISABLE_SPARSE_TENSORS)
 
}  // namespace detail
 
template <typename T>
inline Value Value::CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count,
                                 const int64_t* shape, size_t shape_len) {
  return CreateTensor(info, p_data, p_data_element_count * sizeof(T), shape, shape_len, TypeToTensorType<T>::type);
}
 
inline Value Value::CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count,
                                 const int64_t* shape, size_t shape_len,
                                 ONNXTensorElementDataType type) {
  OrtValue* out;
  ThrowOnError(GetApi().CreateTensorWithDataAsOrtValue(info, p_data, p_data_byte_count, shape, shape_len, type, &out));
  return Value{out};
}
 
inline Value Value::CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count,
                                 const int64_t* shape, size_t shape_len,
                                 ONNXTensorElementDataType type) {
  OrtValue* out;
  ThrowOnError(GetApi().CreateTensorWithDataAndDeleterAsOrtValue(deleter, p_data, p_data_byte_count,
                                                                 shape, shape_len, type, &out));
  return Value{out};
}
 
template <typename T>
inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len) {
  return CreateTensor(allocator, shape, shape_len, TypeToTensorType<T>::type);
}
 
inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len,
                                 ONNXTensorElementDataType type) {
  OrtValue* out;
  ThrowOnError(GetApi().CreateTensorAsOrtValue(allocator, shape, shape_len, type, &out));
  return Value{out};
}
 
#if !defined(DISABLE_SPARSE_TENSORS)
 
template <typename T>
inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape,
                                       const Shape& values_shape) {
  return CreateSparseTensor(info, p_data, dense_shape, values_shape, TypeToTensorType<T>::type);
}
 
inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape,
                                       const Shape& values_shape, ONNXTensorElementDataType type) {
  OrtValue* out;
  ThrowOnError(GetApi().CreateSparseTensorWithValuesAsOrtValue(info, p_data, dense_shape.shape, dense_shape.shape_len,
                                                               values_shape.shape, values_shape.shape_len, type,
                                                               &out));
  return Value{out};
}
 
template <typename T>
inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape) {
  return CreateSparseTensor(allocator, dense_shape, TypeToTensorType<T>::type);
}
 
inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape,
                                       ONNXTensorElementDataType type) {
  OrtValue* out;
  ThrowOnError(GetApi().CreateSparseTensorAsOrtValue(allocator, dense_shape.shape, dense_shape.shape_len, type, &out));
  return Value{out};
}
#endif  // !defined(DISABLE_SPARSE_TENSORS)
 
inline Value Value::CreateMap(const Value& keys, const Value& values) {
  OrtValue* out;
  const OrtValue* inputs[2] = {keys, values};
  ThrowOnError(GetApi().CreateValue(inputs, 2, ONNX_TYPE_MAP, &out));
  return Value{out};
}
 
inline Value Value::CreateSequence(const std::vector<Value>& values) {
  OrtValue* out;
  std::vector<const OrtValue*> values_ort{values.data(), values.data() + values.size()};
  ThrowOnError(GetApi().CreateValue(values_ort.data(), values_ort.size(), ONNX_TYPE_SEQUENCE, &out));
  return Value{out};
}
 
template <typename T>
inline Value Value::CreateOpaque(const char* domain, const char* type_name, const T& data_container) {
  OrtValue* out;
  ThrowOnError(GetApi().CreateOpaqueValue(domain, type_name, &data_container, sizeof(T), &out));
  return Value{out};
}
 
//
// Custom OP Inlines
//
inline Logger::Logger(const OrtLogger* logger) : logger_(logger) {
  Ort::ThrowOnError(GetApi().Logger_GetLoggingSeverityLevel(this->logger_, &this->cached_severity_level_));
}
 
inline OrtLoggingLevel Logger::GetLoggingSeverityLevel() const noexcept {
  return cached_severity_level_;
}
 
inline Status Logger::LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number,
                                 const char* func_name, const char* message) const noexcept {
  OrtStatus* status = GetApi().Logger_LogMessage(logger_, log_severity_level, message, file_path, line_number,
                                                 func_name);
  return Status{status};
}
 
// Disable warnings about the format string not being a literal (-Wformat-nonliteral and -Wformat-security)
// for gcc and clang. The alternative is to use actual C-style variadic parameters and apply
// __attribute__(format(printf...)), which does not work with variadic templates.
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
#pragma GCC diagnostic ignored "-Wformat-security"
#elif defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#pragma clang diagnostic ignored "-Wformat-security"
#endif
template <typename... Args>
inline Status Logger::LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path,
                                          int line_number, const char* func_name, const char* format,
                                          Args&&... args) const noexcept {
  int msg_len = std::snprintf(nullptr, 0U, format, std::forward<Args>(args)...);
 
  if (msg_len < 0) {  // Formatting error
    return Status("Failed to log message due to formatting error", OrtErrorCode::ORT_FAIL);
  }
 
  OrtStatus* status = nullptr;
  const size_t buffer_size = static_cast<size_t>(msg_len) + 1U;
 
  constexpr size_t kStackBufferSize = 1024;
 
  if (buffer_size < kStackBufferSize) {
    char buffer[kStackBufferSize];
    snprintf(buffer, kStackBufferSize, format, std::forward<Args>(args)...);
    status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer, file_path, line_number, func_name);
  } else {
    // std::make_unique is only supported starting at C++14.
#if (__cplusplus >= 201402L) || (_MSC_VER >= 1900)
    auto buffer = std::make_unique<char[]>(buffer_size);
#else
    std::unique_ptr<char[]> buffer(new char[buffer_size]);
#endif
    std::snprintf(buffer.get(), buffer_size, format, std::forward<Args>(args)...);
    status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer.get(), file_path, line_number, func_name);
  }
 
  return Status{status};
}
// Re-enable -Wformat-nonliteral and -Wformat-security
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#elif defined(__clang__)
#pragma clang diagnostic pop
#endif
 
inline KernelContext::KernelContext(OrtKernelContext* context) : ctx_(context) {
}
 
inline size_t KernelContext::GetInputCount() const {
  size_t out = 0;
  Ort::ThrowOnError(GetApi().KernelContext_GetInputCount(ctx_, &out));
  return out;
}
 
inline size_t KernelContext::GetOutputCount() const {
  size_t out = 0;
  Ort::ThrowOnError(GetApi().KernelContext_GetOutputCount(ctx_, &out));
  return out;
}
 
inline ConstValue KernelContext::GetInput(size_t index) const {
  const OrtValue* out = nullptr;
  Ort::ThrowOnError(GetApi().KernelContext_GetInput(ctx_, index, &out));
  return ConstValue{out};
}
 
inline UnownedValue KernelContext::GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const {
  OrtValue* out = nullptr;
  Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dim_values, dim_count, &out));
  return UnownedValue(out);
}
 
inline UnownedValue KernelContext::GetOutput(size_t index, const std::vector<int64_t>& dims) const {
  OrtValue* out = nullptr;
  Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dims.data(), dims.size(), &out));
  return UnownedValue(out);
}
 
inline UnownedValue KernelContext::GetPreallocatedOutput(size_t index) const {
  OrtValue* out = nullptr;
  Ort::ThrowOnError(GetApi().KernelContext_GetPreallocatedOutput(ctx_, index, &out));
  return UnownedValue(out);
}
 
inline void* KernelContext::GetGPUComputeStream() const {
  void* out = nullptr;
  Ort::ThrowOnError(GetApi().KernelContext_GetGPUComputeStream(ctx_, &out));
  return out;
}
 
inline OrtSyncStream* KernelContext::GetSyncStream() const {
  OrtSyncStream* out = nullptr;
  Ort::ThrowOnError(GetApi().KernelContext_GetSyncStream(ctx_, &out));
  return out;
}
 
inline Ort::Allocator KernelContext::GetAllocator(const OrtMemoryInfo& memory_info) const {
  OrtAllocator* out = nullptr;
  Ort::ThrowOnError(GetApi().KernelContext_GetAllocator(ctx_, &memory_info, &out));
  return Ort::Allocator{out};
}
 
inline Logger KernelContext::GetLogger() const {
  const OrtLogger* out = nullptr;
  ThrowOnError(GetApi().KernelContext_GetLogger(this->ctx_, &out));
  return Logger{out};
}
 
inline void KernelContext::ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const {
  ThrowOnError(GetApi().KernelContext_ParallelFor(ctx_, fn, total, num_batch, usr_data));
}
 
namespace detail {
 
template <typename T>
constexpr OrtOpAttrType TypeToAttrType();
 
template <>
inline constexpr OrtOpAttrType TypeToAttrType<int64_t>() {
  return OrtOpAttrType::ORT_OP_ATTR_INT;
}
 
template <>
inline constexpr OrtOpAttrType TypeToAttrType<float>() {
  return OrtOpAttrType::ORT_OP_ATTR_FLOAT;
}
 
template <typename T>
inline constexpr OrtOpAttrType TypeToAttrsType();
 
template <>
inline constexpr OrtOpAttrType TypeToAttrsType<int64_t>() {
  return OrtOpAttrType::ORT_OP_ATTR_INTS;
}
 
template <>
inline constexpr OrtOpAttrType TypeToAttrsType<float>() {
  return OrtOpAttrType::ORT_OP_ATTR_FLOATS;
}
 
inline Status CheckAttrType(const OrtOpAttr* attr, OrtOpAttrType requested_type) {
  OrtOpAttrType type;
  Ort::Status status(GetApi().OpAttr_GetType(attr, &type));
  if (!status.IsOK()) return status;
  if (requested_type != type) {
    std::string msg = "Attribute type mismatch: expected " + std::to_string(requested_type) +
                      ", but got " + std::to_string(type);
    return Ort::Status(msg.c_str(), OrtErrorCode::ORT_INVALID_ARGUMENT);
  }
  return Ort::Status{};
}
 
inline size_t GetDataSize(const OrtOpAttr* attr, OrtOpAttrType attr_type) {
  size_t result{};
  // Ignore the status here because we check the data type so the error should only be about
  // the size
  [[maybe_unused]] Status status{GetApi().ReadOpAttr(attr, attr_type, nullptr, 0, &result)};
  return result;
}
 
template <typename T>
Ort::Status GetNumericValue(const OrtOpAttr* attr, T& out) {
  static_assert(std::is_arithmetic<T>::value, "T must be an arithmetic type");
  size_t size{};
  return Ort::Status{GetApi().ReadOpAttr(attr, TypeToAttrType<T>(), &out, sizeof(out), &size)};
}
 
template <typename T>
struct GetValueImpl {
  static Status GetValue(const OrtOpAttr* attr, T& out) {
    return GetNumericValue<T>(attr, out);
  }
  static Status GetValues(const OrtOpAttr* attr, std::vector<T>& out) {
    // Api deficiency when it comes to value arrays. It is not possible
    // to tell if the error is due to the type mismatch or the size
    // so we check the type first, and then ignore the status of the size check
    constexpr auto deduced_type = TypeToAttrsType<T>();
    auto status = CheckAttrType(attr, deduced_type);
    if (!status.IsOK()) return status;
    auto size = GetDataSize(attr, deduced_type);
    std::vector<T> result;
    if (size > 0) {
      result.resize(size / sizeof(T));
      status = Status{GetApi().ReadOpAttr(
          attr, deduced_type, result.data(), size, &size)};
      if (!status.IsOK()) return status;
    }
    out.swap(result);
    return status;
  }
};
 
// Create GetValueImpl specializations for std::string
template <>
struct GetValueImpl<std::string> {
  static Status GetValue(const OrtOpAttr* attr, std::string& out) {
    // Api deficiency when it comes to value arrays. It is not possible
    // to tell if the error is due to the type mismatch or the size
    // so we check the type first, and then ignore the status of the size check
    auto status = CheckAttrType(attr, OrtOpAttrType::ORT_OP_ATTR_STRING);
    if (!status.IsOK()) return status;
    auto size = GetDataSize(attr, OrtOpAttrType::ORT_OP_ATTR_STRING);
    std::string result;
    if (size > 0) {
      result.resize(size);
      // some compilers in use do not support std::string::data() non-const
      auto* buffer = &result[0];
      status = Status{GetApi().ReadOpAttr(
          attr, OrtOpAttrType::ORT_OP_ATTR_STRING, buffer, size, &size)};
      if (!status.IsOK()) return status;
    }
    out.swap(result);
    return status;
  }
  static Status GetValues(const OrtOpAttr* attr, std::vector<std::string>& out) {
    auto status = CheckAttrType(attr, OrtOpAttrType::ORT_OP_ATTR_STRINGS);
    if (!status.IsOK()) return status;
 
    std::vector<std::string> result;
    size_t total_buffer_size = GetDataSize(attr, OrtOpAttrType::ORT_OP_ATTR_STRINGS);
    if (total_buffer_size > 0) {
      // Create a temporary buffer to hold the string data
      std::vector<char> buffer(total_buffer_size);
      status = Status{GetApi().ReadOpAttr(attr, OrtOpAttrType::ORT_OP_ATTR_STRINGS, buffer.data(),
                                          total_buffer_size, &total_buffer_size)};
      if (!status.IsOK()) return status;
 
      const char* data = buffer.data();
      const char* end = data + total_buffer_size;
      while (data < end) {
        result.emplace_back(data);
        data += result.back().size() + 1;  // Move past the null terminator
      }
    }
    out.swap(result);
    return status;
  }
};
 
template <typename T>
template <typename R>
inline Status ConstOpAttrImpl<T>::GetValue(R& out) const {
  return GetValueImpl<R>::GetValue(this->p_, out);
}
 
template <typename T>
template <typename R>
inline Status ConstOpAttrImpl<T>::GetValueArray(std::vector<R>& out) const {
  return GetValueImpl<R>::GetValues(this->p_, out);
}
 
template <typename T>
inline Status ConstOpAttrImpl<T>::GetTensorAttributeAsOrtValue(Value& out) const {
  OrtValue* tensor_value = nullptr;
  auto status = Status(GetApi().OpAttr_GetTensorAttributeAsOrtValue(this->p_, &tensor_value));
  if (!status.IsOK()) return status;
  out = Value{tensor_value};
  return status;
}
 
template <typename T>
inline std::string ConstOpAttrImpl<T>::GetName() const {
  const char* name = nullptr;
  ThrowOnError(GetApi().OpAttr_GetName(this->p_, &name));
  if (name != nullptr) {
    return name;
  }
  return {};
}
 
template <typename T>
inline OrtOpAttrType ConstOpAttrImpl<T>::GetType() const {
  OrtOpAttrType type;
  ThrowOnError(GetApi().OpAttr_GetType(this->p_, &type));
  return type;
}
}  // namespace detail
 
inline OpAttr::OpAttr(const char* name, const void* data, int len, OrtOpAttrType type) {
  Ort::ThrowOnError(GetApi().CreateOpAttr(name, data, len, type, &p_));
}
 
namespace detail {
template <typename T>
inline KernelInfo KernelInfoImpl<T>::Copy() const {
  OrtKernelInfo* info_copy = nullptr;
  Ort::ThrowOnError(GetApi().CopyKernelInfo(this->p_, &info_copy));
  return KernelInfo{info_copy};
}
 
template <typename T>
inline size_t KernelInfoImpl<T>::GetInputCount() const {
  size_t out = 0;
  ThrowOnError(GetApi().KernelInfo_GetInputCount(this->p_, &out));
  return out;
}
 
template <typename T>
inline size_t KernelInfoImpl<T>::GetOutputCount() const {
  size_t out = 0;
  ThrowOnError(GetApi().KernelInfo_GetOutputCount(this->p_, &out));
  return out;
}
 
template <typename T>
inline std::string KernelInfoImpl<T>::GetInputName(size_t index) const {
  size_t size = 0;
 
  // Feed nullptr for the data buffer to query the true size of the string value
  Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, nullptr, &size));
 
  std::string out;
  out.resize(size);
  Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, &out[0], &size));
  out.resize(size - 1);  // remove the terminating character '\0'
 
  return out;
}
 
template <typename T>
inline std::string KernelInfoImpl<T>::GetOutputName(size_t index) const {
  size_t size = 0;
 
  // Feed nullptr for the data buffer to query the true size of the string value
  Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, nullptr, &size));
 
  std::string out;
  out.resize(size);
  Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, &out[0], &size));
  out.resize(size - 1);  // remove the terminating character '\0'
 
  return out;
}
 
template <typename T>
inline TypeInfo KernelInfoImpl<T>::GetInputTypeInfo(size_t index) const {
  OrtTypeInfo* out = nullptr;
  ThrowOnError(GetApi().KernelInfo_GetInputTypeInfo(this->p_, index, &out));
  return TypeInfo{out};
}
 
template <typename T>
inline TypeInfo KernelInfoImpl<T>::GetOutputTypeInfo(size_t index) const {
  OrtTypeInfo* out = nullptr;
  ThrowOnError(GetApi().KernelInfo_GetOutputTypeInfo(this->p_, index, &out));
  return TypeInfo{out};
}
 
template <typename T>
inline Value KernelInfoImpl<T>::GetTensorAttribute(const char* name, OrtAllocator* allocator) const {
  OrtValue* out = nullptr;
  ThrowOnError(GetApi().KernelInfoGetAttribute_tensor(this->p_, name, allocator, &out));
  return Value{out};
}
 
template <typename T>
inline ConstValue KernelInfoImpl<T>::GetTensorConstantInput(size_t index, int* is_constant) const {
  const OrtValue* out = nullptr;
  ThrowOnError(GetApi().KernelInfoGetConstantInput_tensor(this->p_, index, is_constant, &out));
  return ConstValue{out};
}
 
template <typename T>
inline std::string KernelInfoImpl<T>::GetNodeName() const {
  size_t size = 0;
 
  // Feed nullptr for the data buffer to query the true size of the string value
  Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, nullptr, &size));
 
  std::string out;
  out.resize(size);
  Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, &out[0], &size));
  out.resize(size - 1);  // remove the terminating character '\0'
 
  return out;
}
 
template <typename T>
inline Logger KernelInfoImpl<T>::GetLogger() const {
  const OrtLogger* out = nullptr;
  ThrowOnError(GetApi().KernelInfo_GetLogger(this->p_, &out));
  return Logger{out};
}
 
template <typename T>
inline KeyValuePairs KernelInfoImpl<T>::GetConfigEntries() const {
  OrtKeyValuePairs* out = nullptr;
  Ort::ThrowOnError(GetApi().KernelInfo_GetConfigEntries(this->p_, &out));
  return KeyValuePairs{out};
}
 
template <typename T>
inline std::string KernelInfoImpl<T>::GetOperatorDomain() const {
  size_t size = 0;
 
  // Feed nullptr for the data buffer to query the true size of the string value
  Ort::ThrowOnError(GetApi().KernelInfo_GetOperatorDomain(this->p_, nullptr, &size));
 
  std::string out;
  out.resize(size);
  Ort::ThrowOnError(GetApi().KernelInfo_GetOperatorDomain(this->p_, &out[0], &size));
  out.resize(size - 1);  // remove the terminating character '\0'
 
  return out;
}
 
template <typename T>
inline std::string KernelInfoImpl<T>::GetOperatorType() const {
  size_t size = 0;
 
  // Feed nullptr for the data buffer to query the true size of the string value
  Ort::ThrowOnError(GetApi().KernelInfo_GetOperatorType(this->p_, nullptr, &size));
 
  std::string out;
  out.resize(size);
  Ort::ThrowOnError(GetApi().KernelInfo_GetOperatorType(this->p_, &out[0], &size));
  out.resize(size - 1);  // remove the terminating character '\0'
 
  return out;
}
 
template <typename T>
inline int KernelInfoImpl<T>::GetOperatorSinceVersion() const {
  int out = 0;
  Ort::ThrowOnError(GetApi().KernelInfo_GetOperatorSinceVersion(this->p_, &out));
  return out;
}
 
template <typename T>
inline const OrtEp* KernelInfoImpl<T>::GetEp() const {
  const OrtEp* ep = nullptr;
  Ort::ThrowOnError(GetEpApi().KernelInfo_GetEp(this->p_, &ep));
  return ep;
}
 
inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, float& out) {
  Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_float(p, name, &out));
}
 
inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, int64_t& out) {
  Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_int64(p, name, &out));
}
 
inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, std::string& result) {
  size_t size = 0;
  // Feed nullptr for the data buffer to query the true size of the string attribute
  Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, nullptr, &size));
 
  std::string out;
  out.resize(size);
  Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, &out[0], &size));
  out.resize(size - 1);  // remove the terminating character '\0'
  out.swap(result);
}
 
inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector<float>& result) {
  size_t size = 0;
  // Feed nullptr for the data buffer to query the true size of the attribute
  Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, nullptr, &size));
 
  std::vector<float> out;
  out.resize(size);
  Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, out.data(), &size));
  out.swap(result);
}
 
inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector<int64_t>& result) {
  size_t size = 0;
 
  // Feed nullptr for the data buffer to query the true size of the attribute
  Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, nullptr, &size));
 
  std::vector<int64_t> out;
  out.resize(size);
  Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, out.data(), &size));
  out.swap(result);
}
 
inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector<std::string>& result) {
  AllocatorWithDefaultOptions allocator;
  char** out = nullptr;
  size_t size = 0;
 
  Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_string(p, name, allocator, nullptr, &size));
  if (size == 0) {
    result.clear();
    return;
  }
 
  Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_string(p, name, allocator, &out, &size));
 
  auto deleter = detail::AllocatedFree(allocator);
  std::unique_ptr<void, decltype(deleter)> array_guard(out, deleter);
  auto strings_deleter = [&deleter, size](char** values) {
    for (size_t i = 0; i < size; ++i) {
      if (values[i] != nullptr) {
        deleter(values[i]);
      }
    }
  };
  std::unique_ptr<char*, decltype(strings_deleter)> strings_guard(out, strings_deleter);
 
  std::vector<std::string> strings;
  strings.reserve(size);
  for (size_t i = 0; i < size; ++i) {
    strings.emplace_back(out[i]);
  }
 
  strings.swap(result);
}
}  // namespace detail
 
inline KernelInfo::KernelInfo(OrtKernelInfo* info) : detail::KernelInfoImpl<OrtKernelInfo>{info} {}
 
inline Op::Op(OrtOp* p) : detail::Base<OrtOp>(p) {}
 
inline Op Op::Create(const OrtKernelInfo* info, const char* op_name, const char* domain, int version,
                     const char** type_constraint_names,
                     const ONNXTensorElementDataType* type_constraint_values,
                     size_t type_constraint_count,
                     const OpAttr* attr_values, size_t attr_count,
                     size_t input_count, size_t output_count) {
  static_assert(sizeof(OpAttr) == sizeof(OrtOpAttr*),
                "OpAttr's is expected to be just an array of OrtOpAttr in memory so we can reinterpret safely");
  auto attr_input_values = reinterpret_cast<const OrtOpAttr* const*>(attr_values);
  OrtOp* op;
  Ort::ThrowOnError(GetApi().CreateOp(info, op_name, domain, version, type_constraint_names, type_constraint_values,
                                      static_cast<int>(type_constraint_count),
                                      attr_input_values,
                                      static_cast<int>(attr_count),
                                      static_cast<int>(input_count),
                                      static_cast<int>(output_count), &op));
  return Op{op};
}
 
inline void Op::Invoke(const OrtKernelContext* context,
                       const Value* input_values,
                       size_t input_count,
                       Value* output_values,
                       size_t output_count) {
  static_assert(sizeof(Value) == sizeof(OrtValue*),
                "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely");
  auto ort_input_values = reinterpret_cast<const OrtValue* const*>(input_values);
  auto ort_output_values = reinterpret_cast<OrtValue**>(output_values);
  Ort::ThrowOnError(GetApi().InvokeOp(context, p_, ort_input_values, static_cast<int>(input_count),
                                      ort_output_values, static_cast<int>(output_count)));
}
 
inline void Op::Invoke(const OrtKernelContext* context,
                       const OrtValue* const* input_values,
                       size_t input_count,
                       OrtValue* const* output_values,
                       size_t output_count) {
  Ort::ThrowOnError(GetApi().InvokeOp(context, p_, input_values, static_cast<int>(input_count),
                                      output_values, static_cast<int>(output_count)));
}
 
inline std::string GetVersionString() {
  return OrtGetApiBase()->GetVersionString();
}
 
inline std::string GetBuildInfoString() {
  return GetApi().GetBuildInfoString();
}
 
inline std::vector<std::string> GetAvailableProviders() {
  char** providers;
  int len;
 
  auto release_fn = [&len](char** providers) {
    // This should always return nullptr.
    ThrowOnError(GetApi().ReleaseAvailableProviders(providers, len));
  };
 
  ThrowOnError(GetApi().GetAvailableProviders(&providers, &len));
  std::unique_ptr<char*, decltype(release_fn)> guard(providers, release_fn);
  std::vector<std::string> available_providers;
  available_providers.reserve(static_cast<size_t>(len));
  for (int i = 0; i < len; ++i) {
    available_providers.emplace_back(providers[i]);
  }
  return available_providers;
}
 
template <typename TOp, typename TKernel, bool WithStatus>
void CustomOpBase<TOp, TKernel, WithStatus>::GetSessionConfigs(std::unordered_map<std::string, std::string>& out,
                                                               ConstSessionOptions options) const {
  const TOp* derived = static_cast<const TOp*>(this);
  std::vector<std::string> keys = derived->GetSessionConfigKeys();
 
  out.reserve(keys.size());
 
  std::string config_entry_key = detail::MakeCustomOpConfigEntryKey(derived->GetName(), "");
  const size_t prefix_size = config_entry_key.length();
 
  for (const auto& key : keys) {
    config_entry_key.resize(prefix_size);
    config_entry_key.append(key);
    out[key] = options.GetConfigEntryOrDefault(config_entry_key.c_str(), "");
  }
}
 
inline ShapeInferContext::ShapeInferContext(const OrtApi* ort_api,
                                            OrtShapeInferContext* ctx) : ort_api_(ort_api), ctx_(ctx) {
  size_t input_count = 0;
  Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputCount(ctx_, &input_count));
  for (size_t ith_input = 0; ith_input < input_count; ++ith_input) {
    OrtTensorTypeAndShapeInfo* info{};
    Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputTypeShape(ctx, ith_input, &info));
    TensorTypeAndShapeInfo type_shape_info(info);
    auto integer_shape = type_shape_info.GetShape();
    std::vector<const char*> symbolic_shape(integer_shape.size(), {});
    if (!integer_shape.empty()) {
      type_shape_info.GetSymbolicDimensions(&symbolic_shape[0], integer_shape.size());
    }
    Shape shape;
    for (size_t ith = 0; ith < integer_shape.size(); ++ith) {
      if (symbolic_shape[ith] && std::string{symbolic_shape[ith]}.size() > 0) {
        shape.emplace_back(symbolic_shape[ith]);
      } else {
        shape.emplace_back(integer_shape[ith]);
      }
    }
    input_shapes_.push_back(std::move(shape));
    type_shape_info.release();
  }
}
 
inline Status ShapeInferContext::SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type) {
  OrtTensorTypeAndShapeInfo* info = {};
  ORT_CXX_RETURN_ON_API_FAIL(ort_api_->CreateTensorTypeAndShapeInfo(&info));
  ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetTensorElementType(info, type));
 
  using InfoPtr = std::unique_ptr<OrtTensorTypeAndShapeInfo, std::function<void(OrtTensorTypeAndShapeInfo*)>>;
 
  InfoPtr info_ptr(info, [this](OrtTensorTypeAndShapeInfo* obj) {
    ort_api_->ReleaseTensorTypeAndShapeInfo(obj);
  });
 
  std::vector<int64_t> integer_dims;
  std::vector<const char*> symbolic_dims;
 
  for (const auto dim : shape) {
    if (dim.IsInt()) {
      integer_dims.push_back(dim.AsInt());
      symbolic_dims.push_back("");
    } else {
      if (!dim.AsSym() || std::string{dim.AsSym()}.empty()) {
        ORT_CXX_API_THROW("Symbolic dim must not be an empty string", ORT_INVALID_ARGUMENT);
      }
      integer_dims.push_back(SymbolicInteger::INVALID_INT_DIM);
      symbolic_dims.push_back(dim.AsSym());
    }
  }
 
  ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetDimensions(info, integer_dims.data(), integer_dims.size()));
  ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetSymbolicDimensions(info, symbolic_dims.data(), symbolic_dims.size()));
  ORT_CXX_RETURN_ON_API_FAIL(ort_api_->ShapeInferContext_SetOutputTypeShape(ctx_, indice, info));
  return Status{nullptr};
}
 
inline int64_t ShapeInferContext::GetAttrInt(const char* attr_name) {
  auto attr = GetAttrHdl(attr_name);
  int64_t value;
  Status status = attr.GetValue<int64_t>(value);
  if (!status.IsOK()) {
    ORT_CXX_API_THROW("Getting int attribute failed: " + status.GetErrorMessage(), status.GetErrorCode());
  }
  return value;
}
 
inline ShapeInferContext::Ints ShapeInferContext::GetAttrInts(const char* attr_name) {
  auto attr = GetAttrHdl(attr_name);
  ShapeInferContext::Ints result;
  auto status = attr.GetValueArray<int64_t>(result);
  if (!status.IsOK()) {
    ORT_CXX_API_THROW("Getting ints attribute failed: " + status.GetErrorMessage(), status.GetErrorCode());
  }
  return result;
}
 
inline float ShapeInferContext::GetAttrFloat(const char* attr_name) {
  auto attr = GetAttrHdl(attr_name);
  float value;
  Status status = attr.GetValue<float>(value);
  if (!status.IsOK()) {
    ORT_CXX_API_THROW("Getting float attribute failed: " + status.GetErrorMessage(), status.GetErrorCode());
  }
  return value;
}
 
inline ShapeInferContext::Floats ShapeInferContext::GetAttrFloats(const char* attr_name) {
  auto attr = GetAttrHdl(attr_name);
  ShapeInferContext::Floats result;
  auto status = attr.GetValueArray<float>(result);
  if (!status.IsOK()) {
    ORT_CXX_API_THROW("Getting floats attribute failed: " + status.GetErrorMessage(), status.GetErrorCode());
  }
  return result;
}
 
inline std::string ShapeInferContext::GetAttrString(const char* attr_name) {
  auto attr = GetAttrHdl(attr_name);
  std::string value;
  Status status = attr.GetValue<std::string>(value);
  if (!status.IsOK()) {
    ORT_CXX_API_THROW("Getting string attribute failed: " + status.GetErrorMessage(), status.GetErrorCode());
  }
  return value;
}
 
inline ShapeInferContext::Strings ShapeInferContext::GetAttrStrings(const char* attr_name) {
  auto attr = GetAttrHdl(attr_name);
  ShapeInferContext::Strings result;
  auto status = attr.GetValueArray<std::string>(result);
  if (!status.IsOK()) {
    ORT_CXX_API_THROW("Getting strings attribute failed: " + status.GetErrorMessage(), status.GetErrorCode());
  }
  return result;
}
 
inline ConstOpAttr ShapeInferContext::GetAttrHdl(const char* attr_name) const {
  const OrtOpAttr* attr_hdl = {};
  Ort::ThrowOnError(ort_api_->ShapeInferContext_GetAttribute(ctx_, attr_name, &attr_hdl));
  return ConstOpAttr{attr_hdl};
}
 
namespace detail {
inline std::vector<const char*> StringsToCharPtrs(const std::vector<std::string>& strings) {
  std::vector<const char*> ptrs;
  ptrs.reserve(strings.size());
  std::transform(strings.begin(), strings.end(), std::back_inserter(ptrs),
                 [](const std::string& s) { return s.c_str(); });
 
  return ptrs;
}
}  // namespace detail
 
namespace detail {
template <typename T>
inline size_t ConstNodeImpl<T>::GetId() const {
  size_t id;
  ThrowOnError(GetApi().Node_GetId(this->p_, &id));
  return id;
}
 
template <typename T>
inline std::string ConstNodeImpl<T>::GetName() const {
  const char* name;
  ThrowOnError(GetApi().Node_GetName(this->p_, &name));
  return std::string(name);
}
 
template <typename T>
inline std::string ConstNodeImpl<T>::GetOperatorType() const {
  const char* type;
  ThrowOnError(GetApi().Node_GetOperatorType(this->p_, &type));
  return std::string(type);
}
 
template <typename T>
inline std::string ConstNodeImpl<T>::GetDomain() const {
  const char* domain;
  ThrowOnError(GetApi().Node_GetDomain(this->p_, &domain));
  return std::string(domain);
}
 
template <typename T>
inline int ConstNodeImpl<T>::GetSinceVersion() const {
  int since_version;
  ThrowOnError(GetApi().Node_GetSinceVersion(this->p_, &since_version));
  return since_version;
}
 
template <typename T>
inline std::vector<ConstValueInfo> ConstNodeImpl<T>::GetInputs() const {
  static_assert(sizeof(const OrtValueInfo*) == sizeof(ConstValueInfo));
  size_t num_vi;
  ThrowOnError(GetApi().Node_GetNumInputs(this->p_, &num_vi));
  std::vector<ConstValueInfo> result;
  if (num_vi > 0) {
    result.resize(num_vi);
    ThrowOnError(GetApi().Node_GetInputs(this->p_, reinterpret_cast<const OrtValueInfo**>(result.data()), num_vi));
  }
  return result;
}
 
template <typename T>
inline std::vector<ConstValueInfo> ConstNodeImpl<T>::GetOutputs() const {
  static_assert(sizeof(const OrtValueInfo*) == sizeof(ConstValueInfo));
  size_t num_vi;
  ThrowOnError(GetApi().Node_GetNumOutputs(this->p_, &num_vi));
  std::vector<ConstValueInfo> result;
  if (num_vi > 0) {
    result.resize(num_vi);
    ThrowOnError(GetApi().Node_GetOutputs(this->p_, reinterpret_cast<const OrtValueInfo**>(result.data()), num_vi));
  }
  return result;
}
 
template <typename T>
inline std::vector<ConstValueInfo> ConstNodeImpl<T>::GetImplicitInputs() const {
  static_assert(sizeof(const OrtValueInfo*) == sizeof(ConstValueInfo));
  size_t num_vi;
  ThrowOnError(GetApi().Node_GetNumImplicitInputs(this->p_, &num_vi));
  std::vector<ConstValueInfo> result;
  if (num_vi > 0) {
    result.resize(num_vi);
    ThrowOnError(GetApi().Node_GetImplicitInputs(this->p_, reinterpret_cast<const OrtValueInfo**>(result.data()),
                                                 num_vi));
  }
  return result;
}
 
template <typename T>
inline std::vector<ConstOpAttr> ConstNodeImpl<T>::GetAttributes() const {
  static_assert(sizeof(const OrtOpAttr*) == sizeof(ConstOpAttr), "Must be the same size");
  size_t num_attrs;
  ThrowOnError(GetApi().Node_GetNumAttributes(this->p_, &num_attrs));
  std::vector<ConstOpAttr> attrs;
  if (num_attrs > 0) {
    attrs.resize(num_attrs);
    ThrowOnError(GetApi().Node_GetAttributes(this->p_, reinterpret_cast<const OrtOpAttr**>(attrs.data()), num_attrs));
  }
  return attrs;
}
 
template <typename T>
inline Status ConstNodeImpl<T>::GetAttributeByName(const std::string& name, ConstOpAttr& out) const {
  const OrtOpAttr* attr = nullptr;
  auto status = Status(GetApi().Node_GetAttributeByName(this->p_, name.c_str(), &attr));
  out = ConstOpAttr{attr};
  return status;
}
 
template <typename T>
inline std::vector<AttrNameSubgraph> ConstNodeImpl<T>::GetSubgraphs() const {
  size_t num_graphs;
  ThrowOnError(GetApi().Node_GetNumSubgraphs(this->p_, &num_graphs));
  std::vector<AttrNameSubgraph> result;
  if (num_graphs > 0) {
    std::vector<const OrtGraph*> sub_graphs(num_graphs);
    std::vector<const char*> attr_names(num_graphs);
    ThrowOnError(GetApi().Node_GetSubgraphs(this->p_, sub_graphs.data(), num_graphs, attr_names.data()));
    result.reserve(num_graphs);
    for (size_t i = 0; i < num_graphs; ++i) {
      result.push_back({std::string(attr_names[i]), ConstGraph{sub_graphs[i]}});
    }
  }
  return result;
}
 
template <typename T>
inline ConstGraph ConstNodeImpl<T>::GetGraph() const {
  const OrtGraph* graph;
  ThrowOnError(GetApi().Node_GetGraph(this->p_, &graph));
  return ConstGraph{graph};
}
 
template <typename T>
inline std::string ConstNodeImpl<T>::GetEpName() const {
  const char* name;
  ThrowOnError(GetApi().Node_GetEpName(this->p_, &name));
  return std::string(name);
}
 
}  // namespace detail
 
#if !defined(ORT_MINIMAL_BUILD)
// static
inline void Node::Init(const std::string& operator_name, const std::string& operator_domain,
                       const std::string& node_name,
                       const std::vector<std::string>& input_names,
                       const std::vector<std::string>& output_names,
                       std::vector<OpAttr>& attributes,
                       OrtNode*& node) {
  auto inputs = detail::StringsToCharPtrs(input_names);
  auto outputs = detail::StringsToCharPtrs(output_names);
 
  std::vector<OrtOpAttr*> attributes_ptrs;
  attributes_ptrs.reserve(attributes.size());
  std::transform(attributes.begin(), attributes.end(), std::back_inserter(attributes_ptrs),
                 [](OpAttr& attr) -> OrtOpAttr* { return attr; });
 
  ThrowOnError(GetModelEditorApi().CreateNode(operator_name.c_str(), operator_domain.c_str(), node_name.c_str(),
                                              inputs.data(), inputs.size(),
                                              outputs.data(), outputs.size(),
                                              attributes_ptrs.data(), attributes_ptrs.size(),
                                              &node));
 
  // Node now owns the attributes
  std::for_each(attributes.begin(), attributes.end(), [](OpAttr& attr) { attr.release(); });
}
 
inline Node::Node(const std::string& operator_name, const std::string& operator_domain,
                  const std::string& node_name,
                  const std::vector<std::string>& input_names,
                  const std::vector<std::string>& output_names,
                  std::vector<OpAttr>& attributes) {
  Init(operator_name, operator_domain, node_name, input_names, output_names, attributes, p_);
}
 
inline Node::Node(const std::string& operator_name, const std::string& operator_domain,
                  const std::string& node_name,
                  const std::vector<std::string>& input_names,
                  const std::vector<std::string>& output_names) {
  std::vector<OpAttr> empty_attributes;
  Init(operator_name, operator_domain, node_name, input_names, output_names, empty_attributes, p_);
}
inline ValueInfo::ValueInfo(const std::string& name, const ConstTypeInfo& type_info) {
  ThrowOnError(GetModelEditorApi().CreateValueInfo(name.c_str(), type_info, &p_));
}
#endif  // !defined(ORT_MINIMAL_BUILD)
 
namespace detail {
template <typename T>
inline std::string ConstValueInfoImpl<T>::GetName() const {
  const char* p = nullptr;
  ThrowOnError(GetApi().GetValueInfoName(this->p_, &p));
  return std::string(p);
}
 
template <typename T>
inline ConstTypeInfo ConstValueInfoImpl<T>::TypeInfo() const {
  const OrtTypeInfo* type_info = nullptr;
  ThrowOnError(GetApi().GetValueInfoTypeInfo(this->p_, &type_info));
  return ConstTypeInfo{type_info};
}
 
template <typename T>
inline ValueInfoConsumerProducerInfo ConstValueInfoImpl<T>::GetProducerNode() const {
  ValueInfoConsumerProducerInfo info;
  const OrtNode* producer;
  size_t index;
  ThrowOnError(GetApi().ValueInfo_GetValueProducer(this->p_, &producer, &index));
  info.node = ConstNode(producer);
  info.index = static_cast<int64_t>(index);
  return info;
}
 
template <typename T>
inline std::vector<ValueInfoConsumerProducerInfo> ConstValueInfoImpl<T>::GetConsumers() const {
  size_t num = 0;
  ThrowOnError(GetApi().ValueInfo_GetValueNumConsumers(this->p_, &num));
  std::vector<ValueInfoConsumerProducerInfo> out;
  if (num > 0) {
    std::vector<const OrtNode*> nodes(num);
    std::vector<int64_t> indices(num);
    ThrowOnError(GetApi().ValueInfo_GetValueConsumers(this->p_, nodes.data(), indices.data(), num));
    out.reserve(num);
    for (size_t i = 0; i < num; ++i) {
      out.push_back({ConstNode{nodes[i]}, indices[i]});
    }
  }
  return out;
}
 
template <typename T>
inline Status ConstValueInfoImpl<T>::GetInitializer(ConstValue& value) const {
  const OrtValue* out = nullptr;
  auto status = Status(GetApi().ValueInfo_GetInitializerValue(this->p_, &out));
  if (!status.IsOK()) return status;
  value = ConstValue{out};
  return status;
}
 
template <typename T>
inline Status ConstValueInfoImpl<T>::GetExternalInitializerInfo(ExternalInitializerInfo& info) const {
  OrtExternalInitializerInfo* out = nullptr;
  auto status = Status(GetApi().ValueInfo_GetExternalInitializerInfo(this->p_, &out));
  if (!status.IsOK()) return status;
  info = ExternalInitializerInfo{out};
  return status;
}
 
template <typename T>
inline bool ConstValueInfoImpl<T>::IsRequiredGraphInput() const {
  bool out = false;
  ThrowOnError(GetApi().ValueInfo_IsRequiredGraphInput(this->p_, &out));
  return out;
}
 
template <typename T>
inline bool ConstValueInfoImpl<T>::IsOptionalGraphInput() const {
  bool out = false;
  ThrowOnError(GetApi().ValueInfo_IsOptionalGraphInput(this->p_, &out));
  return out;
}
 
template <typename T>
inline bool ConstValueInfoImpl<T>::IsGraphOutput() const {
  bool out = false;
  ThrowOnError(GetApi().ValueInfo_IsGraphOutput(this->p_, &out));
  return out;
}
 
template <typename T>
inline bool ConstValueInfoImpl<T>::IsConstantInitializer() const {
  bool out = false;
  ThrowOnError(GetApi().ValueInfo_IsConstantInitializer(this->p_, &out));
  return out;
}
 
template <typename T>
inline bool ConstValueInfoImpl<T>::IsFromOuterScope() const {
  bool out = false;
  ThrowOnError(GetApi().ValueInfo_IsFromOuterScope(this->p_, &out));
  return out;
}
 
template <typename T>
inline ModelMetadata ConstGraphImpl<T>::GetModelMetadata() const {
  OrtModelMetadata* out;
  ThrowOnError(GetApi().Graph_GetModelMetadata(this->p_, &out));
  return ModelMetadata{out};
}
 
template <typename T>
inline std::string ConstGraphImpl<T>::GetName() const {
  const char* name;
  ThrowOnError(GetApi().Graph_GetName(this->p_, &name));
  return std::string(name);
}
 
template <typename T>
inline std::basic_string<ORTCHAR_T> ConstGraphImpl<T>::GetModelPath() const {
  const ORTCHAR_T* path;
  ThrowOnError(GetApi().Graph_GetModelPath(this->p_, &path));
  return std::basic_string<ORTCHAR_T>(path);
}
 
template <typename T>
inline int64_t ConstGraphImpl<T>::GetOnnxIRVersion() const {
  int64_t version;
  ThrowOnError(GetApi().Graph_GetOnnxIRVersion(this->p_, &version));
  return version;
}
 
template <typename T>
inline std::vector<OperatorSet> ConstGraphImpl<T>::GetOperatorSets() const {
  size_t num_opsets;
  ThrowOnError(GetApi().Graph_GetNumOperatorSets(this->p_, &num_opsets));
  std::vector<OperatorSet> result;
  if (num_opsets > 0) {
    std::vector<const char*> domains;
    std::vector<int64_t> versions;
    domains.resize(num_opsets);
    versions.resize(num_opsets);
    ThrowOnError(GetApi().Graph_GetOperatorSets(this->p_, domains.data(), versions.data(), num_opsets));
    result.reserve(num_opsets);
    for (size_t i = 0; i < num_opsets; ++i) {
      result.push_back({domains[i], versions[i]});
    }
  }
  return result;
}
 
template <typename T>
inline std::vector<ConstValueInfo> ConstGraphImpl<T>::GetInputs() const {
  static_assert(sizeof(const OrtValueInfo*) == sizeof(ConstValueInfo));
  size_t num_vi;
  ThrowOnError(GetApi().Graph_GetNumInputs(this->p_, &num_vi));
  std::vector<ConstValueInfo> result;
  if (num_vi > 0) {
    result.resize(num_vi);
    ThrowOnError(GetApi().Graph_GetInputs(this->p_, reinterpret_cast<const OrtValueInfo**>(result.data()), num_vi));
  }
  return result;
}
 
template <typename T>
inline std::vector<ConstValueInfo> ConstGraphImpl<T>::GetOutputs() const {
  static_assert(sizeof(const OrtValueInfo*) == sizeof(ConstValueInfo));
  size_t num_vi;
  ThrowOnError(GetApi().Graph_GetNumOutputs(this->p_, &num_vi));
  std::vector<ConstValueInfo> result;
  if (num_vi > 0) {
    result.resize(num_vi);
    ThrowOnError(GetApi().Graph_GetOutputs(this->p_, reinterpret_cast<const OrtValueInfo**>(result.data()), num_vi));
  }
  return result;
}
 
template <typename T>
inline std::vector<ConstValueInfo> ConstGraphImpl<T>::GetInitializers() const {
  static_assert(sizeof(const OrtValueInfo*) == sizeof(ConstValueInfo));
  size_t num_vi;
  ThrowOnError(GetApi().Graph_GetNumInitializers(this->p_, &num_vi));
  std::vector<ConstValueInfo> result;
  if (num_vi > 0) {
    result.resize(num_vi);
    ThrowOnError(GetApi().Graph_GetInitializers(this->p_, reinterpret_cast<const OrtValueInfo**>(result.data()),
                                                num_vi));
  }
  return result;
}
 
template <typename T>
inline std::vector<ConstNode> ConstGraphImpl<T>::GetNodes() const {
  static_assert(sizeof(const OrtNode*) == sizeof(ConstNode));
  size_t num_nodes;
  ThrowOnError(GetApi().Graph_GetNumNodes(this->p_, &num_nodes));
  std::vector<ConstNode> result;
  if (num_nodes > 0) {
    result.resize(num_nodes);
    ThrowOnError(GetApi().Graph_GetNodes(this->p_, reinterpret_cast<const OrtNode**>(result.data()), num_nodes));
  }
  return result;
}
 
template <typename T>
inline ConstNode ConstGraphImpl<T>::GetParentNode() const {
  const OrtNode* parent;
  ThrowOnError(GetApi().Graph_GetParentNode(this->p_, &parent));
  return ConstNode{parent};
}
 
template <typename T>
inline Graph ConstGraphImpl<T>::GetGraphView(const std::vector<ConstNode>& nodes) const {
  OrtGraph* graph_viewer;
  std::vector<const OrtNode*> inputs_ptrs;
  inputs_ptrs.reserve(nodes.size());
  std::transform(nodes.begin(), nodes.end(), std::back_inserter(inputs_ptrs),
                 [](ConstNode n) -> const OrtNode* { return n; });
  ThrowOnError(GetApi().Graph_GetGraphView(this->p_, inputs_ptrs.data(),
                                           nodes.size(), &graph_viewer));
  return Graph{graph_viewer};
}
 
#if !defined(ORT_MINIMAL_BUILD)
template <typename T>
inline void GraphImpl<T>::SetInputs(std::vector<ValueInfo>& inputs) {
  std::vector<OrtValueInfo*> inputs_ptrs;
  inputs_ptrs.reserve(inputs.size());
  std::transform(inputs.begin(), inputs.end(), std::back_inserter(inputs_ptrs),
                 [](ValueInfo& vi) -> OrtValueInfo* { return vi; });
 
  ThrowOnError(GetModelEditorApi().SetGraphInputs(this->p_, inputs_ptrs.data(), inputs_ptrs.size()));
 
  // Graph now owns the inputs
  std::for_each(inputs.begin(), inputs.end(), [](ValueInfo& vi) { vi.release(); });
}
 
template <typename T>
inline void GraphImpl<T>::SetOutputs(std::vector<ValueInfo>& outputs) {
  std::vector<OrtValueInfo*> outputs_ptrs;
  outputs_ptrs.reserve(outputs.size());
  std::transform(outputs.begin(), outputs.end(), std::back_inserter(outputs_ptrs),
                 [](ValueInfo& vi) -> OrtValueInfo* { return vi; });
 
  ThrowOnError(GetModelEditorApi().SetGraphOutputs(this->p_, outputs_ptrs.data(), outputs_ptrs.size()));
 
  // Graph now owns the outputs
  std::for_each(outputs.begin(), outputs.end(), [](ValueInfo& vi) { vi.release(); });
}
 
template <typename T>
inline void GraphImpl<T>::AddInitializer(const std::string& name, Value& initializer, bool data_is_external) {
  // Graph takes ownership of `initializer`
  // On error the ownership is not transferred.
  ThrowOnError(GetModelEditorApi().AddInitializerToGraph(this->p_, name.c_str(), initializer, data_is_external));
  initializer.release();
}
 
template <typename T>
inline void GraphImpl<T>::AddNode(Node& node) {
  // Graph takes ownership of `node` only on success. Pass the raw pointer via implicit conversion
  // (which does not release the wrapper) so that on failure `node` still owns it; release after the
  // C call returns OK.
  ThrowOnError(GetModelEditorApi().AddNodeToGraph(this->p_, node));
  node.release();
}
 
template <typename T>
inline void ModelImpl<T>::AddGraph(Graph& graph) {
  // Model takes ownership of `graph` only on success. See AddNode for the rationale.
  ThrowOnError(GetModelEditorApi().AddGraphToModel(this->p_, graph));
  graph.release();
}
#endif  // !defined(ORT_MINIMAL_BUILD)
 
}  // namespace detail
 
#if !defined(ORT_MINIMAL_BUILD)
inline Graph::Graph() {
  ThrowOnError(GetModelEditorApi().CreateGraph(&p_));
}
 
inline Model::Model(const std::vector<DomainOpsetPair>& opsets) {
  std::vector<const char*> domains;
  std::vector<int> versions;
  domains.reserve(opsets.size());
  versions.reserve(opsets.size());
 
  for (const auto& pair : opsets) {
    domains.push_back(pair.first.c_str());
    versions.push_back(pair.second);
  }
 
  ThrowOnError(GetModelEditorApi().CreateModel(domains.data(), versions.data(), opsets.size(), &p_));
}
#endif
 
namespace detail {
template <typename T>
inline const char* ConstKernelDefImpl<T>::GetOperatorType() const {
  return GetEpApi().KernelDef_GetOperatorType(this->p_);
}
 
template <typename T>
inline const char* ConstKernelDefImpl<T>::GetDomain() const {
  return GetEpApi().KernelDef_GetDomain(this->p_);
}
 
template <typename T>
inline std::pair<int, int> ConstKernelDefImpl<T>::GetSinceVersion() const {
  int start = 0;
  int end = 0;
 
  ThrowOnError(GetEpApi().KernelDef_GetSinceVersion(this->p_, &start, &end));
  return std::pair<int, int>(start, end);
}
 
template <typename T>
inline const char* ConstKernelDefImpl<T>::GetExecutionProvider() const {
  return GetEpApi().KernelDef_GetExecutionProvider(this->p_);
}
 
template <typename T>
inline OrtMemType ConstKernelDefImpl<T>::GetInputMemType(size_t input_index) const {
  OrtMemType mem_type{};
  ThrowOnError(GetEpApi().KernelDef_GetInputMemType(this->p_, input_index, &mem_type));
 
  return mem_type;
}
 
template <typename T>
inline OrtMemType ConstKernelDefImpl<T>::GetOutputMemType(size_t output_index) const {
  OrtMemType mem_type{};
  ThrowOnError(GetEpApi().KernelDef_GetOutputMemType(this->p_, output_index, &mem_type));
 
  return mem_type;
}
}  // namespace detail
 
inline KernelDefBuilder::KernelDefBuilder() {
  ThrowOnError(GetEpApi().CreateKernelDefBuilder(&p_));
}
 
inline KernelDefBuilder::KernelDefBuilder(OrtKernelDefBuilder* p) : detail::Base<OrtKernelDefBuilder>{p} {
}
 
inline KernelDefBuilder& KernelDefBuilder::SetOperatorType(const char* op_type) {
  ThrowOnError(GetEpApi().KernelDefBuilder_SetOperatorType(p_, op_type));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::SetDomain(const char* domain) {
  ThrowOnError(GetEpApi().KernelDefBuilder_SetDomain(p_, domain));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::SetSinceVersion(int since_version_start, int since_version_end) {
  ThrowOnError(GetEpApi().KernelDefBuilder_SetSinceVersion(p_, since_version_start, since_version_end));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::SetExecutionProvider(const char* ep_name) {
  ThrowOnError(GetEpApi().KernelDefBuilder_SetExecutionProvider(p_, ep_name));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::SetInputMemType(size_t input_index, OrtMemType mem_type) {
  ThrowOnError(GetEpApi().KernelDefBuilder_SetInputMemType(p_, input_index, mem_type));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::SetOutputMemType(size_t output_index, OrtMemType mem_type) {
  ThrowOnError(GetEpApi().KernelDefBuilder_SetOutputMemType(p_, output_index, mem_type));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::AddTypeConstraint(const char* arg_name,
                                                             const OrtDataType* data_type) {
  ThrowOnError(GetEpApi().KernelDefBuilder_AddTypeConstraint(p_, arg_name, &data_type, 1));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::AddTypeConstraint(const char* arg_name,
                                                             const std::vector<const OrtDataType*>& data_types) {
  ThrowOnError(GetEpApi().KernelDefBuilder_AddTypeConstraint(p_, arg_name, data_types.data(), data_types.size()));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::AddInputOutputAlias(int input_index, int output_index) {
  ThrowOnError(GetEpApi().KernelDefBuilder_AddInputOutputAliases(p_, &input_index, &output_index, 1));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::AddInputOutputAliases(const std::vector<int>& input_indices,
                                                                 const std::vector<int>& output_indices) {
  if (input_indices.size() != output_indices.size()) {
    ORT_CXX_API_THROW("Expecting input and output indices to have the same element count", ORT_INVALID_ARGUMENT);
  }
 
  ThrowOnError(GetEpApi().KernelDefBuilder_AddInputOutputAliases(p_, input_indices.data(), output_indices.data(),
                                                                 input_indices.size()));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::AddInputOutputMutableAlias(int input_index, int output_index) {
  ThrowOnError(GetEpApi().KernelDefBuilder_AddInputOutputMutableAliases(p_, &input_index, &output_index, 1));
  return *this;
}
 
inline KernelDefBuilder& KernelDefBuilder::AddInputOutputMutableAliases(const std::vector<int>& input_indices,
                                                                        const std::vector<int>& output_indices) {
  if (input_indices.size() != output_indices.size()) {
    ORT_CXX_API_THROW("Expecting input and output indices to have the same element count", ORT_INVALID_ARGUMENT);
  }
 
  ThrowOnError(GetEpApi().KernelDefBuilder_AddInputOutputMutableAliases(p_, input_indices.data(), output_indices.data(),
                                                                        input_indices.size()));
  return *this;
}
 
inline KernelDef KernelDefBuilder::Build() {
  OrtKernelDef* kernel_def = nullptr;
  ThrowOnError(GetEpApi().KernelDefBuilder_Build(p_, &kernel_def));
  return KernelDef(kernel_def);
}
 
inline KernelRegistry::KernelRegistry() {
  ThrowOnError(GetEpApi().CreateKernelRegistry(&p_));
}
 
inline KernelRegistry::KernelRegistry(OrtKernelRegistry* p) : detail::Base<OrtKernelRegistry>{p} {
}
 
inline Status KernelRegistry::AddKernel(const OrtKernelDef* kernel_def, OrtKernelCreateFunc kernel_create_func,
                                        void* kernel_create_func_state) {
  return Status{GetEpApi().KernelRegistry_AddKernel(p_, kernel_def, kernel_create_func, kernel_create_func_state)};
}
 
namespace detail {
template <typename T>
inline Status SharedPrePackedWeightCacheImpl<T>::StoreWeightData(void** buffer_data_ptrs, size_t* buffer_sizes,
                                                                 size_t num_buffers) {
  return Status{GetEpApi().SharedPrePackedWeightCache_StoreWeightData(this->p_, buffer_data_ptrs, buffer_sizes,
                                                                      num_buffers)};
}
}  // namespace detail
 
inline Ort::KeyValuePairs GetEnvConfigEntries() {
  OrtKeyValuePairs* entries = nullptr;
  Ort::ThrowOnError(GetEpApi().GetEnvConfigEntries(&entries));
 
  return Ort::KeyValuePairs{entries};
}
 
namespace detail {
template <typename T>
inline int OpSchemaImpl<T>::GetSinceVersion() const {
  int version = 0;
  ThrowOnError(GetEpApi().OpSchema_GetSinceVersion(this->p_, &version));
  return version;
}
 
template <typename T>
inline size_t OpSchemaImpl<T>::GetNumInputs() const {
  size_t num = 0;
  ThrowOnError(GetEpApi().OpSchema_GetNumInputs(this->p_, &num));
  return num;
}
 
template <typename T>
inline std::string OpSchemaImpl<T>::GetInputName(size_t index) const {
  const char* name = nullptr;
  ThrowOnError(GetEpApi().OpSchema_GetInputName(this->p_, index, &name));
  return std::string(name);
}
 
template <typename T>
inline Ort::ConstOpSchemaTypeConstraint OpSchemaImpl<T>::GetInputTypeConstraint(size_t index) const {
  const OrtOpSchemaTypeConstraint* tc = nullptr;
  ThrowOnError(GetEpApi().OpSchema_GetInputTypeConstraint(this->p_, index, &tc));
  return Ort::ConstOpSchemaTypeConstraint{tc};
}
 
template <typename T>
inline size_t OpSchemaImpl<T>::GetNumOutputs() const {
  size_t num = 0;
  ThrowOnError(GetEpApi().OpSchema_GetNumOutputs(this->p_, &num));
  return num;
}
 
template <typename T>
inline std::string OpSchemaImpl<T>::GetOutputName(size_t index) const {
  const char* name = nullptr;
  ThrowOnError(GetEpApi().OpSchema_GetOutputName(this->p_, index, &name));
  return std::string(name);
}
 
template <typename T>
inline Ort::ConstOpSchemaTypeConstraint OpSchemaImpl<T>::GetOutputTypeConstraint(size_t index) const {
  const OrtOpSchemaTypeConstraint* tc = nullptr;
  ThrowOnError(GetEpApi().OpSchema_GetOutputTypeConstraint(this->p_, index, &tc));
  return Ort::ConstOpSchemaTypeConstraint{tc};
}
 
template <typename T>
inline size_t OpSchemaImpl<T>::GetTypeConstraintCount() const {
  size_t count = 0;
  ThrowOnError(GetEpApi().OpSchema_GetTypeConstraintCount(this->p_, &count));
  return count;
}
 
template <typename T>
inline Ort::ConstOpSchemaTypeConstraint OpSchemaImpl<T>::GetTypeConstraint(size_t index) const {
  const OrtOpSchemaTypeConstraint* tc = nullptr;
  ThrowOnError(GetEpApi().OpSchema_GetTypeConstraint(this->p_, index, &tc));
  return Ort::ConstOpSchemaTypeConstraint{tc};
}
 
template <typename T>
inline std::string OpSchemaTypeConstraintImpl<T>::GetTypeParamName() const {
  const char* name = nullptr;
  ThrowOnError(GetEpApi().OpSchemaTypeConstraint_GetTypeParamName(this->p_, &name));
  return std::string(name);
}
 
template <typename T>
inline std::vector<std::string> OpSchemaTypeConstraintImpl<T>::GetAllowedTypes() const {
  const char* const* types = nullptr;
  size_t num_types = 0;
  ThrowOnError(GetEpApi().OpSchemaTypeConstraint_GetAllowedTypes(this->p_, &types, &num_types));
  std::vector<std::string> result;
  result.reserve(num_types);
  for (size_t i = 0; i < num_types; ++i) {
    result.emplace_back(types[i]);
  }
  return result;
}
 
template <typename T>
inline std::vector<size_t> OpSchemaTypeConstraintImpl<T>::GetInputIndices() const {
  const size_t* indices = nullptr;
  size_t count = 0;
  ThrowOnError(GetEpApi().OpSchemaTypeConstraint_GetInputIndices(this->p_, &indices, &count));
  if (count == 0) return {};
  return std::vector<size_t>(indices, indices + count);
}
 
template <typename T>
inline std::vector<size_t> OpSchemaTypeConstraintImpl<T>::GetOutputIndices() const {
  const size_t* indices = nullptr;
  size_t count = 0;
  ThrowOnError(GetEpApi().OpSchemaTypeConstraint_GetOutputIndices(this->p_, &indices, &count));
  if (count == 0) return {};
  return std::vector<size_t>(indices, indices + count);
}
}  // namespace detail
 
inline OpSchema GetOpSchema(const char* name, int max_inclusive_version, const char* domain) {
  OrtOpSchema* schema = nullptr;
  ThrowOnError(GetEpApi().GetOpSchema(name, max_inclusive_version, domain, &schema));
  return OpSchema{schema};
}
 
}  // namespace Ort