sparse-ir-capi 0.9.0

C API for SparseIR Rust implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
//! Basis API
//!
//! Functions for creating and manipulating finite temperature basis objects.

use std::panic::{AssertUnwindSafe, catch_unwind};

use sparse_ir::basis::FiniteTempBasis;

use crate::types::{spir_basis, spir_funcs, spir_kernel, spir_sve_result};
use crate::{
    SPIR_COMPUTATION_SUCCESS, SPIR_INTERNAL_ERROR, SPIR_INVALID_ARGUMENT, SPIR_NOT_SUPPORTED,
    SPIR_STATISTICS_BOSONIC, SPIR_STATISTICS_FERMIONIC, StatusCode,
};

/// Manual release function (replaces macro-generated one)
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_release(basis: *mut spir_basis) {
    if !basis.is_null() {
        unsafe {
            let _ = Box::from_raw(basis);
        }
    }
}

/// Manual clone function (replaces macro-generated one)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn spir_basis_clone(src: *const spir_basis) -> *mut spir_basis {
    if src.is_null() {
        return std::ptr::null_mut();
    }

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe {
        let src_ref = &*src;
        let cloned = (*src_ref).clone();
        Box::into_raw(Box::new(cloned))
    }));

    result.unwrap_or(std::ptr::null_mut())
}

/// Check if the basis pointer is non-null.
///
/// Note: This only performs a null check. It cannot detect dangling
/// pointers; dereferencing an arbitrary non-null pointer would be
/// undefined behaviour that `catch_unwind` cannot reliably catch.
///
/// # Returns
/// 1 if the pointer is non-null, 0 otherwise
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_is_assigned(obj: *const spir_basis) -> i32 {
    if obj.is_null() { 0 } else { 1 }
}

/// Create a finite temperature basis (libsparseir compatible)
///
/// # Arguments
/// * `statistics` - 0 for Bosonic, 1 for Fermionic
/// * `beta` - Inverse temperature (must be > 0)
/// * `omega_max` - Frequency cutoff (must be > 0)
/// * `epsilon` - Accuracy target (must be > 0)
/// * `k` - Kernel object (can be NULL if sve is provided)
/// * `sve` - Pre-computed SVE result (can be NULL, will compute if needed)
/// * `max_size` - Maximum basis size (-1 for no limit)
/// * `status` - Pointer to store status code
///
/// # Returns
/// * Pointer to basis object, or NULL on failure
///
/// # Safety
/// The caller must ensure `status` is a valid pointer.
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_new(
    statistics: libc::c_int,
    beta: f64,
    omega_max: f64,
    epsilon: f64,
    k: *const spir_kernel,
    sve: *const spir_sve_result,
    max_size: libc::c_int,
    status: *mut StatusCode,
) -> *mut spir_basis {
    if status.is_null() {
        return std::ptr::null_mut();
    }

    // Validate inputs
    if beta <= 0.0
        || omega_max <= 0.0
        || epsilon <= 0.0
        || !beta.is_finite()
        || !omega_max.is_finite()
        || !epsilon.is_finite()
    {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    // Validate statistics
    if statistics != SPIR_STATISTICS_BOSONIC && statistics != SPIR_STATISTICS_FERMIONIC {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    // Must have kernel (SVE can be provided for optimization but kernel is required for type info)
    if k.is_null() {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    // Convert max_size
    let max_size_opt = if max_size < 0 {
        None
    } else {
        Some(max_size as usize)
    };

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let kernel_ref = &*k;

        // Check that kernel's lambda matches beta * omega_max
        let expected_lambda = beta * omega_max;
        let kernel_lambda = kernel_ref.lambda();
        if (kernel_lambda - expected_lambda).abs() > 1e-10 {
            return Err(SPIR_INVALID_ARGUMENT);
        }

        // Dispatch based on kernel type and statistics
        if let Some(logistic) = kernel_ref.as_logistic() {
            if statistics == SPIR_STATISTICS_FERMIONIC {
                // Fermionic
                let basis: FiniteTempBasis<_, _> = if !sve.is_null() {
                    let sve_ref = &*sve;
                    FiniteTempBasis::from_sve_result(
                        **logistic,
                        beta,
                        sve_ref.inner().as_ref().clone(),
                        Some(epsilon),
                        max_size_opt,
                    )
                } else {
                    FiniteTempBasis::new(**logistic, beta, Some(epsilon), max_size_opt)
                };
                Ok(Box::into_raw(Box::new(spir_basis::new_logistic_fermionic(
                    basis,
                ))))
            } else {
                // Bosonic
                let basis: FiniteTempBasis<_, _> = if !sve.is_null() {
                    let sve_ref = &*sve;
                    FiniteTempBasis::from_sve_result(
                        **logistic,
                        beta,
                        sve_ref.inner().as_ref().clone(),
                        Some(epsilon),
                        max_size_opt,
                    )
                } else {
                    FiniteTempBasis::new(**logistic, beta, Some(epsilon), max_size_opt)
                };
                Ok(Box::into_raw(Box::new(spir_basis::new_logistic_bosonic(
                    basis,
                ))))
            }
        } else if let Some(reg_bose) = kernel_ref.as_regularized_bose() {
            if statistics == SPIR_STATISTICS_FERMIONIC {
                // RegularizedBoseKernel is meaningful only for bosonic statistics;
                // reject the combination at the boundary (the fermionic
                // regularizer would panic downstream when building a DLR).
                return Err(SPIR_NOT_SUPPORTED);
            } else {
                // Bosonic
                let basis: FiniteTempBasis<_, _> = if !sve.is_null() {
                    let sve_ref = &*sve;
                    FiniteTempBasis::from_sve_result(
                        **reg_bose,
                        beta,
                        sve_ref.inner().as_ref().clone(),
                        Some(epsilon),
                        max_size_opt,
                    )
                } else {
                    FiniteTempBasis::new(**reg_bose, beta, Some(epsilon), max_size_opt)
                };
                Ok(Box::into_raw(Box::new(
                    spir_basis::new_regularized_bose_bosonic(basis),
                )))
            }
        } else {
            Err(SPIR_INTERNAL_ERROR)
        }
    }));

    match result {
        Ok(Ok(ptr)) => {
            unsafe {
                *status = SPIR_COMPUTATION_SUCCESS;
            }
            ptr
        }
        Ok(Err(code)) => {
            unsafe {
                *status = code;
            }
            std::ptr::null_mut()
        }
        Err(_) => {
            unsafe {
                *status = SPIR_INTERNAL_ERROR;
            }
            std::ptr::null_mut()
        }
    }
}

/// Create a finite temperature basis from SVE result and custom regularizer function
///
/// This function creates a basis from a pre-computed SVE result and a custom
/// regularizer function. The regularizer function is used to scale the basis
/// functions in the frequency domain.
///
/// # Arguments
/// * `statistics` - 0 for Bosonic, 1 for Fermionic
/// * `beta` - Inverse temperature (must be > 0)
/// * `omega_max` - Frequency cutoff (must be > 0)
/// * `epsilon` - Accuracy target (must be > 0)
/// * `lambda` - Kernel parameter Λ = β * ωmax (must be > 0)
/// * `ypower` - Power of y in kernel: 0 for `LogisticKernel`, 1 for `RegularizedBoseKernel`.
///              Other values return `SPIR_INVALID_ARGUMENT`.
/// * `conv_radius` - Convergence radius for Fourier transform (currently unused)
/// * `sve` - Pre-computed SVE result (must not be NULL)
/// * `regularizer_funcs` - Custom regularizer function (must not be NULL)
/// * `max_size` - Maximum basis size (-1 for no limit)
/// * `status` - Pointer to store status code
///
/// # Returns
/// * Pointer to basis object, or NULL on failure
///
/// # Note
/// The kernel type is determined by `ypower`: 0 selects `LogisticKernel`, 1 selects
/// `RegularizedBoseKernel`. The regularizer function is evaluated for validity but
/// the custom weight is not yet fully integrated into basis construction.
///
/// # Safety
/// The caller must ensure `status` is a valid pointer.
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_new_from_sve_and_regularizer(
    statistics: libc::c_int,
    beta: f64,
    omega_max: f64,
    epsilon: f64,
    lambda: f64,
    ypower: libc::c_int,
    _conv_radius: f64,
    sve: *const spir_sve_result,
    regularizer_funcs: *const spir_funcs,
    max_size: libc::c_int,
    status: *mut StatusCode,
) -> *mut spir_basis {
    if status.is_null() {
        return std::ptr::null_mut();
    }

    // Validate inputs
    if beta <= 0.0
        || omega_max <= 0.0
        || epsilon <= 0.0
        || lambda <= 0.0
        || !beta.is_finite()
        || !omega_max.is_finite()
        || !epsilon.is_finite()
        || !lambda.is_finite()
    {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    // Validate statistics
    if statistics != SPIR_STATISTICS_BOSONIC && statistics != SPIR_STATISTICS_FERMIONIC {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    // Must have SVE and regularizer_funcs
    if sve.is_null() || regularizer_funcs.is_null() {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    // Check that lambda matches beta * omega_max
    let expected_lambda = beta * omega_max;
    if (lambda - expected_lambda).abs() > 1e-10 {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    // Validate ypower: 0 => LogisticKernel, 1 => RegularizedBoseKernel
    if ypower != 0 && ypower != 1 {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    // Convert max_size
    let max_size_opt = if max_size < 0 {
        None
    } else {
        Some(max_size as usize)
    };

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let sve_ref = &*sve;
        let sve_result = sve_ref.inner().as_ref().clone();

        // Evaluate regularizer_funcs at a test point to verify it's valid
        // (Note: Currently, the custom regularizer is not fully integrated into basis construction)
        let test_omega = omega_max / 2.0;
        let _regularizer_value = match (*regularizer_funcs).eval_continuous(test_omega) {
            Some(values) if !values.is_empty() => values[0],
            _ => {
                // Default to 1.0 if evaluation fails
                1.0
            }
        };

        // Select kernel type based on ypower:
        //   ypower == 0 => LogisticKernel
        //   ypower == 1 => RegularizedBoseKernel
        if ypower == 0 {
            use sparse_ir::kernel::LogisticKernel;
            let kernel = LogisticKernel::new(lambda);

            if statistics == SPIR_STATISTICS_FERMIONIC {
                let basis =
                    FiniteTempBasis::<LogisticKernel, sparse_ir::traits::Fermionic>::from_sve_result(
                        kernel,
                        beta,
                        sve_result,
                        Some(epsilon),
                        max_size_opt,
                    );
                Ok::<*mut spir_basis, StatusCode>(Box::into_raw(Box::new(
                    spir_basis::new_logistic_fermionic(basis),
                )))
            } else {
                let basis =
                    FiniteTempBasis::<LogisticKernel, sparse_ir::traits::Bosonic>::from_sve_result(
                        kernel,
                        beta,
                        sve_result,
                        Some(epsilon),
                        max_size_opt,
                    );
                Ok::<*mut spir_basis, StatusCode>(Box::into_raw(Box::new(
                    spir_basis::new_logistic_bosonic(basis),
                )))
            }
        } else {
            // ypower == 1: RegularizedBoseKernel is meaningful only for bosonic
            // statistics; reject the combination at the boundary (the fermionic
            // regularizer would panic downstream when building a DLR).
            if statistics == SPIR_STATISTICS_FERMIONIC {
                return Err(SPIR_NOT_SUPPORTED);
            } else {
                use sparse_ir::kernel::RegularizedBoseKernel;
                let kernel = RegularizedBoseKernel::new(lambda);

                let basis =
                    FiniteTempBasis::<RegularizedBoseKernel, sparse_ir::traits::Bosonic>::from_sve_result(
                        kernel,
                        beta,
                        sve_result,
                        Some(epsilon),
                        max_size_opt,
                    );
                Ok::<*mut spir_basis, StatusCode>(Box::into_raw(Box::new(
                    spir_basis::new_regularized_bose_bosonic(basis),
                )))
            }
        }
    }));

    match result {
        Ok(Ok(ptr)) => {
            unsafe {
                *status = SPIR_COMPUTATION_SUCCESS;
            }
            ptr
        }
        Ok(Err(code)) => {
            unsafe {
                *status = code;
            }
            std::ptr::null_mut()
        }
        Err(_) => {
            unsafe {
                *status = SPIR_INTERNAL_ERROR;
            }
            std::ptr::null_mut()
        }
    }
}

/// Get the number of basis functions
///
/// # Arguments
/// * `b` - Basis object
/// * `size` - Pointer to store the size
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if b or size is null
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_size(b: *const spir_basis, size: *mut libc::c_int) -> StatusCode {
    if b.is_null() || size.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        *size = basis.size() as libc::c_int;
        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Get singular values from a basis
///
/// # Arguments
/// * `b` - Basis object
/// * `svals` - Pre-allocated array to store singular values (size must be >= basis size)
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if b or svals is null
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_svals(b: *const spir_basis, svals: *mut f64) -> StatusCode {
    use std::io::Write;

    if b.is_null() || svals.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let sval_vec = basis.svals();
        debug_println!("spir_basis_get_svals: sval_vec.len() = {}", sval_vec.len());
        std::io::stderr().flush().unwrap();

        // Safety: We assume the caller has allocated enough memory
        // The size should match basis.size() which is checked by Julia side
        if sval_vec.len() > 0 {
            std::ptr::copy_nonoverlapping(sval_vec.as_ptr(), svals, sval_vec.len());
        }
        SPIR_COMPUTATION_SUCCESS
    }));

    match result {
        Ok(code) => code,
        Err(panic_payload) => {
            use std::io::Write;
            debug_eprintln!("Panic in spir_basis_get_svals");
            std::io::stderr().flush().unwrap();
            if let Some(s) = panic_payload.downcast_ref::<String>() {
                debug_eprintln!("Panic message: {}", s);
            } else if let Some(s) = panic_payload.downcast_ref::<&str>() {
                debug_eprintln!("Panic message: {}", s);
            }
            std::io::stderr().flush().unwrap();
            SPIR_INTERNAL_ERROR
        }
    }
}

/// Get statistics type (Fermionic or Bosonic) of a basis
///
/// # Arguments
/// * `b` - Basis object
/// * `statistics` - Pointer to store statistics (0 = Bosonic, 1 = Fermionic)
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if b or statistics is null
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_stats(
    b: *const spir_basis,
    statistics: *mut libc::c_int,
) -> StatusCode {
    if b.is_null() || statistics.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        *statistics = basis.statistics();
        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Get singular values (alias for spir_basis_get_svals for libsparseir compatibility)
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_singular_values(
    b: *const spir_basis,
    svals: *mut f64,
) -> StatusCode {
    spir_basis_get_svals(b, svals)
}

/// Get the number of default tau sampling points
///
/// # Arguments
/// * `b` - Basis object
/// * `num_points` - Pointer to store the number of points
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if b or num_points is null
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_n_default_taus(
    b: *const spir_basis,
    num_points: *mut libc::c_int,
) -> StatusCode {
    if b.is_null() || num_points.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let points = basis.default_tau_sampling_points();
        *num_points = points.len() as libc::c_int;
        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Get default tau sampling points
///
/// # Arguments
/// * `b` - Basis object
/// * `points` - Pre-allocated array to store tau points
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if b or points is null
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_default_taus(
    b: *const spir_basis,
    points: *mut f64,
) -> StatusCode {
    if b.is_null() || points.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let tau_points = basis.default_tau_sampling_points();
        std::ptr::copy_nonoverlapping(tau_points.as_ptr(), points, tau_points.len());
        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Get the number of default Matsubara sampling points
///
/// # Arguments
/// * `b` - Basis object
/// * `positive_only` - If true, return only positive frequencies
/// * `num_points` - Pointer to store the number of points
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if b or num_points is null
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_n_default_matsus(
    b: *const spir_basis,
    positive_only: bool,
    num_points: *mut libc::c_int,
) -> StatusCode {
    if b.is_null() || num_points.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let points = basis.default_matsubara_sampling_points(positive_only);
        *num_points = points.len() as libc::c_int;
        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Get default Matsubara sampling points
///
/// # Arguments
/// * `b` - Basis object
/// * `positive_only` - If true, return only positive frequencies
/// * `points` - Pre-allocated array to store Matsubara indices
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if b or points is null
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_default_matsus(
    b: *const spir_basis,
    positive_only: bool,
    points: *mut i64,
) -> StatusCode {
    if b.is_null() || points.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let matsu_points = basis.default_matsubara_sampling_points(positive_only);
        std::ptr::copy_nonoverlapping(matsu_points.as_ptr(), points, matsu_points.len());
        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Gets the basis functions in imaginary time (Ï„) domain
///
/// # Arguments
/// * `b` - Pointer to the finite temperature basis object
/// * `status` - Pointer to store the status code
///
/// # Returns
/// Pointer to the basis functions object (`spir_funcs`), or NULL if creation fails
///
/// # Safety
/// The caller must ensure that `b` is a valid pointer, and must call
/// `spir_funcs_release()` on the returned pointer when done.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn spir_basis_get_u(
    b: *const spir_basis,
    status: *mut StatusCode,
) -> *mut spir_funcs {
    use crate::types::{BasisType, spir_funcs};
    use std::panic::catch_unwind;

    if status.is_null() {
        return std::ptr::null_mut();
    }

    if b.is_null() {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis_ref = &*b;
        let beta = basis_ref.beta();

        let funcs = match basis_ref.inner() {
            BasisType::LogisticFermionic(basis) => {
                spir_funcs::from_u_fermionic(basis.u().clone(), beta)
            }
            BasisType::LogisticBosonic(basis) => {
                spir_funcs::from_u_bosonic(basis.u().clone(), beta)
            }
            BasisType::RegularizedBoseFermionic(basis) => {
                spir_funcs::from_u_fermionic(basis.u().clone(), beta)
            }
            BasisType::RegularizedBoseBosonic(basis) => {
                spir_funcs::from_u_bosonic(basis.u().clone(), beta)
            }
            // DLR: tau-domain functions using kernel-aware pole weights
            BasisType::DLRFermionic(dlr) => spir_funcs::from_dlr_tau_fermionic(
                dlr.poles.clone(),
                beta,
                dlr.wmax,
                dlr.pole_weights().to_vec(),
                dlr.kernel_ypower(),
            ),
            BasisType::DLRBosonic(dlr) => spir_funcs::from_dlr_tau_bosonic(
                dlr.poles.clone(),
                beta,
                dlr.wmax,
                dlr.pole_weights().to_vec(),
                dlr.kernel_ypower(),
            ),
        };

        Result::<*mut spir_funcs, String>::Ok(Box::into_raw(Box::new(funcs)))
    }));

    match result {
        Ok(Ok(ptr)) => {
            unsafe {
                *status = SPIR_COMPUTATION_SUCCESS;
            }
            ptr
        }
        Ok(Err(msg)) => {
            debug_eprintln!("Error in spir_basis_get_u: {}", msg);
            unsafe {
                *status = SPIR_INTERNAL_ERROR;
            }
            std::ptr::null_mut()
        }
        Err(_) => {
            unsafe {
                *status = SPIR_INTERNAL_ERROR;
            }
            std::ptr::null_mut()
        }
    }
}

/// Gets the basis functions in real frequency (ω) domain
///
/// # Arguments
/// * `b` - Pointer to the finite temperature basis object
/// * `status` - Pointer to store the status code
///
/// # Returns
/// Pointer to the basis functions object (`spir_funcs`), or NULL if creation fails
///
/// # Safety
/// The caller must ensure that `b` is a valid pointer, and must call
/// `spir_funcs_release()` on the returned pointer when done.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn spir_basis_get_v(
    b: *const spir_basis,
    status: *mut StatusCode,
) -> *mut spir_funcs {
    use crate::types::{BasisType, spir_funcs};
    use std::panic::catch_unwind;

    if status.is_null() {
        return std::ptr::null_mut();
    }

    if b.is_null() {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis_ref = &*b;
        let beta = basis_ref.beta();

        let funcs = match basis_ref.inner() {
            BasisType::LogisticFermionic(basis) => spir_funcs::from_v(basis.v().clone(), beta),
            BasisType::LogisticBosonic(basis) => spir_funcs::from_v(basis.v().clone(), beta),
            BasisType::RegularizedBoseFermionic(basis) => {
                spir_funcs::from_v(basis.v().clone(), beta)
            }
            BasisType::RegularizedBoseBosonic(basis) => spir_funcs::from_v(basis.v().clone(), beta),
            // DLR: no continuous functions (v)
            BasisType::DLRFermionic(_) | BasisType::DLRBosonic(_) => {
                return Result::<*mut spir_funcs, String>::Err(
                    "DLR does not support continuous functions".to_string(),
                );
            }
        };

        Result::<*mut spir_funcs, String>::Ok(Box::into_raw(Box::new(funcs)))
    }));

    match result {
        Ok(Ok(ptr)) => {
            unsafe {
                *status = SPIR_COMPUTATION_SUCCESS;
            }
            ptr
        }
        Ok(Err(msg)) => {
            debug_eprintln!("Error in spir_basis_get_v: {}", msg);
            unsafe {
                *status = SPIR_INTERNAL_ERROR;
            }
            std::ptr::null_mut()
        }
        Err(_) => {
            unsafe {
                *status = SPIR_INTERNAL_ERROR;
            }
            std::ptr::null_mut()
        }
    }
}

/// Gets the number of default omega (real frequency) sampling points
///
/// # Arguments
/// * `b` - Pointer to the finite temperature basis object
/// * `num_points` - Pointer to store the number of sampling points
///
/// # Returns
/// Status code (SPIR_COMPUTATION_SUCCESS on success)
///
/// # Safety
/// The caller must ensure that `b` and `num_points` are valid pointers
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_n_default_ws(
    b: *const spir_basis,
    num_points: *mut libc::c_int,
) -> StatusCode {
    if b.is_null() || num_points.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let omega_points = basis.default_omega_sampling_points();
        *num_points = omega_points.len() as libc::c_int;
        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Gets the default omega (real frequency) sampling points
///
/// # Arguments
/// * `b` - Pointer to the finite temperature basis object
/// * `points` - Pre-allocated array to store the omega sampling points
///
/// # Returns
/// Status code (SPIR_COMPUTATION_SUCCESS on success)
///
/// # Safety
/// The caller must ensure that `points` has size >= `spir_basis_get_n_default_ws(b)`
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_default_ws(b: *const spir_basis, points: *mut f64) -> StatusCode {
    if b.is_null() || points.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let omega_points = basis.default_omega_sampling_points();
        std::ptr::copy_nonoverlapping(omega_points.as_ptr(), points, omega_points.len());
        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Gets the basis functions in Matsubara frequency domain
///
/// # Arguments
/// * `b` - Pointer to the finite temperature basis object
/// * `status` - Pointer to store the status code
///
/// # Returns
/// Pointer to the basis functions object (`spir_funcs`), or NULL if creation fails
///
/// # Safety
/// The caller must ensure that `b` is a valid pointer, and must call
/// `spir_funcs_release()` on the returned pointer when done.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn spir_basis_get_uhat(
    b: *const spir_basis,
    status: *mut StatusCode,
) -> *mut spir_funcs {
    use crate::types::{BasisType, spir_funcs};
    use std::panic::catch_unwind;

    if status.is_null() {
        return std::ptr::null_mut();
    }

    if b.is_null() {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis_ref = &*b;
        let beta = basis_ref.beta();

        let funcs = match basis_ref.inner() {
            BasisType::LogisticFermionic(basis) => {
                spir_funcs::from_uhat_fermionic(basis.uhat().clone(), beta)
            }
            BasisType::LogisticBosonic(basis) => {
                spir_funcs::from_uhat_bosonic(basis.uhat().clone(), beta)
            }
            BasisType::RegularizedBoseFermionic(basis) => {
                spir_funcs::from_uhat_fermionic(basis.uhat().clone(), beta)
            }
            BasisType::RegularizedBoseBosonic(basis) => {
                spir_funcs::from_uhat_bosonic(basis.uhat().clone(), beta)
            }
            // DLR: Matsubara-domain functions using discrete poles
            BasisType::DLRFermionic(dlr) => spir_funcs::from_dlr_matsubara_fermionic(
                dlr.poles.clone(),
                beta,
                dlr.wmax,
                dlr.pole_weights().to_vec(),
                dlr.kernel_ypower(),
            ),
            BasisType::DLRBosonic(dlr) => spir_funcs::from_dlr_matsubara_bosonic(
                dlr.poles.clone(),
                beta,
                dlr.wmax,
                dlr.pole_weights().to_vec(),
                dlr.kernel_ypower(),
            ),
        };

        Result::<*mut spir_funcs, String>::Ok(Box::into_raw(Box::new(funcs)))
    }));

    match result {
        Ok(Ok(ptr)) => {
            unsafe {
                *status = SPIR_COMPUTATION_SUCCESS;
            }
            ptr
        }
        Ok(Err(msg)) => {
            debug_eprintln!("Error in spir_basis_get_uhat: {}", msg);
            unsafe {
                *status = SPIR_INTERNAL_ERROR;
            }
            std::ptr::null_mut()
        }
        Err(_) => {
            unsafe {
                *status = SPIR_INTERNAL_ERROR;
            }
            std::ptr::null_mut()
        }
    }
}

/// Gets the full (untruncated) Matsubara-frequency basis functions
///
/// This function returns an object representing all basis functions
/// in the Matsubara-frequency domain, including those beyond the truncation
/// threshold. Unlike `spir_basis_get_uhat`, which returns only the truncated
/// basis functions (up to `basis.size()`), this function returns all basis
/// functions from the SVE result (up to `sve_result.s.size()`).
///
/// # Arguments
/// * `b` - Pointer to the finite temperature basis object (must be an IR basis)
/// * `status` - Pointer to store the status code
///
/// # Returns
/// Pointer to the basis functions object, or NULL if creation fails
///
/// # Note
/// The returned object must be freed using `spir_funcs_release`
/// when no longer needed
/// This function is only available for IR basis objects (not DLR)
/// uhat_full.size() >= uhat.size() is always true
/// The first uhat.size() functions in uhat_full are identical to uhat
///
/// # Safety
/// The caller must ensure that `b` is a valid pointer, and must call
/// `spir_funcs_release()` on the returned pointer when done.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn spir_basis_get_uhat_full(
    b: *const spir_basis,
    status: *mut StatusCode,
) -> *mut spir_funcs {
    use crate::SPIR_NOT_SUPPORTED;
    use crate::types::{BasisType, spir_funcs};
    use std::panic::catch_unwind;

    if status.is_null() {
        return std::ptr::null_mut();
    }

    if b.is_null() {
        unsafe {
            *status = SPIR_INVALID_ARGUMENT;
        }
        return std::ptr::null_mut();
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis_ref = &*b;
        let beta = basis_ref.beta();

        let funcs = match basis_ref.inner() {
            BasisType::LogisticFermionic(basis) => {
                spir_funcs::from_uhat_full_fermionic(basis.uhat_full().clone(), beta)
            }
            BasisType::LogisticBosonic(basis) => {
                spir_funcs::from_uhat_full_bosonic(basis.uhat_full().clone(), beta)
            }
            BasisType::RegularizedBoseFermionic(basis) => {
                spir_funcs::from_uhat_full_fermionic(basis.uhat_full().clone(), beta)
            }
            BasisType::RegularizedBoseBosonic(basis) => {
                spir_funcs::from_uhat_full_bosonic(basis.uhat_full().clone(), beta)
            }
            // DLR: not supported (only IR basis has uhat_full)
            BasisType::DLRFermionic(_) | BasisType::DLRBosonic(_) => {
                return Result::<*mut spir_funcs, String>::Err(
                    "uhat_full is only available for IR basis, not DLR".to_string(),
                );
            }
        };

        Result::<*mut spir_funcs, String>::Ok(Box::into_raw(Box::new(funcs)))
    }));

    match result {
        Ok(Ok(ptr)) => {
            unsafe {
                *status = SPIR_COMPUTATION_SUCCESS;
            }
            ptr
        }
        Ok(Err(msg)) => {
            debug_eprintln!("Error in spir_basis_get_uhat_full: {}", msg);
            unsafe {
                *status = SPIR_NOT_SUPPORTED;
            }
            std::ptr::null_mut()
        }
        Err(_) => {
            unsafe {
                *status = SPIR_INTERNAL_ERROR;
            }
            std::ptr::null_mut()
        }
    }
}

/// Get default tau sampling points with custom limit (extended version)
///
/// # Arguments
/// * `b` - Basis object
/// * `n_points` - Maximum number of points requested
/// * `points` - Pre-allocated array to store tau points (size >= n_points)
/// * `n_points_returned` - Pointer to store actual number of points returned
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if any pointer is null or n_points < 0
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
///
/// # Note
/// Returns min(n_points, actual_default_points) sampling points
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_default_taus_ext(
    b: *const spir_basis,
    n_points: libc::c_int,
    points: *mut f64,
    n_points_returned: *mut libc::c_int,
) -> StatusCode {
    if b.is_null() || points.is_null() || n_points_returned.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    if n_points < 0 {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let tau_points = basis.default_tau_sampling_points_size_requested(n_points as usize);

        // Return min(requested, available) points
        let n_to_return = std::cmp::min(n_points as usize, tau_points.len());
        std::ptr::copy_nonoverlapping(tau_points.as_ptr(), points, n_to_return);
        *n_points_returned = n_to_return as libc::c_int;

        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Get number of default Matsubara sampling points with custom limit (extended version)
///
/// # Arguments
/// * `b` - Basis object
/// * `positive_only` - If true, return only positive frequencies
/// * `mitigate` - If true, enable mitigation (fencing) to improve conditioning
/// * `L` - Requested number of sampling points
/// * `num_points_returned` - Pointer to store the computed point count
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if any pointer is null or L < 0
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
///
/// # Note
/// Returns the full computed count for `spir_basis_get_default_matsus_ext`
/// with the same parameters. When mitigate is true, fencing may produce more
/// points than requested; the getter truncates the output to the provided
/// buffer size, so this count can exceed what was returned.
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_n_default_matsus_ext(
    b: *const spir_basis,
    positive_only: bool,
    mitigate: bool,
    #[allow(non_snake_case)] L: libc::c_int,
    num_points_returned: *mut libc::c_int,
) -> StatusCode {
    if b.is_null() || num_points_returned.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    if L < 0 {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let matsu_points = basis.default_matsubara_sampling_points_with_mitigate(
            positive_only,
            mitigate,
            L as usize,
        );

        *num_points_returned = matsu_points.len() as libc::c_int;

        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

/// Get default Matsubara sampling points with custom limit (extended version)
///
/// # Arguments
/// * `b` - Basis object
/// * `positive_only` - If true, return only positive frequencies
/// * `mitigate` - If true, enable mitigation (fencing) to improve conditioning
/// * `n_points` - Maximum number of points requested
/// * `points` - Pre-allocated array to store Matsubara indices (size >= n_points)
/// * `n_points_returned` - Pointer to store the full computed point count
///
/// # Returns
/// * `SPIR_COMPUTATION_SUCCESS` (0) on success
/// * `SPIR_INVALID_ARGUMENT` (-6) if any pointer is null or n_points < 0
/// * `SPIR_INTERNAL_ERROR` (-7) if internal panic occurs
///
/// # Note
/// `points` must hold at least `n_points` elements and is never written
/// beyond that. When `mitigate` is true, fencing can produce more points than
/// requested: the output is truncated to `n_points` elements and
/// `n_points_returned` reports the full computed count, so
/// `n_points_returned > n_points` signals truncation. Call
/// `spir_basis_get_n_default_matsus_ext` with the same parameters to see the
/// full count before choosing the buffer size.
#[unsafe(no_mangle)]
pub extern "C" fn spir_basis_get_default_matsus_ext(
    b: *const spir_basis,
    positive_only: bool,
    mitigate: bool,
    n_points: libc::c_int,
    points: *mut i64,
    n_points_returned: *mut libc::c_int,
) -> StatusCode {
    if b.is_null() || points.is_null() || n_points_returned.is_null() {
        return SPIR_INVALID_ARGUMENT;
    }

    if n_points < 0 {
        return SPIR_INVALID_ARGUMENT;
    }

    let result = catch_unwind(AssertUnwindSafe(|| unsafe {
        let basis = &*b;
        let matsu_points = basis.default_matsubara_sampling_points_with_mitigate(
            positive_only,
            mitigate,
            n_points as usize,
        );

        // The caller-owned buffer holds n_points elements and is never written
        // beyond that. With mitigate=true, fencing can compute more points than
        // requested; only the first n_points elements are returned and
        // n_points_returned reports the number actually written. Call
        // spir_basis_get_n_default_matsus_ext with the same parameters to see
        // the full computed count and detect truncation.
        let n_to_return = matsu_points.len().min(n_points as usize);
        std::ptr::copy_nonoverlapping(matsu_points.as_ptr(), points, n_to_return);
        *n_points_returned = n_to_return as libc::c_int;

        SPIR_COMPUTATION_SUCCESS
    }));

    result.unwrap_or(SPIR_INTERNAL_ERROR)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::kernel::*;
    use crate::sve::*;
    use crate::{
        spir_funcs_get_size, spir_funcs_release, spir_gauss_legendre_rule_piecewise_double,
    };
    use std::ptr;

    #[test]
    fn test_basis_from_sve() {
        use crate::{spir_funcs_get_size, spir_funcs_release};
        // Create kernel
        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(10.0, &mut kernel_status);
        assert_eq!(kernel_status, SPIR_COMPUTATION_SUCCESS);

        // Compute SVE
        let mut sve_status = SPIR_INTERNAL_ERROR;
        let sve = spir_sve_result_new(kernel, 1e-6, -1, -1, -1, &mut sve_status);
        assert_eq!(sve_status, SPIR_COMPUTATION_SUCCESS);

        // Create basis from SVE (kernel is still required for type info)
        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            1,      // Fermionic
            10.0,   // beta
            1.0,    // omega_max
            1e-6,   // epsilon
            kernel, // kernel required (for type info)
            sve,    // SVE provided (optimization)
            -1,     // no max_size
            &mut basis_status,
        );
        assert_eq!(basis_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!basis.is_null());

        // Get size
        let mut size = 0;
        let status = spir_basis_get_size(basis, &mut size);
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert!(size > 0);
        debug_println!("Basis size: {}", size);

        // Get statistics
        let mut stats = -1;
        let status = spir_basis_get_stats(basis, &mut stats);
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert_eq!(stats, 1); // Fermionic

        // Cleanup
        spir_basis_release(basis);
        spir_sve_result_release(sve);
        spir_kernel_release(kernel);
    }

    #[test]
    fn test_basis_from_kernel() {
        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(10.0, &mut kernel_status);

        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            0,    // Bosonic
            10.0, // beta
            1.0,  // omega_max
            1e-6, // epsilon
            kernel,
            ptr::null(), // no SVE (compute from kernel)
            -1,
            &mut basis_status,
        );
        assert_eq!(basis_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!basis.is_null());

        let mut stats = -1;
        spir_basis_get_stats(basis, &mut stats);
        assert_eq!(stats, 0); // Bosonic

        spir_basis_release(basis);
        spir_kernel_release(kernel);
    }

    #[test]
    fn test_basis_tau_sampling() {
        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(10.0, &mut kernel_status);

        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            0,
            10.0,
            1.0,
            1e-6,
            kernel,
            ptr::null(),
            -1,
            &mut basis_status,
        );

        // Get number of tau points
        let mut n_taus = 0;
        let status = spir_basis_get_n_default_taus(basis, &mut n_taus);
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert!(n_taus > 0);
        debug_println!("Number of tau points: {}", n_taus);

        // Get tau points
        let mut taus = vec![0.0; n_taus as usize];
        let status = spir_basis_get_default_taus(basis, taus.as_mut_ptr());
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);

        debug_println!("First 5 tau points:");
        for i in 0..std::cmp::min(5, taus.len()) {
            debug_println!("  tau[{}] = {}", i, taus[i]);
        }

        spir_basis_release(basis);
        spir_kernel_release(kernel);
    }

    #[test]
    fn test_basis_matsubara_sampling() {
        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(10.0, &mut kernel_status);

        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            1,
            10.0,
            1.0,
            1e-6,
            kernel,
            ptr::null(),
            -1,
            &mut basis_status,
        );

        // Get number of Matsubara points (positive only)
        let mut n_matsus = 0;
        let status = spir_basis_get_n_default_matsus(basis, true, &mut n_matsus);
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert!(n_matsus > 0);
        debug_println!("Number of Matsubara points (positive): {}", n_matsus);

        // Get Matsubara points
        let mut matsus = vec![0i64; n_matsus as usize];
        let status = spir_basis_get_default_matsus(basis, true, matsus.as_mut_ptr());
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);

        debug_println!("First 5 Matsubara indices:");
        for i in 0..std::cmp::min(5, matsus.len()) {
            debug_println!("  n[{}] = {}", i, matsus[i]);
        }

        spir_basis_release(basis);
        spir_kernel_release(kernel);
    }

    #[test]
    fn test_basis_omega_sampling() {
        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(10.0, &mut kernel_status);

        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            1,
            10.0,
            1.0,
            1e-6,
            kernel,
            ptr::null(),
            -1,
            &mut basis_status,
        );

        // Get number of omega points
        let mut n_ws = 0;
        let status = spir_basis_get_n_default_ws(basis, &mut n_ws);
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert!(n_ws > 0);
        debug_println!("Number of omega points: {}", n_ws);

        // Get omega points
        let mut ws = vec![0.0; n_ws as usize];
        let status = spir_basis_get_default_ws(basis, ws.as_mut_ptr());
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);

        debug_println!("First 5 omega points:");
        for i in 0..std::cmp::min(5, ws.len()) {
            debug_println!("  w[{}] = {}", i, ws[i]);
        }

        // Test singular_values alias
        let mut size = 0;
        let status = spir_basis_get_size(basis, &mut size);
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);

        let mut svals = vec![0.0; size as usize];
        let status = spir_basis_get_singular_values(basis, svals.as_mut_ptr());
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);

        // Verify it matches get_svals
        let mut svals2 = vec![0.0; size as usize];
        let status2 = spir_basis_get_svals(basis, svals2.as_mut_ptr());
        assert_eq!(status2, SPIR_COMPUTATION_SUCCESS);
        assert_eq!(svals, svals2);
        debug_println!("✓ get_singular_values matches get_svals");

        spir_basis_release(basis);
        spir_kernel_release(kernel);
    }

    #[test]
    fn test_basis_ext_functions() {
        use crate::kernel::*;

        // Create kernel and basis
        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(10.0, &mut kernel_status);
        assert_eq!(kernel_status, SPIR_COMPUTATION_SUCCESS);

        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            1,
            10.0,
            1.0,
            1e-6,
            kernel,
            ptr::null(),
            -1,
            &mut basis_status,
        );
        assert_eq!(basis_status, SPIR_COMPUTATION_SUCCESS);

        // Test get_default_taus_ext
        let requested_tau = 5; // Request only 5 points
        let mut tau_points = vec![0.0; requested_tau];
        let mut tau_returned = 0;
        let status = spir_basis_get_default_taus_ext(
            basis,
            requested_tau as libc::c_int,
            tau_points.as_mut_ptr(),
            &mut tau_returned,
        );
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert_eq!(tau_returned, requested_tau as libc::c_int);
        println!(
            "✓ get_default_taus_ext returned {} tau points (requested {})",
            tau_returned, requested_tau
        );
        debug_println!("  First 3: {:?}", &tau_points[..3]);

        // Test get_n_default_matsus_ext
        let requested_matsu = 3; // Request only 3 points
        let mut matsu_count = 0;
        let status = spir_basis_get_n_default_matsus_ext(
            basis,
            true,  // positive_only
            false, // mitigate
            requested_matsu,
            &mut matsu_count,
        );
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert!(matsu_count > 0);
        debug_println!("✓ get_n_default_matsus_ext returned count: {}", matsu_count);

        // Test get_default_matsus_ext
        // Allocate space based on the count returned by get_n_default_matsus_ext
        let mut matsu_points = vec![0i64; matsu_count as usize];
        let mut matsu_returned = 0;
        let status = spir_basis_get_default_matsus_ext(
            basis,
            true,  // positive_only
            false, // mitigate
            requested_matsu,
            matsu_points.as_mut_ptr(),
            &mut matsu_returned,
        );
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        // The returned count should match what get_n_default_matsus_ext reported
        assert_eq!(matsu_returned, matsu_count);
        println!(
            "✓ get_default_matsus_ext returned {} matsubara points",
            matsu_returned
        );
        debug_println!("  Points: {:?}", matsu_points);

        // Test error case: negative n_points
        let mut bad_returned = 0;
        let status = spir_basis_get_default_taus_ext(basis, -1, ptr::null_mut(), &mut bad_returned);
        assert_eq!(status, SPIR_INVALID_ARGUMENT);
        debug_println!("✓ Negative n_points correctly rejected");

        spir_basis_release(basis);
        spir_kernel_release(kernel);
    }

    #[test]
    fn test_basis_get_uhat_full() {
        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(10.0, &mut kernel_status);
        assert_eq!(kernel_status, SPIR_COMPUTATION_SUCCESS);

        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            1,    // Fermionic
            10.0, // beta
            1.0,  // omega_max
            1e-6, // epsilon
            kernel,
            ptr::null(),
            -1,
            &mut basis_status,
        );
        assert_eq!(basis_status, SPIR_COMPUTATION_SUCCESS);

        // Get uhat (truncated)
        let mut uhat_status = SPIR_INTERNAL_ERROR;
        let uhat_funcs = unsafe { spir_basis_get_uhat(basis, &mut uhat_status) };
        assert_eq!(uhat_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!uhat_funcs.is_null());

        let mut uhat_size = 0;
        let status = spir_funcs_get_size(uhat_funcs, &mut uhat_size);
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);

        // Get uhat_full (untruncated)
        let mut uhat_full_status = SPIR_INTERNAL_ERROR;
        let uhat_full_funcs = unsafe { spir_basis_get_uhat_full(basis, &mut uhat_full_status) };
        assert_eq!(uhat_full_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!uhat_full_funcs.is_null());

        let mut uhat_full_size = 0;
        let status = spir_funcs_get_size(uhat_full_funcs, &mut uhat_full_size);
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);

        // uhat_full should have at least as many functions as uhat
        assert_eq!(uhat_size, 10);
        assert!(uhat_full_size >= uhat_size);
        // assert!(uhat_full_size == 28); <--- expected value
        // Test error handling: DLR basis (not supported)
        {
            // Note: DLR basis creation would require different API
            // For now, we just test that IR basis works
        }

        unsafe {
            spir_funcs_release(uhat_funcs);
            spir_funcs_release(uhat_full_funcs);
            spir_basis_release(basis);
            spir_kernel_release(kernel);
        }
    }

    #[test]
    fn test_basis_new_from_sve_and_regularizer() {
        use crate::{
            SPIR_COMPUTATION_SUCCESS, SPIR_INTERNAL_ERROR, spir_funcs_from_piecewise_legendre,
            spir_funcs_release,
        };
        let lambda = 10.0;
        let beta = 1.0;
        let omega_max = lambda / beta;
        let epsilon = 1e-8;

        // Create kernel and SVE result
        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(lambda, &mut kernel_status);
        assert_eq!(kernel_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!kernel.is_null());

        let mut sve_status = SPIR_INTERNAL_ERROR;
        use crate::SPIR_TWORK_AUTO;
        let sve = spir_sve_result_new(kernel, epsilon, -1, -1, SPIR_TWORK_AUTO, &mut sve_status);
        assert_eq!(sve_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!sve.is_null());

        // Create regularizer_func as spir_funcs
        // For LogisticKernel with Fermionic statistics, regularizer_func(omega) = 1.0
        // We'll create a simple constant function
        let n_segments = 1;
        let segments = [-omega_max, omega_max]; // Full omega range
        let coeffs = [1.0]; // Constant function = 1.0
        let nfuncs = 1;
        let order = 0;

        let mut regularizer_status = SPIR_INTERNAL_ERROR;
        let regularizer_funcs = spir_funcs_from_piecewise_legendre(
            segments.as_ptr(),
            n_segments,
            coeffs.as_ptr(),
            nfuncs,
            order,
            &mut regularizer_status,
        );
        assert_eq!(regularizer_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!regularizer_funcs.is_null());

        // Create basis using new function
        // For LogisticKernel: ypower=0, conv_radius=1.0 (typical values)
        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new_from_sve_and_regularizer(
            1, // Fermionic
            beta,
            omega_max,
            epsilon,
            lambda,
            0,   // ypower=0
            1.0, // conv_radius=1.0
            sve,
            regularizer_funcs,
            -1, // no max_size
            &mut basis_status,
        );

        if basis_status == SPIR_COMPUTATION_SUCCESS && !basis.is_null() {
            let mut basis_size = 0;
            let status = spir_basis_get_size(basis, &mut basis_size);
            assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
            assert!(basis_size > 0);

            unsafe {
                spir_basis_release(basis);
            }
        }

        // Test error handling
        {
            let mut basis_status = SPIR_INTERNAL_ERROR;
            let basis_err = spir_basis_new_from_sve_and_regularizer(
                1,
                beta,
                omega_max,
                epsilon,
                lambda,
                0,
                1.0,
                ptr::null(),
                regularizer_funcs,
                -1,
                &mut basis_status,
            );
            assert_ne!(basis_status, SPIR_COMPUTATION_SUCCESS);
            assert!(basis_err.is_null());
        }

        {
            let mut basis_status = SPIR_INTERNAL_ERROR;
            let basis_err = spir_basis_new_from_sve_and_regularizer(
                1,
                beta,
                omega_max,
                epsilon,
                lambda,
                0,
                1.0,
                sve,
                ptr::null(),
                -1,
                &mut basis_status,
            );
            assert_ne!(basis_status, SPIR_COMPUTATION_SUCCESS);
            assert!(basis_err.is_null());
        }

        unsafe {
            spir_funcs_release(regularizer_funcs);
            spir_sve_result_release(sve);
            spir_kernel_release(kernel);
        }
    }

    #[test]
    fn test_basis_rejects_fermionic_regularized_bose() {
        use crate::SPIR_NOT_SUPPORTED;
        use crate::{
            spir_funcs_from_piecewise_legendre, spir_funcs_release, spir_sve_result_release,
        };

        let lambda = 10.0;
        let beta = 1.0;
        let omega_max = lambda / beta;
        let epsilon = 1e-8;

        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_reg_bose_kernel_new(lambda, &mut kernel_status);
        assert_eq!(kernel_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!kernel.is_null());

        // spir_basis_new with RegularizedBoseKernel + fermionic statistics must
        // be rejected at the boundary instead of deferring a downstream panic.
        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            SPIR_STATISTICS_FERMIONIC,
            beta,
            omega_max,
            epsilon,
            kernel,
            ptr::null(),
            -1,
            &mut basis_status,
        );
        assert_eq!(basis_status, SPIR_NOT_SUPPORTED);
        assert!(basis.is_null());

        // Same combination via spir_basis_new_from_sve_and_regularizer (ypower = 1).
        let mut sve_status = SPIR_INTERNAL_ERROR;
        let sve = spir_sve_result_new(kernel, epsilon, -1, -1, -1, &mut sve_status);
        assert_eq!(sve_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!sve.is_null());

        let n_segments = 1;
        let segments = [-omega_max, omega_max];
        let coeffs = [1.0];
        let nfuncs = 1;
        let order = 0;

        let mut regularizer_status = SPIR_INTERNAL_ERROR;
        let regularizer_funcs = spir_funcs_from_piecewise_legendre(
            segments.as_ptr(),
            n_segments,
            coeffs.as_ptr(),
            nfuncs,
            order,
            &mut regularizer_status,
        );
        assert_eq!(regularizer_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!regularizer_funcs.is_null());

        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new_from_sve_and_regularizer(
            SPIR_STATISTICS_FERMIONIC,
            beta,
            omega_max,
            epsilon,
            lambda,
            1,   // ypower = 1 => RegularizedBoseKernel
            1.0, // conv_radius (unused)
            sve,
            regularizer_funcs,
            -1,
            &mut basis_status,
        );
        assert_eq!(basis_status, SPIR_NOT_SUPPORTED);
        assert!(basis.is_null());

        // Bosonic statistics with the same kernel must still succeed.
        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            SPIR_STATISTICS_BOSONIC,
            beta,
            omega_max,
            epsilon,
            kernel,
            sve,
            -1,
            &mut basis_status,
        );
        assert_eq!(basis_status, SPIR_COMPUTATION_SUCCESS);
        assert!(!basis.is_null());

        unsafe {
            spir_basis_release(basis);
            spir_funcs_release(regularizer_funcs);
            spir_sve_result_release(sve);
            spir_kernel_release(kernel);
        }
    }

    #[test]
    fn test_basis_rejects_nan_params() {
        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(10.0, &mut kernel_status);
        assert_eq!(kernel_status, SPIR_COMPUTATION_SUCCESS);

        // NaN beta / omega_max / epsilon must not pass the <= 0.0 guards.
        for (beta, omega_max, epsilon) in [
            (f64::NAN, 1.0, 1e-6),
            (10.0, f64::NAN, 1e-6),
            (10.0, 1.0, f64::NAN),
        ] {
            let mut basis_status = SPIR_INTERNAL_ERROR;
            let basis = spir_basis_new(
                SPIR_STATISTICS_FERMIONIC,
                beta,
                omega_max,
                epsilon,
                kernel,
                ptr::null(),
                -1,
                &mut basis_status,
            );
            assert_eq!(basis_status, SPIR_INVALID_ARGUMENT);
            assert!(basis.is_null());
        }

        unsafe {
            spir_kernel_release(kernel);
        }
    }

    #[test]
    fn test_get_default_matsus_ext_mitigate_buffer_check() {
        let beta = 10.0;
        let wmax = 10.0;
        let epsilon = 1e-8;

        let mut kernel_status = SPIR_INTERNAL_ERROR;
        let kernel = spir_logistic_kernel_new(beta * wmax, &mut kernel_status);
        assert_eq!(kernel_status, SPIR_COMPUTATION_SUCCESS);

        let mut sve_status = SPIR_INTERNAL_ERROR;
        let sve = spir_sve_result_new(kernel, epsilon, -1, -1, -1, &mut sve_status);
        assert_eq!(sve_status, SPIR_COMPUTATION_SUCCESS);

        let mut basis_status = SPIR_INTERNAL_ERROR;
        let basis = spir_basis_new(
            SPIR_STATISTICS_FERMIONIC,
            beta,
            wmax,
            epsilon,
            kernel,
            sve,
            -1,
            &mut basis_status,
        );
        assert_eq!(basis_status, SPIR_COMPUTATION_SUCCESS);

        let mut basis_size = 0;
        let status = spir_basis_get_size(basis, &mut basis_size);
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);

        let positive_only = false;
        let mitigate = true;
        let n_requested = basis_size;

        // Query the required buffer size (fencing may add points).
        let mut n_required = 0;
        let status = spir_basis_get_n_default_matsus_ext(
            basis,
            positive_only,
            mitigate,
            n_requested,
            &mut n_required,
        );
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert!(n_required >= n_requested);

        // A buffer sized exactly to the request is never overflowed: the
        // getter writes at most n_points elements and reports the count
        // written. When fencing computes more points, the output is truncated
        // to the buffer size; comparing with the query above reveals it.
        let mut points = vec![0i64; n_requested as usize];
        let mut n_returned = -1;
        let status = spir_basis_get_default_matsus_ext(
            basis,
            positive_only,
            mitigate,
            n_requested,
            points.as_mut_ptr(),
            &mut n_returned,
        );
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert!(
            n_returned <= n_requested,
            "never report more than was written"
        );
        if n_required > n_requested {
            assert_eq!(n_returned, n_requested, "output truncated to buffer size");
        } else {
            assert_eq!(n_returned, n_required);
        }

        // A larger request also never overflows its buffer.
        let mut points = vec![0i64; n_required as usize];
        let mut n_returned = 0;
        let status = spir_basis_get_default_matsus_ext(
            basis,
            positive_only,
            mitigate,
            n_required,
            points.as_mut_ptr(),
            &mut n_returned,
        );
        assert_eq!(status, SPIR_COMPUTATION_SUCCESS);
        assert!(n_returned <= n_required);

        unsafe {
            spir_basis_release(basis);
            spir_sve_result_release(sve);
            spir_kernel_release(kernel);
        }
    }
}