alpm_types/
version.rs

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
use std::{
    cmp::Ordering,
    fmt::{Display, Formatter},
    iter::Peekable,
    num::NonZeroUsize,
    str::{CharIndices, Chars, FromStr},
};

use lazy_regex::{lazy_regex, Lazy};
use regex::Regex;
use semver::Version as SemverVersion;

use crate::error::Error;
use crate::Architecture;

pub(crate) static PKGREL_REGEX: Lazy<Regex> = lazy_regex!(r"^[1-9]+[0-9]*(|[.]{1}[1-9]+[0-9]*)$");
pub(crate) static PKGVER_REGEX: Lazy<Regex> = lazy_regex!(r"^([[:alnum:]][[:alnum:]_+.]*)$");

/// The version and architecture of a build tool
///
/// `BuildToolVersion` is used in conjunction with `BuildTool` to denote the specific build tool a
/// package is built with. A `BuildToolVersion` wraps a `Version` (that is guaranteed to have a
/// `Pkgrel`) and an `Architecture`.
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::BuildToolVersion;
///
/// assert!(BuildToolVersion::from_str("1-1-any").is_ok());
/// assert!(BuildToolVersion::from_str("1").is_ok());
/// assert!(BuildToolVersion::from_str("1-1").is_err());
/// assert!(BuildToolVersion::from_str("1-1-foo").is_err());
/// ```
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct BuildToolVersion {
    version: Version,
    architecture: Option<Architecture>,
}

impl BuildToolVersion {
    /// Create a new BuildToolVersion
    pub fn new(version: Version, architecture: Option<Architecture>) -> Self {
        BuildToolVersion {
            version,
            architecture,
        }
    }

    /// Return a reference to the Architecture
    pub fn architecture(&self) -> &Option<Architecture> {
        &self.architecture
    }

    /// Return a reference to the Version
    pub fn version(&self) -> &Version {
        &self.version
    }
}

impl FromStr for BuildToolVersion {
    type Err = Error;
    /// Create an BuildToolVersion from a string and return it in a Result
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        const VERSION_DELIMITER: char = '-';
        match s.rsplit_once(VERSION_DELIMITER) {
            Some((version, architecture)) => match Architecture::from_str(architecture) {
                Ok(architecture) => Ok(BuildToolVersion {
                    version: Version::with_pkgrel(version)?,
                    architecture: Some(architecture),
                }),
                Err(err) => Err(err.into()),
            },
            None => Ok(BuildToolVersion {
                version: Version::from_str(s)?,
                architecture: None,
            }),
        }
    }
}

impl Display for BuildToolVersion {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        if let Some(architecture) = &self.architecture {
            write!(fmt, "{}-{}", self.version, architecture)
        } else {
            write!(fmt, "{}", self.version)
        }
    }
}

/// An epoch of a package
///
/// Epoch is used to indicate the downgrade of a package and is prepended to a version, delimited by
/// a `":"` (e.g. `1:` is added to `0.10.0-1` to form `1:0.10.0-1` which then orders newer than
/// `1.0.0-1`).
///
/// An Epoch wraps a usize that is guaranteed to be greater than `0`.
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::Epoch;
///
/// assert!(Epoch::from_str("1").is_ok());
/// assert!(Epoch::from_str("0").is_err());
/// ```
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Epoch(pub NonZeroUsize);

impl Epoch {
    /// Create a new Epoch
    pub fn new(epoch: NonZeroUsize) -> Self {
        Epoch(epoch)
    }
}

impl FromStr for Epoch {
    type Err = Error;
    /// Create an Epoch from a string and return it in a Result
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.parse() {
            Ok(epoch) => Ok(Epoch(epoch)),
            Err(source) => Err(Error::InvalidInteger {
                kind: source.kind().clone(),
            }),
        }
    }
}

impl Display for Epoch {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self.0)
    }
}

/// A pkgrel of a package
///
/// Pkgrel is used to indicate the build version of a package and is appended to a version,
/// delimited by a `"-"` (e.g. `-2` is added to `1.0.0` to form `1.0.0-2` which then orders newer
/// than `1.0.0-1`).
///
/// A Pkgrel wraps a String which is guaranteed to not start with a `"0"`, to contain only numeric
/// characters (optionally delimited by a single `"."`, which must be followed by at least one
/// non-`"0"` numeric character).
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::Pkgrel;
///
/// assert!(Pkgrel::new("1".to_string()).is_ok());
/// assert!(Pkgrel::new("1.1".to_string()).is_ok());
/// assert!(Pkgrel::new("0".to_string()).is_err());
/// assert!(Pkgrel::new("0.1".to_string()).is_err());
/// assert!(Pkgrel::new("1.0".to_string()).is_err());
/// ```
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Pkgrel(String);

impl Pkgrel {
    /// Create a new Pkgrel from a string and return it in a Result
    pub fn new(pkgrel: String) -> Result<Self, Error> {
        Pkgrel::from_str(pkgrel.as_str())
    }

    /// Return a reference to the inner type
    pub fn inner(&self) -> &str {
        &self.0
    }
}

impl FromStr for Pkgrel {
    type Err = Error;
    /// Create a Pkgrel from a string and return it in a Result
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if PKGREL_REGEX.is_match(s) {
            Ok(Pkgrel(s.to_string()))
        } else {
            Err(Error::RegexDoesNotMatch {
                value: s.to_string(),
                regex_type: "pkgrel".to_string(),
                regex: PKGREL_REGEX.to_string(),
            })
        }
    }
}

impl Display for Pkgrel {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self.inner())
    }
}

/// A pkgver of a package
///
/// Pkgver is used to denote the upstream version of a package.
///
/// A Pkgver wraps a `String`, which is guaranteed to only contain alphanumeric characters, `"_"`,
/// `"+"` or `"."`, but to not start with a `"_"`, a `"+"` or a `"."` character and to be at least
/// one char long.
///
/// NOTE: This implementation of Pkgver is stricter than that of libalpm/pacman. It does not allow
/// empty strings `""`, or chars that are not in the allowed set, or `"."` as the first character.
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::Pkgver;
///
/// assert!(Pkgver::new("1".to_string()).is_ok());
/// assert!(Pkgver::new("1.1".to_string()).is_ok());
/// assert!(Pkgver::new("foo".to_string()).is_ok());
/// assert!(Pkgver::new("0".to_string()).is_ok());
/// assert!(Pkgver::new(".0.1".to_string()).is_err());
/// assert!(Pkgver::new("_1.0".to_string()).is_err());
/// assert!(Pkgver::new("+1.0".to_string()).is_err());
/// ```
#[derive(Clone, Debug, Eq)]
pub struct Pkgver(pub(crate) String);

impl Pkgver {
    /// Create a new Pkgver from a string and return it in a Result
    pub fn new(pkgver: String) -> Result<Self, Error> {
        Pkgver::from_str(pkgver.as_str())
    }

    /// Return a reference to the inner type
    pub fn inner(&self) -> &str {
        &self.0
    }

    /// Return an iterator over all segments of this version.
    pub fn segments(&self) -> VersionSegments {
        VersionSegments::new(&self.0)
    }
}

impl FromStr for Pkgver {
    type Err = Error;
    /// Create a Pkgver from a string and return it in a Result
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if PKGVER_REGEX.is_match(s) {
            Ok(Pkgver(s.to_string()))
        } else {
            Err(Error::RegexDoesNotMatch {
                value: s.to_string(),
                regex_type: "pkgver".to_string(),
                regex: PKGVER_REGEX.to_string(),
            })
        }
    }
}

impl Display for Pkgver {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self.inner())
    }
}

/// This struct represents a single segment in a version string.
/// `VersionSegment`s are returned by the [VersionSegments] iterator, which is responsible for
/// splitting a version string into its segments.
///
/// Version strings are split according to the following rules:
/// - Non-alphanumeric characters always count as delimiters (`.`, `-`, `$`, etc.).
/// - Each segment also contains the info about the amount of leading delimiters for that segment.
///   Leading delimiters that directly follow after one another are grouped together. The length of
///   the delimiters is important, as it plays a crucial role in the algorithm that determines which
///   version is newer.
///
///   `1...a` would be represented as:
///
///   ```text
///   [
///     (segment: "1", delimiters: 0),
///     (segment: "a", delimiters: 3)
///   ]
///   ```
/// - There's no differentiation between different delimiters. `'$$$' == '...' == '.$-'`
/// - Alphanumeric strings are also split into individual sub-segments. This is done by walking over
///   the string and splitting it every time a switch from alphabetic to numeric is detected or vice
///   versa.
///
///   `1.1asdf123.0` would be represented as:
///
///   ```text
///   [
///     (segment: "1", delimiters: 0),
///     (segment: "1", delimiters: 1)
///     (segment: "asdf", delimiters: 0)
///     (segment: "123", delimiters: 0)
///     (segment: "0", delimiters: 1)
///   ]
///   ```
/// - Trailing delimiters are encoded as an empty string.
///
///   `1...` would be represented as:
///
///   ```text
///   [
///     (segment: "1", delimiters: 0),
///     (segment: "", delimiters: 3),
///   ]
///   ```
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct VersionSegment<'a> {
    /// The string representation of the next segment
    pub segment: &'a str,
    /// The amount of leading delimiters that were found for this segment
    pub delimiters: usize,
}

impl<'a> VersionSegment<'a> {
    /// Create a new instance of a VersionSegment consisting of the segment's string and the amount
    /// of leading delimiters.
    pub fn new(segment: &'a str, delimiters: usize) -> Self {
        Self {
            segment,
            delimiters,
        }
    }

    /// Passhrough to `self.segment.is_empty()` for convenience purposes.
    pub fn is_empty(&self) -> bool {
        self.segment.is_empty()
    }

    /// Passhrough to `self.segment.chars()` for convenience purposes.
    pub fn chars(&self) -> Chars<'a> {
        self.segment.chars()
    }

    /// Passhrough `self.segment.parse()` for convenience purposes.
    pub fn parse<T: FromStr>(&self) -> Result<T, T::Err> {
        FromStr::from_str(self.segment)
    }

    /// Compare the `self`'s segment string with segment string of `other`.
    pub fn str_cmp(&self, other: &VersionSegment) -> Ordering {
        self.segment.cmp(other.segment)
    }
}

/// An [Iterator] over all [VersionSegment]s of an upstream version string.
/// Check the documentation on [VersionSegment] to see how a string is split into segments.
///
/// Important note:
/// Trailing delimiters will also produce a trailing [VersionSegment] with an empty string.
///
/// This iterator is capable of handling utf-8 strings.
/// However, non alphanumeric chars are still interpreted as delimiters.
pub struct VersionSegments<'a> {
    /// The original version string. We need that reference so we can get some string
    /// slices based on indices later on.
    version: &'a str,
    /// An iterator over the version's chars and their respective start byte's index.
    version_chars: Peekable<CharIndices<'a>>,
}

impl<'a> VersionSegments<'a> {
    /// Create a new instance of a VersionSegments iterator.
    pub fn new(version: &'a str) -> Self {
        VersionSegments {
            version,
            version_chars: version.char_indices().peekable(),
        }
    }
}

impl<'a> Iterator for VersionSegments<'a> {
    type Item = VersionSegment<'a>;

    /// Get the next [VersionSegment] of this version string.
    fn next(&mut self) -> Option<VersionSegment<'a>> {
        // Used to track the number of delimiters the next segment is prefixed with.
        let mut delimiter_count = 0;

        // First up, get the delimiters out of the way.
        // Peek at the next char, if it's a delimiter, consume it and increase the delimiter count.
        while let Some((_, char)) = self.version_chars.peek() {
            // An alphanumeric char indicates that we reached the next segment.
            if char.is_alphanumeric() {
                break;
            }

            self.version_chars.next();
            delimiter_count += 1;
            continue;
        }

        // Get the next char. If there's no further char, we reached the end of the version string.
        let Some((first_index, first_char)) = self.version_chars.next() else {
            // We're at the end of the string and now have to differentiate between two cases:

            // 1. There are no trailing delimiters. We can just return `None` as we truly reached
            //    the end.
            if delimiter_count == 0 {
                return None;
            }

            // 2. There's no further segment, but there were some trailing delimiters. The
            //    comparison algorithm considers this case which is why we have to somehow encode
            //    it. We do so by returning an empty segment.
            return Some(VersionSegment::new("", delimiter_count));
        };

        // Cache the last valid char + index that was checked. We need this to
        // calculate the offset in case the last char is a multi-byte UTF-8 char.
        let mut last_char = first_char;
        let mut last_char_index = first_index;

        // The following section now handles the splitting of an alphanumeric string into its
        // sub-segments. As described in the [VersionSegment] docs, the string needs to be split
        // every time a switch from alphabetic to numeric or vice versa is detected.

        let is_numeric = first_char.is_numeric();

        if is_numeric {
            // Go through chars until we hit a non-numeric char or reached the end of the string.
            #[allow(clippy::while_let_on_iterator)]
            while let Some((index, next_char)) =
                self.version_chars.next_if(|(_, peek)| peek.is_numeric())
            {
                last_char_index = index;
                last_char = next_char;
            }
        } else {
            // Go through chars until we hit a non-alphabetic char or reached the end of the string.
            #[allow(clippy::while_let_on_iterator)]
            while let Some((index, next_char)) =
                self.version_chars.next_if(|(_, peek)| peek.is_alphabetic())
            {
                last_char_index = index;
                last_char = next_char;
            }
        }

        // Create a subslice based on the indices of the first and last char.
        // The last char might be multi-byte, which is why we add its length.
        let segment_slice = &self.version[first_index..(last_char_index + last_char.len_utf8())];

        Some(VersionSegment::new(segment_slice, delimiter_count))
    }
}

impl Ord for Pkgver {
    /// This block implements the logic to determine which of two package versions is newer or
    /// whether they're considered equal.
    ///
    /// This logic is surprisingly complex as it mirrors the current C-alpmlib implementation for
    /// backwards compatibility reasons.
    /// <https://gitlab.archlinux.org/pacman/pacman/-/blob/a2d029388c7c206f5576456f91bfbea2dca98c96/lib/libalpm/version.c#L83-217>
    fn cmp(&self, other: &Self) -> Ordering {
        // Equal strings are considered equal versions.
        if self.inner() == other.inner() {
            return Ordering::Equal;
        }

        let mut self_segments = self.segments().peekable();
        let mut other_segments = other.segments().peekable();

        // Loop through both versions' segments and compare them.
        loop {
            // Try to get the next segments
            let self_segment = self_segments.next();
            let other_segment = other_segments.next();

            // Make sure that there's a next segment for both versions.
            let (self_segment, other_segment) = match (self_segment, other_segment) {
                // Both segments exist, we continue after match.
                (Some(self_seg), Some(other_seg)) => (self_seg, other_seg),

                // Both versions reached their end and are thereby equal.
                (None, None) => return Ordering::Equal,

                // One version is longer than the other.
                // Sadly, this isn't trivial to handle.
                //
                // The rules are as follows:
                // Versions with at least two additional segments are always newer.
                // -> `1.a.0` > `1`
                //        ⤷ Two more segment, include one delimiter
                // -> `1.a0` > `1`
                //        ⤷ Two more segment, thereby an alphanumerical string.
                //
                // If one version is exactly one segment and has a delimiter, it's also considered
                // newer.
                // -> `1.0` > `1`
                // -> `1.a` > `1`
                //      ⤷ Delimiter exists, thereby newer
                //
                // If one version is exactly one segment longer and that segment is
                // purely alphabetic **without** a leading delimiter, that segment is considered
                // older. The reason for this is to handle pre-releases (e.g. alpha/beta).
                // -> `1.0alpha` > `1.0`
                //          ⤷ Purely alphabetic last segment, without delimiter and thereby older.
                (Some(seg), None) => {
                    // There's at least one more segment, making `Self` effectively newer.
                    // It's either an alphanumeric string or another segment separated with a
                    // delimiter.
                    if self_segments.next().is_some() {
                        return Ordering::Greater;
                    }

                    // We now know that this is also the last segment of `self`.
                    // If the current segment has a leading delimiter, it's also considered newer.
                    if seg.delimiters > 0 {
                        return Ordering::Greater;
                    }

                    // If all chars are alphabetic, `self` is consider older.
                    if !seg.is_empty() && seg.chars().all(char::is_alphabetic) {
                        return Ordering::Less;
                    }

                    return Ordering::Greater;
                }

                // This is the same logic as above, but inverted.
                (None, Some(seg)) => {
                    if other_segments.next().is_some() {
                        return Ordering::Less;
                    }
                    if seg.delimiters > 0 {
                        return Ordering::Less;
                    }
                    if !seg.is_empty() && seg.chars().all(char::is_alphabetic) {
                        return Ordering::Greater;
                    }
                    return Ordering::Less;
                }
            };

            // Special case:
            // One or both of the segments is empty. That means that the end of the version string
            // has been reached, but there were some trailing delimiters.
            // Possible examples of how this might look:
            // `1.0.` < `1.0.0`
            // `1.0.` == `1.0.`
            // `1.0.alpha` < `1.0.`
            if other_segment.is_empty() && self_segment.is_empty() {
                // Both reached the end of their version with a trailing delimiter.
                // Counterintuitively, the trailing delimiter count is not considered and both
                // versions are considered equal
                // `1.0....` == `1.0.`
                return Ordering::Equal;
            } else if self_segment.is_empty() {
                // Check if there's at least one other segment on the `other` version.
                // If so, that one is always considered newer.
                // `1.0.1.1` > `1.0.`
                // `1.0.alpha1` > `1.0.`
                // `1.0.alpha.1` > `1.0.`
                //           ⤷ More segments and thereby always newer
                if other_segments.peek().is_some() {
                    return Ordering::Less;
                }

                // In case there's no further segment, both versions reached the last segment.
                // We now have to consider the special case where `other` is purely alphabetic.
                // If that's the case, `self` will be considered newer, as the alphabetic string
                // indicates a pre-release,
                // `1.0.` > `1.0.alpha`.
                //                   ⤷ Purely alphabetic last segment and thereby older.
                //
                // Also, we know that `other_segment` isn't empty at this point.
                if other_segment.chars().all(char::is_alphabetic) {
                    return Ordering::Greater;
                }

                // In all other cases, `other` is newer.
                return Ordering::Less;
            } else if other_segment.is_empty() {
                // Check docs above, as it's the same logic as above, just inverted.
                if self_segments.peek().is_some() {
                    return Ordering::Greater;
                }

                if self_segment.chars().all(char::is_alphabetic) {
                    return Ordering::Less;
                }

                return Ordering::Greater;
            }

            // We finally reached the end handling special cases when the version string ended.
            // From now on, we know that we have two actual segments that might be prefixed by
            // some delimiters.

            // Special case:
            // If one of the segments has more leading delimiters as the other, it's considered
            // newer.
            // `1..0.0` > `1.2.0`
            //         ⤷ Two delimiters, thereby always newer.
            // `1..0.0` < `1..2.0`
            //                ⤷ Same amount of delimiters, now `2 > 0`
            if self_segment.delimiters != other_segment.delimiters {
                return self_segment.delimiters.cmp(&other_segment.delimiters);
            }

            // Check whether any of the segments are numeric.
            // Numeric segments are always considered newer than non-numeric segments.
            // E.g. `1.0.0` > `1.lol.0`
            //         ⤷ `0` vs `lol`. `0` is purely numeric and bigger than a alphanumeric one.
            let self_is_numeric =
                !self_segment.is_empty() && self_segment.chars().all(char::is_numeric);
            let other_is_numeric =
                !other_segment.is_empty() && other_segment.chars().all(char::is_numeric);

            if self_is_numeric && !other_is_numeric {
                return Ordering::Greater;
            } else if !self_is_numeric && other_is_numeric {
                return Ordering::Less;
            }

            // In case both are numeric, we do a number comparison.
            // We can parse the string as we know that they only consist of digits, hence the
            // unwrap.
            //
            // Trailing zeroes are to be ignored, which is automatically done by Rust's number
            // parser. E.g. `1.0001.1` == `1.1.1`
            //                  ⤷ `000` is ignored in comparison.
            if self_is_numeric && other_is_numeric {
                let ordering = self_segment
                    .parse::<usize>()
                    .unwrap()
                    .cmp(&other_segment.parse::<usize>().unwrap());
                match ordering {
                    Ordering::Less => return Ordering::Less,
                    Ordering::Equal => (),
                    Ordering::Greater => return Ordering::Greater,
                }

                // However, there is a special case that needs to be handled when both numbers are
                // considered equal.
                //
                // To have a name for the following edge-case, let's call these "higher-level
                // segments". Higher-level segments are string segments that aren't separated with
                // a delimiter. E.g. on `1.10test11` the string `10test11` would be a
                // higher-level segment that's returned as segments of:
                //
                // `['10', 'test', '11']`
                //
                // The rule is:
                // Pure numeric higher-level segments are superior to mixed alphanumeric segments.
                // -> `1.10` > `1.11a1`
                // -> `1.10` > `1.11a1.2`
                //                  ⤷ `11a1` is alphanumeric and smaller than pure numerics.
                //
                // The current higher-level segment is considered purely numeric if the current
                // segment is numeric and the next segment is split via delimiter,
                // which indicates that a new higher-level segment has started. A
                // follow-up alphabetic segment in the same higher-level
                // segment wouldn't have a delimiter.
                //
                // If there's no further segment, we reached the end of the version string, also
                // indicating a purely numeric string.
                let other_is_pure_numeric = other_segments
                    .peek()
                    .map(|seg| seg.delimiters > 0)
                    .unwrap_or(true);
                let self_is_pure_numeric = self_segments
                    .peek()
                    .map(|seg| seg.delimiters > 0)
                    .unwrap_or(true);

                // One is purely numeric, the other isn't. We can return early.
                if self_is_pure_numeric && !other_is_pure_numeric {
                    return Ordering::Greater;
                } else if !self_is_pure_numeric && other_is_pure_numeric {
                    return Ordering::Less;
                }

                // Now we know that both are either numeric or alphanumeric and can take a look at
                // the next segment.
                continue;
            }
            // At this point, we know that the segments are alphabetic.
            // We do a simple string comparison to determine the newer version.
            // If the strings are equal, we check the next segments.
            match self_segment.str_cmp(&other_segment) {
                Ordering::Less => return Ordering::Less,
                Ordering::Equal => continue,
                Ordering::Greater => return Ordering::Greater,
            }
        }
    }
}

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

impl PartialEq for Pkgver {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other).is_eq()
    }
}

/// The schema version of a type
///
/// A `SchemaVersion` wraps a `semver::Version`, which means that the tracked version should follow [semver](https://semver.org).
/// However, for backwards compatibility reasons it is possible to initialize a `SchemaVersion`
/// using a non-semver compatible string, *if* it can be parsed to a single `u64` (e.g. `"1"`).
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::SchemaVersion;
///
/// // create SchemaVersion from str
/// let version_one = SchemaVersion::from_str("1.0.0").unwrap();
/// let version_also_one = SchemaVersion::from_str("1").unwrap();
/// assert_eq!(version_one, version_also_one);
///
/// // format as String
/// assert_eq!("1.0.0", format!("{}", version_one));
/// assert_eq!("1.0.0", format!("{}", version_also_one));
/// ```
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct SchemaVersion(SemverVersion);

impl SchemaVersion {
    /// Create a new SchemaVersion
    pub fn new(version: SemverVersion) -> Self {
        SchemaVersion(version)
    }

    /// Return a reference to the inner type
    pub fn inner(&self) -> &SemverVersion {
        &self.0
    }
}

impl FromStr for SchemaVersion {
    type Err = Error;
    /// Create a new SchemaVersion from a string
    ///
    /// When providing a non-semver string with only a number (i.e. no minor or patch version), the
    /// number is treated as the major version (e.g. `"23"` -> `"23.0.0"`).
    fn from_str(s: &str) -> Result<SchemaVersion, Self::Err> {
        if !s.contains('.') {
            match s.parse() {
                Ok(major) => Ok(SchemaVersion(SemverVersion::new(major, 0, 0))),
                Err(e) => Err(Error::InvalidInteger {
                    kind: e.kind().clone(),
                }),
            }
        } else {
            match SemverVersion::parse(s) {
                Ok(version) => Ok(SchemaVersion(version)),
                Err(e) => Err(Error::InvalidSemver {
                    kind: e.to_string(),
                }),
            }
        }
    }
}

impl Display for SchemaVersion {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self.0)
    }
}

/// A version of a package
///
/// A `Version` tracks an optional `Epoch`, a `Pkgver` and an optional `Pkgrel`.
///
/// ## Examples
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::{Epoch, Pkgrel, Pkgver, Version};
///
/// let version = Version::from_str("1:2-3").unwrap();
/// assert_eq!(version.epoch, Some(Epoch::from_str("1").unwrap()));
/// assert_eq!(version.pkgver, Pkgver::new("2".to_string()).unwrap());
/// assert_eq!(version.pkgrel, Some(Pkgrel::new("3".to_string()).unwrap()));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Version {
    pub pkgver: Pkgver,
    pub epoch: Option<Epoch>,
    pub pkgrel: Option<Pkgrel>,
}

impl Version {
    /// Create a new Version
    pub fn new(pkgver: Pkgver, epoch: Option<Epoch>, pkgrel: Option<Pkgrel>) -> Self {
        Version {
            pkgver,
            epoch,
            pkgrel,
        }
    }

    /// Create a new Version, which is guaranteed to have a Pkgrel
    pub fn with_pkgrel(version: &str) -> Result<Self, Error> {
        let version = Version::from_str(version)?;
        if version.pkgrel.is_some() {
            Ok(version)
        } else {
            Err(Error::MissingComponent {
                component: "pkgrel",
            })
        }
    }

    /// Compare two Versions and return a number
    ///
    /// The comparison algorithm is based on libalpm/ pacman's vercmp behavior.
    ///
    /// * `1` if `a` is newer than `b`
    /// * `0` if `a` and `b` are considered to be the same version
    /// * `-1` if `a` is older than `b`
    ///
    /// ## Examples
    /// ```
    /// use std::str::FromStr;
    ///
    /// use alpm_types::Version;
    ///
    /// assert_eq!(
    ///     Version::vercmp(
    ///         &Version::from_str("1.0.0").unwrap(),
    ///         &Version::from_str("0.1.0").unwrap()
    ///     ),
    ///     1
    /// );
    /// assert_eq!(
    ///     Version::vercmp(
    ///         &Version::from_str("1.0.0").unwrap(),
    ///         &Version::from_str("1.0.0").unwrap()
    ///     ),
    ///     0
    /// );
    /// assert_eq!(
    ///     Version::vercmp(
    ///         &Version::from_str("0.1.0").unwrap(),
    ///         &Version::from_str("1.0.0").unwrap()
    ///     ),
    ///     -1
    /// );
    /// ```
    pub fn vercmp(a: &Version, b: &Version) -> i8 {
        match a.cmp(b) {
            Ordering::Less => -1,
            Ordering::Equal => 0,
            Ordering::Greater => 1,
        }
    }
}

impl FromStr for Version {
    type Err = Error;
    /// Create a new [`Version`] from a string slice.
    ///
    /// Expects a composite version string such as `2:1.25.1-5`
    /// The components of the above composite version string are:
    ///
    /// - `2`: The optional epoch, delimited with a `:`
    /// - `1.25.1`: The version, which is an arbitrary ASCII string, excluding `[':', '/', '-']`
    /// - `5`: The optional release, delimited with a `-`.
    fn from_str(s: &str) -> Result<Version, Self::Err> {
        // Try to split off epoch from `{}{pkgver}-{pkgrel}`
        let (epoch, pkgver_pkgrel) = s.split_once(':').unzip();
        // If there's no epoch, use the whole version as `pkgver` with an
        // optional `pkgrel`.
        let pkgver_pkgrel = pkgver_pkgrel.unwrap_or(s);

        // Try to split the `{pkgver}-{pkgrel}`
        let (pkgver, pkgrel) = pkgver_pkgrel.split_once('-').unzip();

        // If there's no pkgrel, it's just a stand-alone `pkgver`.
        let pkgver = pkgver.unwrap_or(pkgver_pkgrel);

        Ok(Version {
            pkgver: pkgver.parse()?,
            epoch: if let Some(s) = epoch {
                Some(s.parse()?)
            } else {
                None
            },
            pkgrel: if let Some(s) = pkgrel {
                Some(s.parse()?)
            } else {
                None
            },
        })
    }
}

impl Display for Version {
    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
        if let Some(epoch) = self.epoch {
            write!(fmt, "{}:", epoch)?;
        }

        write!(fmt, "{}", self.pkgver)?;

        if let Some(pkgrel) = &self.pkgrel {
            write!(fmt, "-{}", pkgrel)?;
        }

        Ok(())
    }
}

impl Ord for Version {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self.epoch, other.epoch) {
            (Some(self_epoch), Some(other_epoch)) if self_epoch.cmp(&other_epoch).is_ne() => {
                return self_epoch.cmp(&other_epoch)
            }
            (Some(_), None) => return Ordering::Greater,
            (None, Some(_)) => return Ordering::Less,
            (_, _) => {}
        }

        let pkgver_cmp = self.pkgver.cmp(&other.pkgver);
        if pkgver_cmp.is_ne() {
            return pkgver_cmp;
        }

        self.pkgrel.cmp(&other.pkgrel)
    }
}

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

/// Specifies the comparison function for a [`VersionRequirement`].
///
/// The package version can be required to be:
/// - less than (`<`)
/// - less than or equal to (`<=`)
/// - equal to (`=`)
/// - greater than or equal to (`>=`)
/// - greater than (`>`)
///
/// the specified version.
///
/// ## Note
///
/// The variants of this enum are sorted in a way, that prefers the two-letter comparators over
/// the one-letter ones.
/// This is because when splitting a string on the string representation of [`VersionComparison`]
/// variant and relying on the ordering of [`strum::EnumIter`], the two-letter comparators must be
/// checked before checking the one-letter ones to yield robust results.
#[derive(
    strum::AsRefStr,
    Clone,
    Copy,
    Debug,
    strum::Display,
    strum::EnumIter,
    strum::EnumString,
    PartialEq,
    Eq,
    strum::VariantNames,
)]
pub enum VersionComparison {
    #[strum(to_string = "<=")]
    LessOrEqual,

    #[strum(to_string = ">=")]
    GreaterOrEqual,

    #[strum(to_string = "=")]
    Equal,

    #[strum(to_string = "<")]
    Less,

    #[strum(to_string = ">")]
    Greater,
}

impl VersionComparison {
    /// Returns `true` if the result of a comparison between the actual and required package
    /// versions satisfies the comparison function.
    fn is_compatible_with(self, ord: Ordering) -> bool {
        match (self, ord) {
            (VersionComparison::Less, Ordering::Less)
            | (VersionComparison::LessOrEqual, Ordering::Less | Ordering::Equal)
            | (VersionComparison::Equal, Ordering::Equal)
            | (VersionComparison::GreaterOrEqual, Ordering::Greater | Ordering::Equal)
            | (VersionComparison::Greater, Ordering::Greater) => true,

            (VersionComparison::Less, Ordering::Equal | Ordering::Greater)
            | (VersionComparison::LessOrEqual, Ordering::Greater)
            | (VersionComparison::Equal, Ordering::Less | Ordering::Greater)
            | (VersionComparison::GreaterOrEqual, Ordering::Less)
            | (VersionComparison::Greater, Ordering::Less | Ordering::Equal) => false,
        }
    }
}

/// A version requirement, e.g. for a dependency package.
///
/// It consists of a target version and a comparison function. A version requirement of `>=1.5` has
/// a target version of `1.5` and a comparison function of [`VersionComparison::GreaterOrEqual`].
///
/// ## Examples
///
/// ```
/// use std::str::FromStr;
///
/// use alpm_types::{Version, VersionComparison, VersionRequirement};
///
/// let requirement = VersionRequirement::from_str(">=1.5").unwrap();
///
/// assert_eq!(requirement.comparison, VersionComparison::GreaterOrEqual);
/// assert_eq!(requirement.version, Version::from_str("1.5").unwrap());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionRequirement {
    pub comparison: VersionComparison,
    pub version: Version,
}

impl VersionRequirement {
    /// Create a new `VersionRequirement`
    pub fn new(comparison: VersionComparison, version: Version) -> Self {
        VersionRequirement {
            comparison,
            version,
        }
    }

    /// Returns `true` if the requirement is satisfied by the given package version.
    ///
    /// ## Examples
    ///
    /// ```
    /// use std::str::FromStr;
    ///
    /// use alpm_types::{Version, VersionRequirement};
    ///
    /// let requirement = VersionRequirement::from_str(">=1.5-3").unwrap();
    ///
    /// assert!(!requirement.is_satisfied_by(&Version::from_str("1.5").unwrap()));
    /// assert!(requirement.is_satisfied_by(&Version::from_str("1.5-3").unwrap()));
    /// assert!(requirement.is_satisfied_by(&Version::from_str("1.6").unwrap()));
    /// assert!(requirement.is_satisfied_by(&Version::from_str("2:1.0").unwrap()));
    /// assert!(!requirement.is_satisfied_by(&Version::from_str("1.0").unwrap()));
    /// ```
    pub fn is_satisfied_by(&self, ver: &Version) -> bool {
        self.comparison.is_compatible_with(ver.cmp(&self.version))
    }
}

impl Display for VersionRequirement {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}{}", self.comparison, self.version)
    }
}

impl FromStr for VersionRequirement {
    type Err = Error;

    /// Parses a version requirement from a string.
    ///
    /// ## Errors
    ///
    /// Returns an error if the comparison function or version are malformed.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        fn is_comparison_char(c: char) -> bool {
            matches!(c, '<' | '=' | '>')
        }

        let comparison_end = s
            .find(|c| !is_comparison_char(c))
            .ok_or(Error::MissingComponent {
                component: "operator",
            })?;

        let (comparison, version) = s.split_at(comparison_end);

        let comparison = comparison.parse()?;
        let version = version.parse()?;

        Ok(VersionRequirement {
            comparison,
            version,
        })
    }
}

#[cfg(test)]
mod tests {
    use std::num::IntErrorKind;

    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case("1.0.0", Ok(SchemaVersion(SemverVersion::new(1, 0, 0))))]
    #[case("1", Ok(SchemaVersion(SemverVersion::new(1, 0, 0))))]
    #[case("-1.0.0", Err(Error::InvalidSemver { kind: String::from("unexpected character '-' while parsing major version number") }))]
    fn schema_version(#[case] version: &str, #[case] result: Result<SchemaVersion, Error>) {
        assert_eq!(result, SchemaVersion::from_str(version))
    }

    /// Ensure that valid buildtool version strings are parsed as expected.
    #[rstest]
    #[case(
        "1.0.0-1-any",
        BuildToolVersion::new(Version::from_str("1.0.0-1").unwrap(), Some(Architecture::from_str("any").unwrap())),
    )]
    #[case(
        "1:1.0.0-1-any",
        BuildToolVersion::new(Version::from_str("1:1.0.0-1").unwrap(), Some(Architecture::from_str("any").unwrap())),
    )]
    #[case(
        "1.0.0",
        BuildToolVersion::new(Version::from_str("1.0.0").unwrap(), None),
    )]
    fn valid_buildtoolver_new(#[case] buildtoolver: &str, #[case] expected: BuildToolVersion) {
        assert_eq!(
            BuildToolVersion::from_str(buildtoolver),
            Ok(expected),
            "Expected valid parse of buildtoolver '{buildtoolver}'"
        );
    }

    /// Ensure that invalid buildtool version strings produce the respective errors.
    #[rstest]
    #[case("1.0.0-any", Error::MissingComponent { component: "pkgrel" })]
    #[case(
        ".1.0.0-1-any",
        Error::RegexDoesNotMatch {
            value: ".1.0.0".to_string(),
            regex_type: "pkgver".to_string(),
            regex: PKGVER_REGEX.to_string()
        }
    )]
    #[case("1.0.0-1-foo", strum::ParseError::VariantNotFound.into())]
    fn invalid_buildtoolver_new(#[case] buildtoolver: &str, #[case] expected: Error) {
        assert_eq!(
            BuildToolVersion::from_str(buildtoolver),
            Err(expected),
            "Expected error during parse of buildtoolver '{buildtoolver}'"
        );
    }

    #[rstest]
    #[case(
        SchemaVersion(SemverVersion::new(1, 0, 0)),
        SchemaVersion(SemverVersion::new(0, 1, 0))
    )]
    fn compare_schema_version(#[case] version_a: SchemaVersion, #[case] version_b: SchemaVersion) {
        assert!(version_a > version_b);
    }

    /// Ensure that valid version strings are parsed as expected.
    #[rstest]
    #[case(
        "foo",
        Version {
            epoch: None,
            pkgver: Pkgver::new("foo".to_string()).unwrap(),
            pkgrel: None
        },
    )]
    #[case(
        "1:foo-1",
        Version {
            pkgver: Pkgver::new("foo".to_string()).unwrap(),
            epoch: Some(Epoch::from_str("1").unwrap()),
            pkgrel: Some(Pkgrel::new("1".to_string()).unwrap()),
        },
    )]
    #[case(
        "1:foo",
        Version {
            pkgver: Pkgver::new("foo".to_string()).unwrap(),
            epoch: Some(Epoch::from_str("1").unwrap()),
            pkgrel: None,
        },
    )]
    #[case(
        "foo-1",
        Version {
            pkgver: Pkgver::new("foo".to_string()).unwrap(),
            epoch: None,
            pkgrel: Some(Pkgrel::new("1".to_string()).unwrap())
        }
    )]
    fn valid_version_from_string(#[case] version: &str, #[case] expected: Version) {
        assert_eq!(
            Version::from_str(version),
            Ok(expected),
            "Expected valid parsing for version {version}"
        )
    }

    /// Ensure that invalid version strings produce the respective errors.
    #[rstest]
    #[case(
        "1:1:foo-1",
        Error::RegexDoesNotMatch {
            value: "1:foo".to_string(),
            regex_type: "pkgver".to_string(),
            regex: PKGVER_REGEX.to_string()
        }
    )]
    #[case(
        "1:foo-1-1",
        Error::RegexDoesNotMatch {
            value: "1-1".to_string(),
            regex_type: "pkgrel".to_string(),
            regex: PKGREL_REGEX.to_string()
        }
    )]
    #[case(
        "",
        Error::RegexDoesNotMatch {
            value: "".to_string(),
            regex_type: "pkgver".to_string(),
            regex: PKGVER_REGEX.to_string()
        }
    )]
    #[case(
        ":",
        Error::RegexDoesNotMatch {
            value: "".to_string(),
            regex_type: "pkgver".to_string(),
            regex: PKGVER_REGEX.to_string()
        }
    )]
    #[case(
        ".",
        Error::RegexDoesNotMatch {
            value: ".".to_string(),
            regex_type: "pkgver".to_string(),
            regex: PKGVER_REGEX.to_string()
        }
    )]
    fn invalid_regex_in_version_from_string(#[case] version: &str, #[case] expected: Error) {
        assert_eq!(
            Version::from_str(version),
            Err(expected),
            "Expected error while parsing {version}"
        )
    }

    #[rstest]
    #[case("-1foo:1", Error::InvalidInteger { kind: IntErrorKind::InvalidDigit })]
    #[case("1-foo:1", Error::InvalidInteger { kind: IntErrorKind::InvalidDigit })]
    fn invalid_integer_in_version_from_string(#[case] version: &str, #[case] expected: Error) {
        assert_eq!(
            Version::from_str(version),
            Err(expected),
            "Expected error while parsing {version}"
        )
    }

    /// Test that version parsing works/fails for the special case where a pkgrel is expected.
    /// This is done by calling the `with_pkgrel` function directly.
    #[rstest]
    #[case(
        "1.0.0-1",
        Ok(Version{
            pkgver: Pkgver::new("1.0.0".to_string()).unwrap(),
            pkgrel: Some(Pkgrel::new("1".to_string()).unwrap()),
            epoch: None,
        })
    )]
    #[case("1.0.0", Err(Error::MissingComponent { component: "pkgrel" }))]
    fn version_with_pkgrel(#[case] version: &str, #[case] result: Result<Version, Error>) {
        assert_eq!(result, Version::with_pkgrel(version));
    }

    #[rstest]
    #[case("1", Ok(Epoch(NonZeroUsize::new(1).unwrap())))]
    #[case("0", Err(Error::InvalidInteger { kind: IntErrorKind::Zero }))]
    #[case("-0", Err(Error::InvalidInteger { kind: IntErrorKind::InvalidDigit }))]
    #[case("z", Err(Error::InvalidInteger { kind: IntErrorKind::InvalidDigit }))]
    fn epoch(#[case] version: &str, #[case] result: Result<Epoch, Error>) {
        assert_eq!(result, Epoch::from_str(version));
    }

    /// Make sure that we can parse valid **pkgver** strings.
    #[rstest]
    #[case("foo")]
    #[case("1.0.0")]
    fn valid_pkgver(#[case] pkgver: &str) {
        let parsed = Pkgver::new(pkgver.to_string());
        assert!(parsed.is_ok(), "Expected pkgver {pkgver} to be valid.");
        assert_eq!(
            parsed.as_ref().unwrap().to_string(),
            pkgver,
            "Expected parsed Pkgver representation '{}' to be identical to input '{}'",
            parsed.unwrap(),
            pkgver
        );
    }

    /// Ensure that invalid **pkgver**s are throwing errors.
    #[rstest]
    #[case("1:foo")]
    #[case("foo-1")]
    #[case("foo,1")]
    #[case(".foo")]
    #[case("_foo")]
    // ß is not in [:alnum:]
    #[case("ß")]
    #[case("1.ß")]
    fn invalid_pkgver(#[case] pkgver: &str) {
        assert_eq!(
            Pkgver::new(pkgver.to_string()).as_ref(),
            Err(&Error::RegexDoesNotMatch {
                value: pkgver.to_string(),
                regex_type: "pkgver".to_string(),
                regex: PKGVER_REGEX.to_string()
            }),
            "Expected pkgrel {pkgver} to be invalid."
        );
    }

    /// Make sure that we can parse valid **pkgrel** strings.
    #[rstest]
    #[case("1")]
    #[case("1.1")]
    fn valid_pkgrel(#[case] pkgrel: &str) {
        let parsed = Pkgrel::new(pkgrel.to_string());
        assert!(parsed.is_ok(), "Expected pkgrel {pkgrel} to be valid.");
        assert_eq!(
            parsed.as_ref().unwrap().to_string(),
            pkgrel,
            "Expected parsed Pkgrel representation '{}' to be identical to input '{}'",
            parsed.unwrap(),
            pkgrel
        );
    }

    /// Ensure that invalid **pkgrel**s are throwing errors.
    #[rstest]
    #[case("0.1")]
    #[case("0")]
    fn invalid_pkgrel(#[case] pkgrel: &str) {
        assert_eq!(
            Pkgrel::new(pkgrel.to_string()),
            Err(Error::RegexDoesNotMatch {
                value: pkgrel.to_string(),
                regex_type: "pkgrel".to_string(),
                regex: PKGREL_REGEX.to_string()
            }),
            "Expected pkgrel {pkgrel} to be invalid."
        );
    }

    /// Test that pkgrel ordering works as intended
    #[rstest]
    #[case("1", "2")]
    #[case("1", "1.1")]
    #[case("1", "11")]
    fn pkgrel_cmp(#[case] lesser: &str, #[case] bigger: &str) {
        let lesser = Pkgrel::new(lesser.to_string()).unwrap();
        let bigger = Pkgrel::new(bigger.to_string()).unwrap();
        assert!(lesser.lt(&bigger));
    }

    /// Ensure that versions are properly serialized back to their string representation.
    #[rstest]
    #[case(Version::from_str("1:1-1").unwrap(), "1:1-1")]
    #[case(Version::from_str("1-1").unwrap(), "1-1")]
    #[case(Version::from_str("1").unwrap(), "1")]
    #[case(Version::from_str("1:1").unwrap(), "1:1")]
    fn version_to_string(#[case] version: Version, #[case] to_str: &str) {
        assert_eq!(format!("{}", version), to_str);
    }

    #[rstest]
    #[case(Version::from_str("1"), Version::from_str("1"), Ordering::Equal)]
    #[case(Version::from_str("2"), Version::from_str("1"), Ordering::Greater)]
    #[case(Version::from_str("1"), Version::from_str("2"), Ordering::Less)]
    #[case(Version::from_str("1"), Version::from_str("1.1"), Ordering::Less)]
    #[case(Version::from_str("1.1"), Version::from_str("1"), Ordering::Greater)]
    #[case(Version::from_str("1.1"), Version::from_str("1.1"), Ordering::Equal)]
    #[case(Version::from_str("1.2"), Version::from_str("1.1"), Ordering::Greater)]
    #[case(Version::from_str("1.1"), Version::from_str("1.2"), Ordering::Less)]
    #[case(Version::from_str("1+2"), Version::from_str("1+1"), Ordering::Greater)]
    #[case(Version::from_str("1+1"), Version::from_str("1+2"), Ordering::Less)]
    #[case(Version::from_str("1.1"), Version::from_str("1.1a"), Ordering::Greater)]
    #[case(Version::from_str("1.1a"), Version::from_str("1.1"), Ordering::Less)]
    #[case(
        Version::from_str("1.1"),
        Version::from_str("1.1a1"),
        Ordering::Greater
    )]
    #[case(Version::from_str("1.1a1"), Version::from_str("1.1"), Ordering::Less)]
    #[case(Version::from_str("1.1"), Version::from_str("1.11a"), Ordering::Less)]
    #[case(
        Version::from_str("1.11a"),
        Version::from_str("1.1"),
        Ordering::Greater
    )]
    #[case(
        Version::from_str("1.1_a"),
        Version::from_str("1.1"),
        Ordering::Greater
    )]
    #[case(Version::from_str("1.1"), Version::from_str("1.1_a"), Ordering::Less)]
    #[case(Version::from_str("1.1"), Version::from_str("1.1.a"), Ordering::Less)]
    #[case(
        Version::from_str("1.1.a"),
        Version::from_str("1.1"),
        Ordering::Greater
    )]
    #[case(Version::from_str("1.a"), Version::from_str("1.1"), Ordering::Less)]
    #[case(Version::from_str("1.1"), Version::from_str("1.a"), Ordering::Greater)]
    #[case(Version::from_str("1.a1"), Version::from_str("1.1"), Ordering::Less)]
    #[case(Version::from_str("1.1"), Version::from_str("1.a1"), Ordering::Greater)]
    #[case(Version::from_str("1.a11"), Version::from_str("1.1"), Ordering::Less)]
    #[case(
        Version::from_str("1.1"),
        Version::from_str("1.a11"),
        Ordering::Greater
    )]
    #[case(Version::from_str("a.1"), Version::from_str("1.1"), Ordering::Less)]
    #[case(Version::from_str("1.1"), Version::from_str("a.1"), Ordering::Greater)]
    #[case(Version::from_str("foo"), Version::from_str("1.1"), Ordering::Less)]
    #[case(Version::from_str("1.1"), Version::from_str("foo"), Ordering::Greater)]
    #[case(Version::from_str("a1a"), Version::from_str("a1b"), Ordering::Less)]
    #[case(Version::from_str("a1b"), Version::from_str("a1a"), Ordering::Greater)]
    #[case(
        Version::from_str("20220102"),
        Version::from_str("20220202"),
        Ordering::Less
    )]
    #[case(
        Version::from_str("20220202"),
        Version::from_str("20220102"),
        Ordering::Greater
    )]
    #[case(Version::from_str("1.0.."), Version::from_str("1.0."), Ordering::Equal)]
    #[case(Version::from_str("1.0."), Version::from_str("1.0"), Ordering::Greater)]
    #[case(Version::from_str("1..0"), Version::from_str("1.0"), Ordering::Greater)]
    #[case(Version::from_str("1..0"), Version::from_str("1..0"), Ordering::Equal)]
    #[case(
        Version::from_str("1..1"),
        Version::from_str("1..0"),
        Ordering::Greater
    )]
    #[case(Version::from_str("1..0"), Version::from_str("1..1"), Ordering::Less)]
    #[case(Version::from_str("1+0"), Version::from_str("1.0"), Ordering::Equal)]
    #[case(
        Version::from_str("1.111"),
        Version::from_str("1.1a1"),
        Ordering::Greater
    )]
    #[case(Version::from_str("1.1a1"), Version::from_str("1.111"), Ordering::Less)]
    #[case(Version::from_str("01"), Version::from_str("1"), Ordering::Equal)]
    #[case(Version::from_str("001a"), Version::from_str("1a"), Ordering::Equal)]
    #[case(
        Version::from_str("1.a001a.1"),
        Version::from_str("1.a1a.1"),
        Ordering::Equal
    )]
    fn version_cmp(
        #[case] version_a: Result<Version, Error>,
        #[case] version_b: Result<Version, Error>,
        #[case] expected: Ordering,
    ) {
        // Simply unwrap the Version as we expect all test strings to be valid.
        let version_a = version_a.unwrap();
        let version_b = version_b.unwrap();

        // Derive the expected vercmp binary exitcode from the expected Ordering.
        let vercmp_result = match &expected {
            Ordering::Equal => 0,
            Ordering::Greater => 1,
            Ordering::Less => -1,
        };

        let ordering = version_a.cmp(&version_b);
        assert_eq!(
            ordering, expected,
            "Failed to compare '{version_a}' and '{version_b}'. Expected {expected:?} got {ordering:?}"
        );

        assert_eq!(Version::vercmp(&version_a, &version_b), vercmp_result);
    }

    /// Ensure that valid version comparison strings can be parsed.
    #[rstest]
    #[case("<", VersionComparison::Less)]
    #[case("<=", VersionComparison::LessOrEqual)]
    #[case("=", VersionComparison::Equal)]
    #[case(">=", VersionComparison::GreaterOrEqual)]
    #[case(">", VersionComparison::Greater)]
    fn valid_version_comparison(#[case] comparison: &str, #[case] expected: VersionComparison) {
        assert_eq!(comparison.parse(), Ok(expected));
    }

    /// Ensure that invalid version comparisons will throw an error.
    #[rstest]
    #[case("")]
    #[case("<<")]
    #[case("==")]
    #[case("!=")]
    #[case(" =")]
    #[case("= ")]
    #[case("<1")]
    fn invalid_version_comparison(#[case] comparison: &str) {
        assert_eq!(
            comparison.parse::<VersionComparison>(),
            Err(strum::ParseError::VariantNotFound)
        );
    }

    /// Test successful parsing for version requirement strings.
    #[rstest]
    #[case("=1", VersionRequirement {
        comparison: VersionComparison::Equal,
        version: Version::from_str("1").unwrap(),
    })]
    #[case("<=42:abcd-2.4", VersionRequirement {
        comparison: VersionComparison::LessOrEqual,
        version: Version::from_str("42:abcd-2.4").unwrap(),
    })]
    #[case(">3.1", VersionRequirement {
        comparison: VersionComparison::Greater,
        version: Version::from_str("3.1").unwrap(),
    })]
    fn valid_version_requirement(#[case] requirement: &str, #[case] expected: VersionRequirement) {
        assert_eq!(
            requirement.parse(),
            Ok(expected),
            "Expected successful parse for version requirement '{requirement}'"
        );
    }

    /// Test expected parsing errors for version requirement strings.
    #[rstest]
    #[case("<=", Error::MissingComponent { component: "operator" })]
    #[case("<>3.1", strum::ParseError::VariantNotFound.into())]
    #[case("3.1", strum::ParseError::VariantNotFound.into())]
    #[case("=>3.1", strum::ParseError::VariantNotFound.into())]
    #[case(
        "<3.1>3.2",
        Error::RegexDoesNotMatch {
            value: "3.1>3.2".to_string(),
            regex_type: "pkgver".to_string(),
            regex: PKGVER_REGEX.to_string()
        }
    )]
    fn invalid_version_requirement(#[case] requirement: &str, #[case] expected: Error) {
        assert_eq!(
            requirement.parse::<VersionRequirement>(),
            Err(expected),
            "Expected error while parsing version requirement '{requirement}'"
        );
    }

    /// Check whether a version requirement (>= 1.0) is fulfilled by a given version string.
    #[rstest]
    #[case("=1", "1", true)]
    #[case("=1", "1.0", false)]
    #[case("=1", "1-1", false)]
    #[case("=1", "1:1", false)]
    #[case("=1", "0.9", false)]
    #[case("<42", "41", true)]
    #[case("<42", "42", false)]
    #[case("<42", "43", false)]
    #[case("<=42", "41", true)]
    #[case("<=42", "42", true)]
    #[case("<=42", "43", false)]
    #[case(">42", "41", false)]
    #[case(">42", "42", false)]
    #[case(">42", "43", true)]
    #[case(">=42", "41", false)]
    #[case(">=42", "42", true)]
    #[case(">=42", "43", true)]
    fn version_requirement_satisfied(
        #[case] requirement: &str,
        #[case] version: &str,
        #[case] result: bool,
    ) {
        let requirement = VersionRequirement::from_str(requirement).unwrap();
        let version = Version::from_str(version).unwrap();
        assert_eq!(requirement.is_satisfied_by(&version), result);
    }

    #[rstest]
    #[case("1.0.0", vec![("1", 0), ("0", 1), ("0", 1)])]
    #[case("1..0", vec![("1", 0), ("0", 2)])]
    #[case("1.0.", vec![("1", 0), ("0", 1), ("", 1)])]
    #[case("1..", vec![("1", 0), ("", 2)])]
    #[case("1.🗻lol.0", vec![("1", 0), ("lol", 2), ("0", 1)])]
    #[case("1.🗻lol.", vec![("1", 0), ("lol", 2), ("", 1)])]
    #[case("20220202", vec![("20220202", 0)])]
    #[case("some_string", vec![("some", 0), ("string", 1)])]
    #[case("alpha7654numeric321", vec![("alpha", 0), ("7654", 0), ("numeric", 0), ("321", 0)])]
    fn version_segment_iterator(
        #[case] version: &str,
        #[case] expected_segments: Vec<(&'static str, usize)>,
    ) {
        let version = Pkgver(version.to_string());
        // Convert the simplified definition above into actual VersionSegment instances.
        let expected = expected_segments
            .into_iter()
            .map(|(segment, delimiters)| VersionSegment::new(segment, delimiters))
            .collect::<Vec<VersionSegment>>();

        let mut segments_iter = version.segments();
        let mut expected_iter = expected.clone().into_iter();

        // Iterate over both iterators.
        // We do it manually to ensure that they both end at the same time.
        loop {
            let next_segment = segments_iter.next();
            assert_eq!(
                next_segment,
                expected_iter.next(),
                "Failed for segment {next_segment:?} in version string {version}:\nsegments: {:?}\n expected: {:?}",
                version.segments().collect::<Vec<VersionSegment>>(),
                expected,
            );
            if next_segment.is_none() {
                break;
            }
        }
    }
}