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
use std::cmp::Ordering;
use std::ffi::{c_char, c_int, c_void};
use std::hash::{Hash, Hasher};
use std::ops::{
    BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Deref, DerefMut, Sub, SubAssign,
};
use std::{fmt, ptr, slice};

use pkgcraft::dep::{self, Conditionals, Dep, Evaluate, EvaluateForce, Flatten, Recursive, Uri};
use pkgcraft::eapi::Eapi;
use pkgcraft::traits::{Contains, IntoOwned};
use pkgcraft::types::Ordered;
use pkgcraft::utils::hash;

use crate::eapi::eapi_or_default;
use crate::error::Error;
use crate::macros::*;
use crate::panic::ffi_catch_panic;
use crate::types::SetOp;
use crate::utils::boxed;

pub mod cpn;
pub mod cpv;
pub mod pkg;
pub mod uri;
pub mod use_dep;
pub mod version;

/// DependencySet variants.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum DependencySetKind {
    Package,
    SrcUri,
    License,
    Properties,
    RequiredUse,
    Restrict,
}

/// Opaque wrapper for pkgcraft::dep::DependencySet.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DependencySetWrapper {
    Dep(dep::DependencySet<Dep>),
    String(dep::DependencySet<String>),
    Uri(dep::DependencySet<Uri>),
}

impl fmt::Display for DependencySetWrapper {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Dep(d) => write!(f, "{d}"),
            Self::String(d) => write!(f, "{d}"),
            Self::Uri(d) => write!(f, "{d}"),
        }
    }
}

/// C-compatible wrapper for pkgcraft::dep::DependencySet.
#[derive(Debug)]
#[repr(C)]
pub struct DependencySet {
    set: DependencySetKind,
    dep: *mut DependencySetWrapper,
}

impl Clone for DependencySet {
    fn clone(&self) -> Self {
        let dep = try_ref_from_ptr!(self.dep);
        Self {
            set: self.set,
            dep: Box::into_raw(Box::new(dep.clone())),
        }
    }
}

impl Drop for DependencySet {
    fn drop(&mut self) {
        unsafe {
            drop(Box::from_raw(self.dep));
        }
    }
}

impl DependencySet {
    pub(crate) fn new_dep(d: dep::DependencySet<Dep>) -> Self {
        Self {
            set: DependencySetKind::Package,
            dep: Box::into_raw(Box::new(DependencySetWrapper::Dep(d))),
        }
    }

    pub(crate) fn new_string(d: dep::DependencySet<String>, set: DependencySetKind) -> Self {
        Self {
            set,
            dep: Box::into_raw(Box::new(DependencySetWrapper::String(d))),
        }
    }

    pub(crate) fn new_uri(d: dep::DependencySet<Uri>) -> Self {
        Self {
            set: DependencySetKind::SrcUri,
            dep: Box::into_raw(Box::new(DependencySetWrapper::Uri(d))),
        }
    }
}

impl Hash for DependencySet {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.deref().hash(state)
    }
}

impl PartialEq for DependencySet {
    fn eq(&self, other: &Self) -> bool {
        self.deref().eq(other.deref())
    }
}

impl Eq for DependencySet {}

impl Deref for DependencySet {
    type Target = DependencySetWrapper;

    fn deref(&self) -> &Self::Target {
        try_ref_from_ptr!(self.dep)
    }
}

impl DerefMut for DependencySet {
    fn deref_mut(&mut self) -> &mut Self::Target {
        try_mut_from_ptr!(self.dep)
    }
}

impl fmt::Display for DependencySet {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.deref())
    }
}

impl BitAnd<&DependencySet> for &DependencySet {
    type Output = DependencySet;

    fn bitand(self, other: &DependencySet) -> Self::Output {
        let mut dep = self.clone();
        dep &= other;
        dep
    }
}

impl BitAndAssign<&DependencySet> for DependencySet {
    fn bitand_assign(&mut self, other: &DependencySet) {
        use DependencySetWrapper::*;
        match (self.deref_mut(), other.deref()) {
            (Dep(d1), Dep(d2)) => *d1 &= d2,
            (String(d1), String(d2)) => *d1 &= d2,
            (Uri(d1), Uri(d2)) => *d1 &= d2,
            _ => {
                set_error_and_panic!(Error::new(format!(
                    "DependencySet kind {:?} doesn't match: {:?}",
                    self.set, other.set
                )));
            }
        }
    }
}

impl BitOr<&DependencySet> for &DependencySet {
    type Output = DependencySet;

    fn bitor(self, other: &DependencySet) -> Self::Output {
        let mut dep = self.clone();
        dep |= other;
        dep
    }
}

impl BitOrAssign<&DependencySet> for DependencySet {
    fn bitor_assign(&mut self, other: &DependencySet) {
        use DependencySetWrapper::*;
        match (self.deref_mut(), other.deref()) {
            (Dep(d1), Dep(d2)) => *d1 |= d2,
            (String(d1), String(d2)) => *d1 |= d2,
            (Uri(d1), Uri(d2)) => *d1 |= d2,
            _ => {
                set_error_and_panic!(Error::new(format!(
                    "DependencySet kind {:?} doesn't match: {:?}",
                    self.set, other.set
                )));
            }
        }
    }
}

impl BitXor<&DependencySet> for &DependencySet {
    type Output = DependencySet;

    fn bitxor(self, other: &DependencySet) -> Self::Output {
        let mut dep = self.clone();
        dep ^= other;
        dep
    }
}

impl BitXorAssign<&DependencySet> for DependencySet {
    fn bitxor_assign(&mut self, other: &DependencySet) {
        use DependencySetWrapper::*;
        match (self.deref_mut(), other.deref()) {
            (Dep(d1), Dep(d2)) => *d1 ^= d2,
            (String(d1), String(d2)) => *d1 ^= d2,
            (Uri(d1), Uri(d2)) => *d1 ^= d2,
            _ => {
                set_error_and_panic!(Error::new(format!(
                    "DependencySet kind {:?} doesn't match: {:?}",
                    self.set, other.set
                )));
            }
        }
    }
}

impl Sub<&DependencySet> for &DependencySet {
    type Output = DependencySet;

    fn sub(self, other: &DependencySet) -> Self::Output {
        let mut dep = self.clone();
        dep -= other;
        dep
    }
}

impl SubAssign<&DependencySet> for DependencySet {
    fn sub_assign(&mut self, other: &DependencySet) {
        use DependencySetWrapper::*;
        match (self.deref_mut(), other.deref()) {
            (Dep(d1), Dep(d2)) => *d1 -= d2,
            (String(d1), String(d2)) => *d1 -= d2,
            (Uri(d1), Uri(d2)) => *d1 -= d2,
            _ => {
                set_error_and_panic!(Error::new(format!(
                    "DependencySet kind {:?} doesn't match: {:?}",
                    self.set, other.set
                )));
            }
        }
    }
}

/// Opaque wrapper for pkgcraft::dep::IntoIter<T>.
#[derive(Debug)]
pub enum DependencyIntoIter {
    Dep(DependencySetKind, dep::IntoIter<Dep>),
    String(DependencySetKind, dep::IntoIter<String>),
    Uri(DependencySetKind, dep::IntoIter<Uri>),
}

impl Iterator for DependencyIntoIter {
    type Item = Dependency;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Dep(_, iter) => iter.next().map(Dependency::new_dep),
            Self::String(set, iter) => iter.next().map(|d| Dependency::new_string(d, *set)),
            Self::Uri(_, iter) => iter.next().map(Dependency::new_uri),
        }
    }
}

impl DoubleEndedIterator for DependencyIntoIter {
    fn next_back(&mut self) -> Option<Self::Item> {
        match self {
            Self::Dep(_, iter) => iter.next_back().map(Dependency::new_dep),
            Self::String(set, iter) => iter.next_back().map(|d| Dependency::new_string(d, *set)),
            Self::Uri(_, iter) => iter.next_back().map(Dependency::new_uri),
        }
    }
}

/// Opaque wrapper for pkgcraft::dep::Dependency.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DependencyWrapper {
    Dep(dep::Dependency<Dep>),
    String(dep::Dependency<String>),
    Uri(dep::Dependency<Uri>),
}

impl fmt::Display for DependencyWrapper {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Dep(d) => write!(f, "{d}"),
            Self::String(d) => write!(f, "{d}"),
            Self::Uri(d) => write!(f, "{d}"),
        }
    }
}

/// Dependency variants.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum DependencyKind {
    Enabled,
    Disabled,
    AllOf,
    AnyOf,
    ExactlyOneOf,
    AtMostOneOf,
    Conditional,
}

impl<T: Ordered> From<&dep::Dependency<T>> for DependencyKind {
    fn from(d: &dep::Dependency<T>) -> Self {
        use dep::Dependency::*;
        match d {
            Enabled(_) => Self::Enabled,
            Disabled(_) => Self::Disabled,
            AllOf(_) => Self::AllOf,
            AnyOf(_) => Self::AnyOf,
            ExactlyOneOf(_) => Self::ExactlyOneOf,
            AtMostOneOf(_) => Self::AtMostOneOf,
            Conditional(_, _) => Self::Conditional,
        }
    }
}

/// C-compatible wrapper for pkgcraft::dep::Dependency.
#[derive(Debug, Clone)]
#[repr(C)]
pub struct Dependency {
    set: DependencySetKind,
    kind: DependencyKind,
    dep: *mut DependencyWrapper,
}

impl Drop for Dependency {
    fn drop(&mut self) {
        unsafe {
            drop(Box::from_raw(self.dep));
        }
    }
}

impl Dependency {
    pub(crate) fn new_dep(d: dep::Dependency<Dep>) -> Self {
        Self {
            set: DependencySetKind::Package,
            kind: DependencyKind::from(&d),
            dep: Box::into_raw(Box::new(DependencyWrapper::Dep(d))),
        }
    }

    pub(crate) fn new_string(d: dep::Dependency<String>, set: DependencySetKind) -> Self {
        Self {
            set,
            kind: DependencyKind::from(&d),
            dep: Box::into_raw(Box::new(DependencyWrapper::String(d))),
        }
    }

    pub(crate) fn new_uri(d: dep::Dependency<Uri>) -> Self {
        Self {
            set: DependencySetKind::SrcUri,
            kind: DependencyKind::from(&d),
            dep: Box::into_raw(Box::new(DependencyWrapper::Uri(d))),
        }
    }
}

impl Hash for Dependency {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.deref().hash(state)
    }
}

impl Ord for Dependency {
    fn cmp(&self, other: &Self) -> Ordering {
        self.deref().cmp(other.deref())
    }
}

impl PartialOrd for Dependency {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Dependency {
    fn eq(&self, other: &Self) -> bool {
        self.deref().eq(other.deref())
    }
}

impl Eq for Dependency {}

impl Deref for Dependency {
    type Target = DependencyWrapper;

    fn deref(&self) -> &Self::Target {
        try_ref_from_ptr!(self.dep)
    }
}

impl DerefMut for Dependency {
    fn deref_mut(&mut self) -> &mut Self::Target {
        try_mut_from_ptr!(self.dep)
    }
}

impl fmt::Display for Dependency {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.deref())
    }
}

/// Opaque wrapper for pkgcraft::dep::IntoIterFlatten<T>.
#[derive(Debug)]
pub enum DependencyIntoIterFlatten {
    Dep(dep::IntoIterFlatten<Dep>),
    String(dep::IntoIterFlatten<String>),
    Uri(dep::IntoIterFlatten<Uri>),
}

impl Iterator for DependencyIntoIterFlatten {
    type Item = *mut c_void;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Dep(iter) => iter
                .next()
                .map(|x| Box::into_raw(Box::new(x)) as *mut c_void),
            Self::String(iter) => iter
                .next()
                .map(|x| try_ptr_from_str!(x.as_str()) as *mut c_void),
            Self::Uri(iter) => iter
                .next()
                .map(|x| Box::into_raw(Box::new(x)) as *mut c_void),
        }
    }
}

/// Opaque wrapper for pkgcraft::dep::IntoIterRecursive<T>.
#[derive(Debug)]
pub enum DependencyIntoIterRecursive {
    Dep(DependencySetKind, dep::IntoIterRecursive<Dep>),
    String(DependencySetKind, dep::IntoIterRecursive<String>),
    Uri(DependencySetKind, dep::IntoIterRecursive<Uri>),
}

impl Iterator for DependencyIntoIterRecursive {
    type Item = Dependency;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Dep(_, iter) => iter.next().map(Dependency::new_dep),
            Self::String(set, iter) => iter.next().map(|d| Dependency::new_string(d, *set)),
            Self::Uri(_, iter) => iter.next().map(Dependency::new_uri),
        }
    }
}

/// Opaque wrapper for pkgcraft::dep::IntoIterConditionals<T>.
#[derive(Debug)]
pub enum DependencyIntoIterConditionals {
    Dep(dep::IntoIterConditionals<Dep>),
    String(dep::IntoIterConditionals<String>),
    Uri(dep::IntoIterConditionals<Uri>),
}

impl Iterator for DependencyIntoIterConditionals {
    type Item = dep::UseDep;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Dep(iter) => iter.next(),
            Self::String(iter) => iter.next(),
            Self::Uri(iter) => iter.next(),
        }
    }
}

/// Create a new, empty DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySetKind.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_new(
    kind: DependencySetKind,
) -> *mut DependencySet {
    use DependencySetKind::*;
    let set = match kind {
        Package => DependencySet::new_dep(Default::default()),
        SrcUri => DependencySet::new_uri(Default::default()),
        _ => DependencySet::new_string(Default::default(), kind),
    };

    Box::into_raw(Box::new(set))
}

/// Create a DependencySet from an array of Dependency objects.
///
/// Returns NULL on error.
///
/// # Safety
/// The argument should be an array of similarly-typed Dependency objects.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_from_iter(
    deps: *mut *mut Dependency,
    len: usize,
    kind: DependencySetKind,
) -> *mut DependencySet {
    ffi_catch_panic! {
        let deps = unsafe { slice::from_raw_parts(deps, len) };
        let deps = deps.iter().map(|p| try_ref_from_ptr!(p));
        let (mut deps_dep, mut deps_string, mut deps_uri) = (vec![], vec![], vec![]);

        for d in deps {
            if d.set != kind {
                set_error_and_panic!(
                    Error::new(format!("Dependency kind {:?} doesn't match: {kind:?}", d.set))
                );
            }

            match d.deref() {
                DependencyWrapper::Dep(d) => deps_dep.push(d.clone()),
                DependencyWrapper::String(d) => deps_string.push(d.clone()),
                DependencyWrapper::Uri(d) => deps_uri.push(d.clone()),
            }
        }

        use DependencySetKind::*;
        let dep = match kind {
            Package => DependencySet::new_dep(deps_dep.into_iter().collect()),
            SrcUri => DependencySet::new_uri(deps_uri.into_iter().collect()),
            _ => DependencySet::new_string(deps_string.into_iter().collect(), kind),
        };

        Box::into_raw(Box::new(dep))
    }
}

/// Parse a string into a specified DependencySet type.
///
/// Returns NULL on error.
///
/// # Safety
/// The argument should be a UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_parse(
    s: *const c_char,
    eapi: *const Eapi,
    kind: DependencySetKind,
) -> *mut DependencySet {
    ffi_catch_panic! {
        let s = try_str_from_ptr!(s);
        let eapi = eapi_or_default!(eapi);

        use DependencySetKind::*;
        let depset = match kind {
            Package => {
                let opt_dep = unwrap_or_panic!(dep::DependencySet::package(s, eapi));
                DependencySet::new_dep(opt_dep)
            },
            SrcUri => {
                let opt_dep = unwrap_or_panic!(dep::DependencySet::src_uri(s));
                DependencySet::new_uri(opt_dep)
            },
            License => {
                let opt_dep = unwrap_or_panic!(dep::DependencySet::license(s));
                DependencySet::new_string(opt_dep, kind)
            },
            Properties => {
                let opt_dep = unwrap_or_panic!(dep::DependencySet::properties(s));
                DependencySet::new_string(opt_dep, kind)
            },
            RequiredUse => {
                let opt_dep = unwrap_or_panic!(dep::DependencySet::required_use(s));
                DependencySet::new_string(opt_dep, kind)
            },
            Restrict => {
                let opt_dep = unwrap_or_panic!(dep::DependencySet::restrict(s));
                DependencySet::new_string(opt_dep, kind)
            },
        };

        Box::into_raw(Box::new(depset))
    }
}

/// Parse a string into a specified Dependency type.
///
/// Returns NULL on error.
///
/// # Safety
/// The argument should be a UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_parse(
    s: *const c_char,
    eapi: *const Eapi,
    kind: DependencySetKind,
) -> *mut Dependency {
    ffi_catch_panic! {
        let s = try_str_from_ptr!(s);
        let eapi = eapi_or_default!(eapi);

        use DependencySetKind::*;
        let dep = match kind {
            Package => {
                let dep = unwrap_or_panic!(dep::Dependency::package(s, eapi));
                Dependency::new_dep(dep)
            },
            SrcUri => {
                let dep = unwrap_or_panic!(dep::Dependency::src_uri(s));
                Dependency::new_uri(dep)
            },
            License => {
                let dep = unwrap_or_panic!(dep::Dependency::license(s));
                Dependency::new_string(dep, kind)
            },
            Properties => {
                let dep = unwrap_or_panic!(dep::Dependency::properties(s));
                Dependency::new_string(dep, kind)
            },
            RequiredUse => {
                let dep = unwrap_or_panic!(dep::Dependency::required_use(s));
                Dependency::new_string(dep, kind)
            },
            Restrict => {
                let dep = unwrap_or_panic!(dep::Dependency::restrict(s));
                Dependency::new_string(dep, kind)
            },
        };

        Box::into_raw(Box::new(dep))
    }
}

/// Create a Dependency from a Dep.
///
/// # Safety
/// The argument must be valid Dep pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_from_dep(d: *mut Dep) -> *mut Dependency {
    let d = try_ref_from_ptr!(d);
    let dep = Dependency::new_dep(dep::Dependency::Enabled(d.clone()));
    Box::into_raw(Box::new(dep))
}

/// Evaluate a DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_evaluate(
    d: *mut DependencySet,
    options: *mut *mut c_char,
    len: usize,
) -> *mut DependencySet {
    let dep = try_ref_from_ptr!(d);
    let options = unsafe { slice::from_raw_parts(options, len) };
    let options = options.iter().map(|p| try_str_from_ptr!(p)).collect();

    use DependencySetWrapper::*;
    let evaluated = match dep.deref() {
        Dep(d) => Dep(d.evaluate(&options).into_owned()),
        String(d) => String(d.evaluate(&options).into_owned()),
        Uri(d) => Uri(d.evaluate(&options).into_owned()),
    };

    let dep = DependencySet {
        set: dep.set,
        dep: Box::into_raw(Box::new(evaluated)),
    };

    Box::into_raw(Box::new(dep))
}

/// Forcibly evaluate a DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_evaluate_force(
    d: *mut DependencySet,
    force: bool,
) -> *mut DependencySet {
    let dep = try_ref_from_ptr!(d);

    use DependencySetWrapper::*;
    let evaluated = match dep.deref() {
        Dep(d) => Dep(d.evaluate_force(force).into_owned()),
        String(d) => String(d.evaluate_force(force).into_owned()),
        Uri(d) => Uri(d.evaluate_force(force).into_owned()),
    };

    let dep = DependencySet {
        set: dep.set,
        dep: Box::into_raw(Box::new(evaluated)),
    };

    Box::into_raw(Box::new(dep))
}

/// Returns true if two DependencySets have no elements in common.
///
/// # Safety
/// The arguments must be a valid DependencySet pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_is_disjoint(
    d1: *mut DependencySet,
    d2: *mut DependencySet,
) -> bool {
    let d1 = try_deref_from_ptr!(d1);
    let d2 = try_deref_from_ptr!(d2);

    use DependencySetWrapper::*;
    match (d1, d2) {
        (Dep(d1), Dep(d2)) => d1.is_disjoint(d2),
        (String(d1), String(d2)) => d1.is_disjoint(d2),
        (Uri(d1), Uri(d2)) => d1.is_disjoint(d2),
        _ => true,
    }
}

/// Returns true if a DependencySet is empty.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_is_empty(d: *mut DependencySet) -> bool {
    let deps = try_deref_from_ptr!(d);

    match deps {
        DependencySetWrapper::Dep(d) => d.is_empty(),
        DependencySetWrapper::String(d) => d.is_empty(),
        DependencySetWrapper::Uri(d) => d.is_empty(),
    }
}

/// Returns true if all the elements of the first DependencySet are contained in the second.
///
/// # Safety
/// The arguments must be a valid DependencySet pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_is_subset(
    d1: *mut DependencySet,
    d2: *mut DependencySet,
) -> bool {
    let d1 = try_deref_from_ptr!(d1);
    let d2 = try_deref_from_ptr!(d2);

    use DependencySetWrapper::*;
    match (d1, d2) {
        (Dep(d1), Dep(d2)) => d1.is_subset(d2),
        (String(d1), String(d2)) => d1.is_subset(d2),
        (Uri(d1), Uri(d2)) => d1.is_subset(d2),
        _ => false,
    }
}

/// Returns the Dependency element for a given index.
///
/// Returns NULL on index nonexistence.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_get_index(
    d: *mut DependencySet,
    index: usize,
) -> *mut Dependency {
    ffi_catch_panic! {
        let set = try_ref_from_ptr!(d);
        let err = || Error::new(format!("failed getting DependencySet index: {index}"));

        use DependencySetWrapper::*;
        let dep = match set.deref() {
            Dep(deps) => {
                deps.get_index(index)
                    .ok_or_else(err)
                    .map(|d| Dependency::new_dep(d.clone()))
            }
            String(deps) => {
                deps.get_index(index)
                    .ok_or_else(err)
                    .map(|d| Dependency::new_string(d.clone(), set.set))
            }
            Uri(deps) => {
                deps.get_index(index)
                    .ok_or_else(err)
                    .map(|d| Dependency::new_uri(d.clone()))
            }
        };

        Box::into_raw(Box::new(unwrap_or_panic!(dep)))
    }
}

/// Recursively sort a DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_sort(d: *mut DependencySet) {
    let set = try_mut_from_ptr!(d);

    use DependencySetWrapper::*;
    match set.deref_mut() {
        Dep(deps) => deps.sort(),
        String(deps) => deps.sort(),
        Uri(deps) => deps.sort(),
    }
}

/// Clone a DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_clone(
    d: *mut DependencySet,
) -> *mut DependencySet {
    let set = try_ref_from_ptr!(d);
    Box::into_raw(Box::new(set.clone()))
}

/// Insert a Dependency into a DependencySet.
///
/// Returns false if an equivalent value already exists, otherwise true.
///
/// # Safety
/// The arguments must be valid DependencySet and Dependency pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_insert(
    d: *mut DependencySet,
    value: *mut Dependency,
) -> bool {
    let set = try_mut_from_ptr!(d);
    let spec = try_deref_from_ptr!(value);

    match (set.deref_mut(), spec.clone()) {
        (DependencySetWrapper::Dep(deps), DependencyWrapper::Dep(dep)) => deps.insert(dep),
        (DependencySetWrapper::String(deps), DependencyWrapper::String(dep)) => deps.insert(dep),
        (DependencySetWrapper::Uri(deps), DependencyWrapper::Uri(dep)) => deps.insert(dep),
        _ => panic!("invalid DependencySet and Dependency type combination"),
    }
}

/// Remove the last value from a DependencySet.
///
/// Returns NULL on nonexistence.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_pop(d: *mut DependencySet) -> *mut Dependency {
    let set = try_mut_from_ptr!(d);

    use DependencySetWrapper::*;
    let dep = match set.deref_mut() {
        Dep(deps) => deps.pop().map(Dependency::new_dep),
        String(deps) => deps.pop().map(|d| Dependency::new_string(d, set.set)),
        Uri(deps) => deps.pop().map(Dependency::new_uri),
    };

    dep.map(boxed).unwrap_or(ptr::null_mut())
}

/// Replace a Dependency for a given index in a DependencySet, returning the replaced value.
///
/// Returns NULL on index nonexistence or if the DependencySet already contains the given Dependency.
///
/// # Safety
/// The arguments must be valid DependencySet and Dependency pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_replace_index(
    d: *mut DependencySet,
    index: usize,
    value: *mut Dependency,
) -> *mut Dependency {
    let set = try_mut_from_ptr!(d);
    let spec = try_deref_from_ptr!(value);

    let dep = match (set.deref_mut(), spec) {
        (DependencySetWrapper::Dep(deps), DependencyWrapper::Dep(dep)) => deps
            .shift_replace_index(index, dep.clone())
            .map(Dependency::new_dep),
        (DependencySetWrapper::String(deps), DependencyWrapper::String(dep)) => deps
            .shift_replace_index(index, dep.clone())
            .map(|d| Dependency::new_string(d, set.set)),
        (DependencySetWrapper::Uri(deps), DependencyWrapper::Uri(dep)) => deps
            .shift_replace_index(index, dep.clone())
            .map(Dependency::new_uri),
        _ => panic!("invalid DependencySet and Dependency type combination"),
    };

    dep.map(boxed).unwrap_or(ptr::null_mut())
}

/// Replace a Dependency with another Dependency in a DependencySet, returning the replaced value.
///
/// Returns NULL on nonexistence or if the DependencySet already contains the given Dependency.
///
/// # Safety
/// The arguments must be valid DependencySet and Dependency pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_replace(
    d: *mut DependencySet,
    key: *const Dependency,
    value: *mut Dependency,
) -> *mut Dependency {
    let set = try_mut_from_ptr!(d);
    let key = try_deref_from_ptr!(key);
    let value = try_deref_from_ptr!(value);

    let dep = match (set.deref_mut(), key, value) {
        (DependencySetWrapper::Dep(deps), DependencyWrapper::Dep(k), DependencyWrapper::Dep(v)) => {
            deps.shift_replace(k, v.clone()).map(Dependency::new_dep)
        }
        (
            DependencySetWrapper::String(deps),
            DependencyWrapper::String(k),
            DependencyWrapper::String(v),
        ) => deps
            .shift_replace(k, v.clone())
            .map(|d| Dependency::new_string(d, set.set)),
        (DependencySetWrapper::Uri(deps), DependencyWrapper::Uri(k), DependencyWrapper::Uri(v)) => {
            deps.shift_replace(k, v.clone()).map(Dependency::new_uri)
        }
        _ => panic!("invalid DependencySet and Dependency type combination"),
    };

    dep.map(boxed).unwrap_or(ptr::null_mut())
}

/// Perform a set operation on two DependencySets, assigning to the first.
///
/// Returns NULL on error.
///
/// # Safety
/// The arguments must be valid DependencySet pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_assign_op_set(
    op: SetOp,
    d1: *mut DependencySet,
    d2: *mut DependencySet,
) -> *mut DependencySet {
    ffi_catch_panic! {
        use SetOp::*;
        let dep1 = try_mut_from_ptr!(d1);
        let dep2 = try_ref_from_ptr!(d2);
        match op {
            And => *dep1 &= dep2,
            Or => *dep1 |= dep2,
            Xor => *dep1 ^= dep2,
            Sub => *dep1 -= dep2,
        }
        d1
    }
}

/// Perform a set operation on two DependencySets, creating a new set.
///
/// Returns NULL on error.
///
/// # Safety
/// The arguments must be valid DependencySet pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_op_set(
    op: SetOp,
    d1: *mut DependencySet,
    d2: *mut DependencySet,
) -> *mut DependencySet {
    ffi_catch_panic! {
        use SetOp::*;
        let d1 = try_ref_from_ptr!(d1);
        let d2 = try_ref_from_ptr!(d2);
        let set = match op {
            And => d1 & d2,
            Or => d1 | d2,
            Xor => d1 ^ d2,
            Sub => d1 - d2,
        };
        Box::into_raw(Box::new(set))
    }
}

/// Return the formatted string for a DependencySet object.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_str(d: *mut DependencySet) -> *mut c_char {
    let deps = try_ref_from_ptr!(d);
    try_ptr_from_str!(deps.to_string())
}

/// Determine if two DependencySets are equal.
///
/// # Safety
/// The arguments must be valid DependencySet pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_eq(
    d1: *mut DependencySet,
    d2: *mut DependencySet,
) -> bool {
    let d1 = try_ref_from_ptr!(d1);
    let d2 = try_ref_from_ptr!(d2);
    d1.eq(d2)
}

/// Determine if a DependencySet contains a given Dependency.
///
/// # Safety
/// The arguments must be valid DependencySet and Dependency pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_contains_dependency(
    s: *mut DependencySet,
    d: *mut Dependency,
) -> bool {
    let s = try_deref_from_ptr!(s);
    let d = try_deref_from_ptr!(d);

    match (s, d) {
        (DependencySetWrapper::Dep(s), DependencyWrapper::Dep(d)) => s.contains(d),
        (DependencySetWrapper::String(s), DependencyWrapper::String(d)) => s.contains(d),
        (DependencySetWrapper::Uri(s), DependencyWrapper::Uri(d)) => s.contains(d),
        _ => false,
    }
}

/// Determine if a DependencySet contains a given raw string.
///
/// # Safety
/// The arguments must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_contains_str(
    d: *mut DependencySet,
    s: *const c_char,
) -> bool {
    let d = try_deref_from_ptr!(d);
    let s = try_str_from_ptr!(s);

    match d {
        DependencySetWrapper::Dep(d) => d.contains(s),
        DependencySetWrapper::String(d) => d.contains(s),
        DependencySetWrapper::Uri(d) => d.contains(s),
    }
}

/// Determine if a DependencySet contains a given UseDep.
///
/// # Safety
/// The arguments must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_contains_use_dep(
    d: *mut DependencySet,
    u: *mut use_dep::UseDep,
) -> bool {
    let d = try_deref_from_ptr!(d);
    let u = try_deref_from_ptr!(u);

    match d {
        DependencySetWrapper::Dep(d) => d.contains(u),
        DependencySetWrapper::String(d) => d.contains(u),
        DependencySetWrapper::Uri(d) => d.contains(u),
    }
}

/// Return the hash value for a DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_hash(d: *mut DependencySet) -> u64 {
    let deps = try_ref_from_ptr!(d);
    hash(deps)
}

/// Return a DependencySet's length.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_len(d: *mut DependencySet) -> usize {
    let deps = try_deref_from_ptr!(d);
    use DependencySetWrapper::*;
    match deps {
        Dep(d) => d.len(),
        String(d) => d.len(),
        Uri(d) => d.len(),
    }
}

/// Return an iterator for a DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter(
    d: *mut DependencySet,
) -> *mut DependencyIntoIter {
    let deps = try_ref_from_ptr!(d);
    let iter = match deps.deref().clone() {
        DependencySetWrapper::Dep(d) => DependencyIntoIter::Dep(deps.set, d.into_iter()),
        DependencySetWrapper::String(d) => DependencyIntoIter::String(deps.set, d.into_iter()),
        DependencySetWrapper::Uri(d) => DependencyIntoIter::Uri(deps.set, d.into_iter()),
    };
    Box::into_raw(Box::new(iter))
}

/// Return the next object from a DependencySet iterator.
///
/// Returns NULL when the iterator is empty.
///
/// # Safety
/// The argument must be a valid DependencyIntoIter pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_next(
    i: *mut DependencyIntoIter,
) -> *mut Dependency {
    let iter = try_mut_from_ptr!(i);
    iter.next().map(boxed).unwrap_or(ptr::null_mut())
}

/// Return the next object from the end of a DependencySet iterator.
///
/// Returns NULL when the iterator is empty.
///
/// # Safety
/// The argument must be a valid DependencyIntoIter pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_next_back(
    i: *mut DependencyIntoIter,
) -> *mut Dependency {
    let iter = try_mut_from_ptr!(i);
    iter.next_back().map(boxed).unwrap_or(ptr::null_mut())
}

/// Free a DependencySet iterator.
///
/// # Safety
/// The argument must be a valid DependencyIntoIter pointer or NULL.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_free(i: *mut DependencyIntoIter) {
    if !i.is_null() {
        unsafe { drop(Box::from_raw(i)) };
    }
}

/// Evaluate a Dependency.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_evaluate(
    d: *mut Dependency,
    options: *mut *mut c_char,
    len: usize,
    deps_len: *mut usize,
) -> *mut *mut Dependency {
    let dep = try_ref_from_ptr!(d);
    let options = unsafe { slice::from_raw_parts(options, len) };
    let options = options.iter().map(|p| try_str_from_ptr!(p)).collect();

    use DependencyWrapper::*;
    match dep.deref() {
        Dep(d) => {
            iter_to_array!(d.evaluate(&options).into_iter(), deps_len, |d| {
                Box::into_raw(Box::new(Dependency::new_dep(d.into_owned())))
            })
        }
        String(d) => {
            iter_to_array!(d.evaluate(&options).into_iter(), deps_len, |d| {
                Box::into_raw(Box::new(Dependency::new_string(d.into_owned(), dep.set)))
            })
        }
        Uri(d) => {
            iter_to_array!(d.evaluate(&options).into_iter(), deps_len, |d| {
                Box::into_raw(Box::new(Dependency::new_uri(d.into_owned())))
            })
        }
    }
}

/// Forcibly evaluate a Dependency.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_evaluate_force(
    d: *mut Dependency,
    force: bool,
    deps_len: *mut usize,
) -> *mut *mut Dependency {
    let dep = try_ref_from_ptr!(d);

    use DependencyWrapper::*;
    match dep.deref() {
        Dep(d) => {
            iter_to_array!(d.evaluate_force(force).into_iter(), deps_len, |d| {
                Box::into_raw(Box::new(Dependency::new_dep(d.into_owned())))
            })
        }
        String(d) => {
            iter_to_array!(d.evaluate_force(force).into_iter(), deps_len, |d| {
                Box::into_raw(Box::new(Dependency::new_string(d.into_owned(), dep.set)))
            })
        }
        Uri(d) => {
            iter_to_array!(d.evaluate_force(force).into_iter(), deps_len, |d| {
                Box::into_raw(Box::new(Dependency::new_uri(d.into_owned())))
            })
        }
    }
}

/// Return the conditional for a Dependency.
///
/// Returns NULL if the Dependency variant isn't conditional.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_conditional(
    d: *mut Dependency,
) -> *mut use_dep::UseDep {
    let d = try_deref_from_ptr!(d);

    use DependencyWrapper::*;
    let use_dep = match d {
        Dep(dep::Dependency::Conditional(u, _)) => Some(u.clone().into()),
        String(dep::Dependency::Conditional(u, _)) => Some(u.clone().into()),
        Uri(dep::Dependency::Conditional(u, _)) => Some(u.clone().into()),
        _ => None,
    };

    use_dep.map(boxed).unwrap_or(ptr::null_mut())
}

/// Compare two Dependencys returning -1, 0, or 1 if the first is less than, equal to, or greater
/// than the second, respectively.
///
/// # Safety
/// The arguments must be valid Dependency pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_cmp(
    d1: *mut Dependency,
    d2: *mut Dependency,
) -> c_int {
    let d1 = try_ref_from_ptr!(d1);
    let d2 = try_ref_from_ptr!(d2);

    match d1.cmp(d2) {
        Ordering::Less => -1,
        Ordering::Equal => 0,
        Ordering::Greater => 1,
    }
}

/// Determine if a Dependency contains a given Dependency.
///
/// # Safety
/// The arguments must be valid Dependency pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_contains_dependency(
    d1: *mut Dependency,
    d2: *mut Dependency,
) -> bool {
    let d1 = try_deref_from_ptr!(d1);
    let d2 = try_deref_from_ptr!(d2);

    use DependencyWrapper::*;
    match (d1, d2) {
        (Dep(d1), Dep(d2)) => d1.contains(d2),
        (String(d1), String(d2)) => d1.contains(d2),
        (Uri(d1), Uri(d2)) => d1.contains(d2),
        _ => false,
    }
}

/// Determine if a Dependency contains a given raw string.
///
/// # Safety
/// The arguments must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_contains_str(
    d: *mut Dependency,
    s: *const c_char,
) -> bool {
    let d = try_deref_from_ptr!(d);
    let s = try_str_from_ptr!(s);

    match d {
        DependencyWrapper::Dep(d) => d.contains(s),
        DependencyWrapper::String(d) => d.contains(s),
        DependencyWrapper::Uri(d) => d.contains(s),
    }
}

/// Determine if a Dependency contains a given UseDep.
///
/// # Safety
/// The arguments must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_contains_use_dep(
    d: *mut Dependency,
    u: *mut use_dep::UseDep,
) -> bool {
    let d = try_deref_from_ptr!(d);
    let u = try_deref_from_ptr!(u);

    match d {
        DependencyWrapper::Dep(d) => d.contains(u),
        DependencyWrapper::String(d) => d.contains(u),
        DependencyWrapper::Uri(d) => d.contains(u),
    }
}

/// Return the hash value for a Dependency.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_hash(d: *mut Dependency) -> u64 {
    let deps = try_ref_from_ptr!(d);
    hash(deps)
}

/// Return a Dependency's length.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_len(d: *mut Dependency) -> usize {
    let deps = try_deref_from_ptr!(d);
    use DependencyWrapper::*;
    match deps {
        Dep(d) => d.len(),
        String(d) => d.len(),
        Uri(d) => d.len(),
    }
}

/// Free a Dependency object.
///
/// # Safety
/// The argument must be a Dependency pointer or NULL.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_free(r: *mut Dependency) {
    if !r.is_null() {
        unsafe { drop(Box::from_raw(r)) };
    }
}

/// Return the formatted string for a Dependency object.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_str(d: *mut Dependency) -> *mut c_char {
    let deps = try_ref_from_ptr!(d);
    try_ptr_from_str!(deps.to_string())
}

/// Return an iterator for a Dependency.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_into_iter(
    d: *mut Dependency,
) -> *mut DependencyIntoIter {
    let deps = try_ref_from_ptr!(d);
    let iter = match deps.deref().clone() {
        DependencyWrapper::Dep(d) => DependencyIntoIter::Dep(deps.set, d.into_iter()),
        DependencyWrapper::String(d) => DependencyIntoIter::String(deps.set, d.into_iter()),
        DependencyWrapper::Uri(d) => DependencyIntoIter::Uri(deps.set, d.into_iter()),
    };
    Box::into_raw(Box::new(iter))
}

/// Return a flatten iterator for a Dependency.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_into_iter_flatten(
    d: *mut Dependency,
) -> *mut DependencyIntoIterFlatten {
    let dep = try_deref_from_ptr!(d);
    let iter = match dep.clone() {
        DependencyWrapper::Dep(d) => DependencyIntoIterFlatten::Dep(d.into_iter_flatten()),
        DependencyWrapper::String(d) => DependencyIntoIterFlatten::String(d.into_iter_flatten()),
        DependencyWrapper::Uri(d) => DependencyIntoIterFlatten::Uri(d.into_iter_flatten()),
    };
    Box::into_raw(Box::new(iter))
}

/// Return a flatten iterator for a DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_flatten(
    d: *mut DependencySet,
) -> *mut DependencyIntoIterFlatten {
    let deps = try_deref_from_ptr!(d);
    let iter = match deps.clone() {
        DependencySetWrapper::Dep(d) => DependencyIntoIterFlatten::Dep(d.into_iter_flatten()),
        DependencySetWrapper::String(d) => DependencyIntoIterFlatten::String(d.into_iter_flatten()),
        DependencySetWrapper::Uri(d) => DependencyIntoIterFlatten::Uri(d.into_iter_flatten()),
    };
    Box::into_raw(Box::new(iter))
}

/// Return the next object from a flatten iterator.
///
/// Returns NULL when the iterator is empty.
///
/// # Safety
/// The argument must be a valid DependencyIntoIterFlatten pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_flatten_next(
    i: *mut DependencyIntoIterFlatten,
) -> *mut c_void {
    let iter = try_mut_from_ptr!(i);
    iter.next().unwrap_or(ptr::null_mut())
}

/// Free a flatten iterator.
///
/// # Safety
/// The argument must be a valid DependencyIntoIterFlatten pointer or NULL.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_flatten_free(
    i: *mut DependencyIntoIterFlatten,
) {
    if !i.is_null() {
        unsafe { drop(Box::from_raw(i)) };
    }
}

/// Return a recursive iterator for a Dependency.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_into_iter_recursive(
    d: *mut Dependency,
) -> *mut DependencyIntoIterRecursive {
    let dep = try_ref_from_ptr!(d);
    let iter = match dep.deref().clone() {
        DependencyWrapper::Dep(d) => {
            DependencyIntoIterRecursive::Dep(dep.set, d.into_iter_recursive())
        }
        DependencyWrapper::String(d) => {
            DependencyIntoIterRecursive::String(dep.set, d.into_iter_recursive())
        }
        DependencyWrapper::Uri(d) => {
            DependencyIntoIterRecursive::Uri(dep.set, d.into_iter_recursive())
        }
    };
    Box::into_raw(Box::new(iter))
}

/// Return a recursive iterator for a DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_recursive(
    d: *mut DependencySet,
) -> *mut DependencyIntoIterRecursive {
    let deps = try_ref_from_ptr!(d);
    let iter = match deps.deref().clone() {
        DependencySetWrapper::Dep(d) => {
            DependencyIntoIterRecursive::Dep(deps.set, d.into_iter_recursive())
        }
        DependencySetWrapper::String(d) => {
            DependencyIntoIterRecursive::String(deps.set, d.into_iter_recursive())
        }
        DependencySetWrapper::Uri(d) => {
            DependencyIntoIterRecursive::Uri(deps.set, d.into_iter_recursive())
        }
    };
    Box::into_raw(Box::new(iter))
}

/// Return the next object from a recursive iterator.
///
/// Returns NULL when the iterator is empty.
///
/// # Safety
/// The argument must be a valid DependencyIntoIterRecursive pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_recursive_next(
    i: *mut DependencyIntoIterRecursive,
) -> *mut Dependency {
    let iter = try_mut_from_ptr!(i);
    iter.next().map(boxed).unwrap_or(ptr::null_mut())
}

/// Free a recursive iterator.
///
/// # Safety
/// The argument must be a valid DependencyIntoIterRecursive pointer or NULL.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_recursive_free(
    i: *mut DependencyIntoIterRecursive,
) {
    if !i.is_null() {
        unsafe { drop(Box::from_raw(i)) };
    }
}

/// Return a conditionals iterator for a Dependency.
///
/// # Safety
/// The argument must be a valid Dependency pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_into_iter_conditionals(
    d: *mut Dependency,
) -> *mut DependencyIntoIterConditionals {
    let dep = try_ref_from_ptr!(d);
    let iter = match dep.deref().clone() {
        DependencyWrapper::Dep(d) => {
            DependencyIntoIterConditionals::Dep(d.into_iter_conditionals())
        }
        DependencyWrapper::String(d) => {
            DependencyIntoIterConditionals::String(d.into_iter_conditionals())
        }
        DependencyWrapper::Uri(d) => {
            DependencyIntoIterConditionals::Uri(d.into_iter_conditionals())
        }
    };
    Box::into_raw(Box::new(iter))
}

/// Return a conditionals iterator for a DependencySet.
///
/// # Safety
/// The argument must be a valid DependencySet pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_conditionals(
    d: *mut DependencySet,
) -> *mut DependencyIntoIterConditionals {
    let deps = try_ref_from_ptr!(d);
    let iter = match deps.deref().clone() {
        DependencySetWrapper::Dep(d) => {
            DependencyIntoIterConditionals::Dep(d.into_iter_conditionals())
        }
        DependencySetWrapper::String(d) => {
            DependencyIntoIterConditionals::String(d.into_iter_conditionals())
        }
        DependencySetWrapper::Uri(d) => {
            DependencyIntoIterConditionals::Uri(d.into_iter_conditionals())
        }
    };
    Box::into_raw(Box::new(iter))
}

/// Return the next object from a conditionals iterator.
///
/// Returns NULL when the iterator is empty.
///
/// # Safety
/// The argument must be a valid DependencyIntoIterConditionals pointer.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_conditionals_next(
    i: *mut DependencyIntoIterConditionals,
) -> *mut use_dep::UseDep {
    let iter = try_mut_from_ptr!(i);
    iter.next()
        .map(|x| boxed(x.into()))
        .unwrap_or(ptr::null_mut())
}

/// Free a conditionals iterator.
///
/// # Safety
/// The argument must be a valid DependencyIntoIterConditionals pointer or NULL.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_into_iter_conditionals_free(
    i: *mut DependencyIntoIterConditionals,
) {
    if !i.is_null() {
        unsafe { drop(Box::from_raw(i)) };
    }
}

/// Free a DependencySet.
///
/// # Safety
/// The argument must be a DependencySet pointer or NULL.
#[no_mangle]
pub unsafe extern "C" fn pkgcraft_dependency_set_free(d: *mut DependencySet) {
    if !d.is_null() {
        unsafe { drop(Box::from_raw(d)) };
    }
}