rpm-version 0.5.0

A library for dealing with RPM versions (NEVRA, EVR) correctly. Sort algorithm is identical to RPM.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};

#[cfg(feature = "python")]
pub mod python;

mod sortkey;
pub use sortkey::*;

/// A full RPM "NEVRA" consists of 5 different components - Name, Epoch, Version, Release, and Architecture.
///
/// Name is the name of the package.
///
/// Epoch overrides all other fields and is generally only used as a last resort - in cases where
/// a change to the versioning scheme or packaging error creates a situation where newer packages
/// might otherwise sort as being older.
///
/// Version is the normal version string used by the upstream project. This shouldn't be tweaked
/// by the packager.
///
/// Release indicates firstly the number of times this package has been released - for instance,
/// with custom patches and backports not present in the upstream, but may also indicate other
/// details such as the OS it was built for (fc38, el9) or portions of a git commit hash.
///
/// Architecture indicates the CPU architecture that this package is intended to support.
///
/// In many contexts (on a system, in a repository), package NEVRAs are meant to be unique. You can have
/// different packages with the same NEVRA - but you can't install both, or put them both in a repo.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Nevra<'a> {
    name: Cow<'a, str>,
    evr: Evr<'a>,
    arch: Cow<'a, str>,
}

impl<'a> Nevra<'a> {
    /// Create a new NEVRA
    pub fn new<T: Into<Cow<'a, str>>>(
        name: T,
        epoch: T,
        version: T,
        release: T,
        arch: T,
    ) -> Nevra<'a> {
        Self {
            name: name.into(),
            evr: Evr::new(epoch, version, release),
            arch: arch.into(),
        }
    }

    /// Create a NEVRA parsed from a string
    pub fn parse(nevra: &'a str) -> Self {
        let (n, e, v, r, a) = Nevra::parse_values(nevra);
        Self::new(n, e, v, r, a)
    }

    /// The name value
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The EVR
    pub fn evr(&'a self) -> &'a Evr<'a> {
        &self.evr
    }

    /// The epoch value
    pub fn epoch(&self) -> &str {
        &self.evr.epoch
    }

    /// The version value
    pub fn version(&self) -> &str {
        &self.evr.version
    }

    /// The release value
    pub fn release(&self) -> &str {
        &self.evr.release
    }

    /// The arch value
    pub fn arch(&self) -> &str {
        &self.arch
    }

    /// Return the epoch, version and release values as a 5-element tuple
    pub fn values(&self) -> (&str, &str, &str, &str, &str) {
        (
            &self.name,
            &self.evr.epoch,
            &self.evr.version,
            &self.evr.release,
            &self.arch,
        )
    }

    /// Parse the name, epoch, version, release and arch values and return them as a 5-element tuple
    pub fn parse_values(nevra: &'a str) -> (&'a str, &'a str, &'a str, &'a str, &'a str) {
        // 1. Split Architecture from the right.
        // Example: "foo-1:2.3-4.x86_64" -> ("foo-1:2.3-4", "x86_64")
        let (nevr, arch) = nevra.rsplit_once('.').unwrap_or((nevra, ""));

        // 2. Split Release from the right of the remainder.
        // Example: "foo-1:2.3-4" -> ("foo-1:2.3", "4")
        let (nev, release) = nevr.rsplit_once('-').unwrap_or((nevr, ""));

        // 3. Split Version (with potential Epoch) from the right of the remainder.
        // Example: "foo-1:2.3" -> ("foo", "1:2.3")
        let (name, version_epoch) = nev.rsplit_once('-').unwrap_or((nev, ""));

        // 4. Check the version part for an Epoch.
        // The epoch is separated by a colon. If no colon exists, the epoch is empty.
        let (epoch, version) = match version_epoch.split_once(':') {
            // Example: "1:2.3" -> ("1", "2.3")
            Some((e, v)) => (e, v),
            // Example: "2.3" -> ("", "2.3")
            None => ("", version_epoch),
        };

        (name, epoch, version, release, arch)
    }

    /// Returns the name-epoch-version-release.arch string (NEVRA), e.g. `"foo-1:2.0-3.x86_64"`.
    ///
    /// A package having no epoch value is equivalent to having an epoch of zero, hence,
    /// when the epoch is not present it prints an epoch of 0 - e.g. `"0:1.2.3-4"`
    ///
    /// This is a normalized form, if you want the more display-friendly form, use [`nevra_short()`]
    pub fn nevra(&self) -> String {
        format!("{}-{}.{}", self.name, self.evr.evr(), self.arch)
    }

    /// Returns the name-epoch-version-release.arch string (NEVRA), e.g. `"foo-1:2.0-3.x86_64"`.
    ///
    /// Unlike [`nevra()`], this doesn't print the epoch if it is 0 or non-existing, e.g.
    /// `"foo-2.0-3.x86_64"`, but does print it otherwise.
    ///
    /// Same as [`to_string()`]
    pub fn nevra_short(&self) -> String {
        self.to_string()
    }

    /// Returns the name-version-release.arch string (NVRA)
    ///
    /// This is the form typically used for RPM filenames. It is similar to NEVRA,
    /// but does not include epoch (even when it is present)
    /// e.g. `"foo-2.0-3.x86_64"`.
    pub fn nvra(&self) -> String {
        format!(
            "{}-{}-{}.{}",
            self.name, self.evr.version, self.evr.release, self.arch
        )
    }
}

impl Hash for Nevra<'_> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.evr.hash(state);
        self.arch.hash(state);
    }
}

impl fmt::Display for Nevra<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{}.{}", self.name, self.evr, self.arch)
    }
}

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

impl Ord for Nevra<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        let name_cmp = compare_version_string(&self.name, &other.name);
        if name_cmp != Ordering::Equal {
            return name_cmp;
        }

        let evr_cmp = self.evr.cmp(&other.evr);
        if evr_cmp != Ordering::Equal {
            return evr_cmp;
        }

        compare_version_string(&self.arch, &other.arch)
    }
}

/// A full RPM "version" specifier has 3 different components - Epoch, Version, and Release.
///
/// You are not expected to create these manually, but rather from existing RPMs.
///
/// Epoch overrides all other fields and is generally only used as a last resort - in cases where
/// a change to the versioning scheme or packaging error creates a situation where newer packages
/// might otherwise sort as being older.
///
/// Version is the normal version string used by the upstream project. This shouldn't be tweaked
/// by the packager.
///
/// Release indicates firstly the number of times this package has been released - for instance,
/// with custom patches and backports not present in the upstream, but may also indicate other
/// details such as the OS it was built for (fc38, el9) or portions of a git commit hash.
///
/// Tilde (~) and caret (^) are special values used in particular situations. Including ~ in
/// a version is used for denoting pre-releases and will force it to sort as less than a version
/// without a caret, e.g. 0.5.0 vs 0.5.0~rc1. Including ^ in a version is used for denoting snapshots
/// not directly associated with an upstream release and will force it to sort higher, e.g.
/// 0.5.0 vs 0.5.0^deadbeef
#[derive(Clone, Debug, Default, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Evr<'a> {
    epoch: Cow<'a, str>,
    version: Cow<'a, str>,
    release: Cow<'a, str>,
}

impl<'a> Evr<'a> {
    /// Create a new EVR
    pub fn new<T: Into<Cow<'a, str>>>(epoch: T, version: T, release: T) -> Evr<'a> {
        Evr {
            epoch: epoch.into(),
            version: version.into(),
            release: release.into(),
        }
    }

    /// Create an EVR parsed from a string
    pub fn parse(evr: &'a str) -> Self {
        Evr::parse_values(evr).into()
    }

    /// The epoch value
    pub fn epoch(&self) -> &str {
        &self.epoch
    }

    /// The version value
    pub fn version(&self) -> &str {
        &self.version
    }

    /// The release value
    pub fn release(&self) -> &str {
        &self.release
    }

    /// Set the epoch value
    pub fn set_epoch(&mut self, epoch: impl Into<Cow<'a, str>>) {
        self.epoch = epoch.into();
    }

    /// Set the version value
    pub fn set_version(&mut self, version: impl Into<Cow<'a, str>>) {
        self.version = version.into();
    }

    /// Set the release value
    pub fn set_release(&mut self, release: impl Into<Cow<'a, str>>) {
        self.release = release.into();
    }

    /// Return an epoch:version-release (EVR) string in a normalized form which always
    /// includes an epoch.
    ///
    /// A null epoch is equivalent to 0, hence, this uses an epoch of 0
    /// when the epoch is not present. e.g. `"0:1.2.3-4"`
    pub fn evr(&self) -> String {
        let epoch = if self.epoch.is_empty() {
            "0"
        } else {
            self.epoch.as_ref()
        };

        format!("{}:{}-{}", epoch, self.version(), self.release())
    }

    /// Return an epoch:version-release (EVR) string in short form.
    ///
    /// Does does not print the epoch when it is not present, e.g. `"1.2.3-4"`.
    ///
    /// Same as [`to_string()`]
    pub fn evr_short(&self) -> String {
        self.to_string()
    }

    /// Return the epoch, version and release values as a 3-element tuple
    pub fn values(&self) -> (&str, &str, &str) {
        (self.epoch(), self.version(), self.release())
    }

    /// Parse the epoch, version and release values and return them as a 3-element tuple
    pub fn parse_values(evr: &'a str) -> (&'a str, &'a str, &'a str) {
        let (epoch, vr) = evr.split_once(':').unwrap_or(("", evr));
        let (version, release) = vr.split_once('-').unwrap_or((vr, ""));

        (epoch, version, release)
    }

    /// Encode this EVR as a memcmp-sortable binary key.
    pub fn sortkey(&self) -> EvrSortKey {
        EvrSortKey::from_values(&self.epoch, &self.version, &self.release)
    }
}

impl<'a> From<(&'a str, &'a str, &'a str)> for Evr<'a> {
    fn from(val: (&'a str, &'a str, &'a str)) -> Self {
        Evr::new(val.0, val.1, val.2)
    }
}

impl PartialEq for Evr<'_> {
    #[allow(clippy::comparison_to_empty)]
    fn eq(&self, other: &Self) -> bool {
        ((self.epoch == other.epoch)
            || (self.epoch == "" && other.epoch == "0")
            || (self.epoch == "0" && other.epoch == ""))
            && self.version == other.version
            && self.release == other.release
    }
}

impl Hash for Evr<'_> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let epoch = if self.epoch.is_empty() {
            "0"
        } else {
            &self.epoch
        };
        epoch.hash(state);
        self.version.hash(state);
        self.release.hash(state);
    }
}

impl fmt::Display for Evr<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if !self.epoch.is_empty() {
            write!(f, "{}:", self.epoch)?;
        }

        write!(f, "{}-{}", self.version, self.release)
    }
}

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

impl Ord for Evr<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        let epoch_1 = if self.epoch.is_empty() {
            "0"
        } else {
            &self.epoch
        };
        let epoch_2 = if other.epoch.is_empty() {
            "0"
        } else {
            &other.epoch
        };

        let epoch_cmp = compare_version_string(epoch_1, epoch_2);
        if epoch_cmp != Ordering::Equal {
            return epoch_cmp;
        }

        let version_cmp = compare_version_string(&self.version, &other.version);
        if version_cmp != Ordering::Equal {
            return version_cmp;
        }

        compare_version_string(&self.release, &other.release)
    }
}

/// internal use: each individual component of the EVR is compared using this function
fn compare_version_string(version1: &str, version2: &str) -> Ordering {
    if version1 == version2 {
        return Ordering::Equal;
    }

    let mut version1_part = version1;
    let mut version2_part = version2;

    let not_alphanumeric_tilde_or_caret =
        |c: char| !c.is_ascii_alphanumeric() && c != '~' && c != '^';

    loop {
        // Strip any leading non-alphanumeric, non-tilde, non-caret characters
        version1_part = version1_part.trim_start_matches(not_alphanumeric_tilde_or_caret);
        version2_part = version2_part.trim_start_matches(not_alphanumeric_tilde_or_caret);

        // Tilde separator parses as "older" or lesser version
        match (
            version1_part.strip_prefix('~'),
            version2_part.strip_prefix('~'),
        ) {
            (Some(_), None) => return Ordering::Less,
            (None, Some(_)) => return Ordering::Greater,
            (Some(a), Some(b)) => {
                version1_part = a;
                version2_part = b;
                continue;
            }
            _ => (),
        }

        // if two strings are equal but one is longer, the longer one is considered greater
        // ...unless it ends on a caret, which parses as a lesser version (tilde doesn't have this caveat)
        match (
            version1_part.strip_prefix('^'),
            version2_part.strip_prefix('^'),
        ) {
            (Some(_), None) => match version2_part.is_empty() {
                true => return Ordering::Greater,
                false => return Ordering::Less,
            },
            (None, Some(_)) => match version1_part.is_empty() {
                true => return Ordering::Less,
                false => return Ordering::Greater,
            },
            (Some(a), Some(b)) => {
                version1_part = a;
                version2_part = b;
                continue;
            }
            _ => (),
        }

        if version1_part.is_empty() || version2_part.is_empty() {
            break;
        }

        /// Match a contiguous string of characters matching the provided pattern
        /// and return it, along with the rest of the string, if one was found.
        fn matching_contiguous<F>(string: &str, pat: F) -> Option<(&str, &str)>
        where
            F: Fn(char) -> bool,
        {
            let end = string.find(|c| !pat(c)).unwrap_or(string.len());
            if end == 0 {
                None
            } else {
                Some(string.split_at(end))
            }
        }

        if version1_part.starts_with(|c: char| c.is_ascii_digit()) {
            match (
                matching_contiguous(version1_part, |c| c.is_ascii_digit()),
                matching_contiguous(version2_part, |c| c.is_ascii_digit()),
            ) {
                (Some((prefix1, rest1)), Some((prefix2, rest2))) => {
                    version1_part = rest1;
                    version2_part = rest2;

                    let prefix1 = prefix1.trim_start_matches('0');
                    let prefix2 = prefix2.trim_start_matches('0');

                    let ordering = prefix1.len().cmp(&prefix2.len());
                    if ordering != Ordering::Equal {
                        return ordering;
                    }
                    let ordering = prefix1.cmp(prefix2);
                    if ordering != Ordering::Equal {
                        return ordering;
                    }
                }
                (Some(_), None) => return Ordering::Greater,
                _ => unreachable!(),
            }
        } else {
            match (
                matching_contiguous(version1_part, |c| c.is_ascii_alphabetic()),
                matching_contiguous(version2_part, |c| c.is_ascii_alphabetic()),
            ) {
                (Some((prefix1, rest1)), Some((prefix2, rest2))) => {
                    version1_part = rest1;
                    version2_part = rest2;

                    let ordering = prefix1.cmp(prefix2);
                    if ordering != Ordering::Equal {
                        return ordering;
                    }
                }
                (Some(_), None) => return Ordering::Less,
                _ => unreachable!(),
            }
        }
    }

    version1_part.len().cmp(&version2_part.len())
}

/// Compare two strings as RPM EVR values
pub fn rpm_evr_compare(evr1: &str, evr2: &str) -> Ordering {
    let evr1 = Evr::parse(evr1);
    let evr2 = Evr::parse(evr2);
    evr1.cmp(&evr2)
}

/// The comparison operator in an RPM dependency requirement.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ReqOperator {
    LT,
    LE,
    EQ,
    GE,
    GT,
}

impl fmt::Display for ReqOperator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            ReqOperator::LT => "<",
            ReqOperator::LE => "<=",
            ReqOperator::EQ => "=",
            ReqOperator::GE => ">=",
            ReqOperator::GT => ">",
        })
    }
}

/// An RPM dependency requirement: a package name with an optional version constraint.
///
/// A requirement like `foo >= 1:2.0-1` means "package foo with EVR at least 1:2.0-1".
/// A requirement with no operator/EVR (just a name) is satisfied by any version.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Requirement<'a> {
    name: Cow<'a, str>,
    constraint: Option<(ReqOperator, Evr<'a>)>,
}

impl<'a> Requirement<'a> {
    /// Create a requirement with no version constraint (any version satisfies).
    pub fn new<T: Into<Cow<'a, str>>>(name: T) -> Self {
        Self {
            name: name.into(),
            constraint: None,
        }
    }

    /// Create a requirement with a version constraint.
    pub fn with_constraint<T: Into<Cow<'a, str>>>(name: T, op: ReqOperator, evr: Evr<'a>) -> Self {
        Self {
            name: name.into(),
            constraint: Some((op, evr)),
        }
    }

    /// The required package name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The version constraint, if any.
    pub fn constraint(&self) -> Option<(ReqOperator, &Evr<'a>)> {
        self.constraint.as_ref().map(|(op, evr)| (*op, evr))
    }

    /// Check whether a given package name and EVR satisfy this requirement.
    pub fn satisfies(&self, name: &str, evr: &Evr) -> bool {
        if self.name != name {
            return false;
        }
        match &self.constraint {
            None => true,
            Some((op, req_evr)) => {
                let ord = evr.cmp(req_evr);
                match op {
                    ReqOperator::LT => ord == Ordering::Less,
                    ReqOperator::LE => ord != Ordering::Greater,
                    ReqOperator::EQ => ord == Ordering::Equal,
                    ReqOperator::GE => ord != Ordering::Less,
                    ReqOperator::GT => ord == Ordering::Greater,
                }
            }
        }
    }
}

impl fmt::Display for Requirement<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.constraint {
            None => write!(f, "{}", self.name),
            Some((op, evr)) => write!(f, "{} {} {}", self.name, op, evr),
        }
    }
}

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

    /// Helper: assert that both compare_version_string and version_sortkey
    /// produce the expected ordering (cross-validates both implementations)
    fn assert_ver_order(a: &str, b: &str, expected: Ordering) {
        assert_eq!(
            compare_version_string(a, b),
            expected,
            "compare_version_string({a:?}, {b:?})"
        );
        assert_eq!(
            version_sortkey(a).cmp(&version_sortkey(b)),
            expected,
            "version_sortkey({a:?}) vs version_sortkey({b:?})"
        );
    }

    /// Helper: assert that both Evr::cmp and Evr::sortkey produce the expected
    /// ordering (cross-validates both implementations)
    fn assert_evr_order(a: Evr, b: Evr, expected: Ordering) {
        assert_eq!(a.cmp(&b), expected, "Evr::cmp({a:?}, {b:?})");
        assert_eq!(
            a.sortkey().cmp(&b.sortkey()),
            expected,
            "Evr::sortkey({a:?}) vs Evr::sortkey({b:?})"
        );
    }

    /// Test that NEVRAs are printed as expected
    #[test]
    fn test_nevra_tostr() {
        let nevra = Nevra::new("foo", "", "1.2.3", "45", "x86_64");
        assert_eq!("foo-1.2.3-45.x86_64", nevra.to_string());
        assert_eq!("foo-1.2.3-45.x86_64", nevra.nevra_short());
        assert_eq!("foo-0:1.2.3-45.x86_64", nevra.nevra());

        let nevra = Nevra::new("foo", "0", "1.2.3", "45", "x86_64");
        assert_eq!("foo-0:1.2.3-45.x86_64", nevra.to_string());
        assert_eq!("foo-0:1.2.3-45.x86_64", nevra.nevra());

        let nevra = Nevra::new("foo", "1", "2.3.4", "5", "x86_64");
        assert_eq!("foo-1:2.3.4-5.x86_64", nevra.to_string());
        assert_eq!("foo-1:2.3.4-5.x86_64", nevra.nevra());

        let nevra = Nevra::new("python3.9", "0", "3.9.11", "2.fc38", "x86_64");
        assert_eq!("python3.9-0:3.9.11-2.fc38.x86_64", nevra.to_string());
        assert_eq!("python3.9-0:3.9.11-2.fc38.x86_64", nevra.nevra());
    }

    /// Test that a correctly formed EVR string is parsed correctly
    #[test]
    fn test_nevra_parse() {
        let nevra = Nevra::new("foo", "", "1.2.3", "45", "x86_64");
        assert_eq!(Nevra::parse("foo-1.2.3-45.x86_64"), nevra);

        let nevra = Nevra::new("foo", "0", "1.2.3", "45", "x86_64");
        assert_eq!(Nevra::parse("foo-0:1.2.3-45.x86_64"), nevra);

        let nevra = Nevra::new("foo", "1", "2.3.4", "5", "x86_64");
        assert_eq!(Nevra::parse("foo-1:2.3.4-5.x86_64"), nevra);

        let nevra = Nevra::new("python3.9", "0", "3.9.11", "2", "x86_64");
        assert_eq!(Nevra::parse("python3.9-3.9.11-2.x86_64"), nevra);

        let nevra = Nevra::new("python3.9", "0", "3.9.11", "2.fc38", "x86_64");
        assert_eq!(Nevra::parse("python3.9-3.9.11-2.fc38.x86_64"), nevra);
    }

    /// Test that various not-well-formed NEVRA strings still get parsed in a sensible way
    #[test]
    fn test_nevra_parse_edge_cases() {
        assert_eq!(Nevra::parse_values("foo"), ("foo", "", "", "", ""));
        assert_eq!(
            Nevra::parse_values("foo-1.2-3.bar"),
            ("foo", "", "1.2", "3", "bar")
        );
        assert_eq!(
            Nevra::parse_values("foo-1.2-3.bar.x86_64"),
            ("foo", "", "1.2", "3.bar", "x86_64")
        );
        assert_eq!(
            Nevra::parse_values("python3.9-3.9.11-2.fc38.x86_64"),
            ("python3.9", "", "3.9.11", "2.fc38", "x86_64")
        );

        let nevra = Nevra::new("python3.9-devel", "0", "3.9.11", "2.fc38", "x86_64");
        assert_eq!(Nevra::parse("python3.9-devel-3.9.11-2.fc38.x86_64"), nevra);

        let nevra = Nevra::new("foo-bar", "", "1.2.3", "45", "x86_64");
        assert_eq!(Nevra::parse("foo-bar-1.2.3-45.x86_64"), nevra);

        let nevra = Nevra::new("foo-bar", "0", "1.2.3", "45", "x86_64");
        assert_eq!(Nevra::parse("foo-bar-0:1.2.3-45.x86_64"), nevra);

        let nevra = Nevra::new("foo-bar-0", "", "1.2.3", "45.el10", "x86_64");
        assert_eq!(Nevra::parse("foo-bar-0-1.2.3-45.el10.x86_64"), nevra);

        let nevra = Nevra::new("foo-bar-0", "0", "1.2.3", "45.el10", "x86_64");
        assert_eq!(Nevra::parse("foo-bar-0-0:1.2.3-45.el10.x86_64"), nevra);

        let nevra = Nevra::new("grub2-efi-x64", "1", "2.12", "28.fc42", "x86_64");
        assert_eq!(Nevra::parse("grub2-efi-x64-1:2.12-28.fc42.x86_64"), nevra);
    }

    /// Test comparing NEVRAs using comparison operators
    #[test]
    fn test_nevra_ord() {
        let nevra1 = Nevra::parse("foo-1.2.3-45.noarch");
        let nevra2 = Nevra::parse("foo-1.2.3-45.noarch");
        assert!(nevra1 == nevra2);

        let nevra1 = Nevra::parse("foo-1.2.3-45.noarch");
        let nevra2 = Nevra::parse("foo-0:1.2.3-45.noarch");
        assert!(nevra1 == nevra2);

        let nevra1 = Nevra::parse("bar-1.2.3-45.noarch");
        let nevra2 = Nevra::parse("foo-9:1.2.3-45.noarch");
        assert!(nevra1 < nevra2);

        let nevra1 = Nevra::parse("foo-1.2.3-45.noarch");
        let nevra2 = Nevra::parse("foobar-1.2.3-45.noarch");
        assert!(nevra1 < nevra2);

        let nevra1 = Nevra::parse("foo-2.3.4-5.noarch");
        let nevra2 = Nevra::parse("foobar-1.2.3-45.noarch");
        assert!(nevra1 < nevra2);

        let nevra1 = Nevra::parse("bar-1.2.3-45.noarch");
        let nevra2 = Nevra::parse("foo-1.2.3-45.noarch");
        assert!(nevra1 < nevra2);

        let nevra1 = Nevra::parse("foo-1.2.3-45.fc38.noarch");
        let nevra2 = Nevra::parse("foo-1.2.3-45.fc39.noarch");
        assert!(nevra1 < nevra2);

        let nevra1 = Nevra::parse("foo-1.2.3-45.fc39.i386");
        let nevra2 = Nevra::parse("foo-1.2.3-45.fc39.x86_64");
        assert!(nevra1 < nevra2);

        let nevra1 = Nevra::parse("python3.9-3.9.12-2.fc39.i386");
        let nevra2 = Nevra::parse("python3.11-3.11.7-2.fc39.x86_64");
        assert!(nevra1 < nevra2);

        let nevra1 = Nevra::parse("python3.11-3.11.7-2.fc39.x86_64");
        let nevra2 = Nevra::parse("python3.9-3.9.12-2.fc39.x86_64");
        assert!(nevra1 > nevra2);
    }

    /// Test that EVRs are printed as expected
    #[test]
    fn test_evr_tostr() {
        let evr = Evr::new("", "1.2.3", "45");
        assert_eq!("1.2.3-45", evr.to_string());
        assert_eq!("1.2.3-45", evr.evr_short());
        assert_eq!("0:1.2.3-45", evr.evr());

        let evr = Evr::new("0", "1.2.3", "45");
        assert_eq!("0:1.2.3-45", evr.to_string());
        assert_eq!("0:1.2.3-45", evr.evr());
    }

    /// Test that a correctly formed EVR string is parsed correctly
    #[test]
    fn test_evr_parse() {
        let evr = Evr::new("", "1.2.3", "45");
        assert_eq!(Evr::parse("1.2.3-45"), evr);

        let evr = Evr::new("0", "1.2.3", "45");
        assert_eq!(Evr::parse("0:1.2.3-45"), evr);

        let evr = Evr::new("1", "2.3.4", "5");
        assert_eq!(Evr::parse("1:2.3.4-5"), evr);
    }

    /// Test that various not-well-formed EVR strings still get parsed in a sensible way
    #[test]
    fn test_evr_parse_edge_cases() {
        assert_eq!(Evr::parse_values("-"), ("", "", ""));
        assert_eq!(Evr::parse_values("."), ("", ".", ""));
        assert_eq!(Evr::parse_values(":"), ("", "", ""));
        assert_eq!(Evr::parse_values(":-"), ("", "", ""));
        assert_eq!(Evr::parse_values(".-"), ("", ".", ""));
        assert_eq!(Evr::parse_values("0"), ("", "0", ""));
        assert_eq!(Evr::parse_values("0-"), ("", "0", ""));
        assert_eq!(Evr::parse_values(":0"), ("", "0", ""));
        assert_eq!(Evr::parse_values(":0-"), ("", "0", ""));
        assert_eq!(Evr::parse_values("0:"), ("0", "", ""));
        assert_eq!(Evr::parse_values("asdf:"), ("asdf", "", ""));
        assert_eq!(Evr::parse_values("~:"), ("~", "", ""));
    }

    /// Test direct comparison of rpm EVR strings using rpm_evr_compare
    #[test]
    fn test_rpm_evr_compare() {
        assert_eq!(Ordering::Equal, rpm_evr_compare("0:1.2.3-45", "1.2.3-45"));
        assert_eq!(Ordering::Less, rpm_evr_compare("1.2.3-45", "1:1.2.3-45"));
        assert_eq!(Ordering::Greater, rpm_evr_compare("1.2.3-46", "1.2.3-45"));
    }

    /// Test comparing EVRs using comparison operators
    #[test]
    fn test_evr_ord() {
        // same EVR
        assert_evr_order(
            Evr::parse("1.2.3-45"),
            Evr::parse("1.2.3-45"),
            Ordering::Equal,
        );
        assert_evr_order(
            Evr::parse("2:1.2.3-45"),
            Evr::parse("2:1.2.3-45"),
            Ordering::Equal,
        );
        // zero-epoch == default-epoch
        assert_evr_order(
            Evr::parse("1.2.3-45"),
            Evr::parse("0:1.2.3-45"),
            Ordering::Equal,
        );
        // higher epoch wins
        assert_evr_order(
            Evr::parse("1.2.3-45"),
            Evr::parse("1:1.2.3-45"),
            Ordering::Less,
        );
        // epoch dominates version
        assert_evr_order(
            Evr::parse("4.2.3-45"),
            Evr::parse("1:1.2.3-45"),
            Ordering::Less,
        );

        // version ordering
        assert_evr_order(
            Evr::parse("1.2.3-45"),
            Evr::parse("1.2.4-45"),
            Ordering::Less,
        );
        assert_evr_order(
            Evr::parse("1.23.3-45"),
            Evr::parse("1.2.3-45"),
            Ordering::Greater,
        );
        assert_evr_order(
            Evr::parse("12.2.3-45"),
            Evr::parse("1.2.3-45"),
            Ordering::Greater,
        );
        assert_evr_order(
            Evr::parse("1.2.3-45"),
            Evr::parse("1.12.3-45"),
            Ordering::Less,
        );

        // tilde sorts older
        assert_evr_order(
            Evr::parse("~1.2.3-45"),
            Evr::parse("1.2.3-45"),
            Ordering::Less,
        );
        assert_evr_order(
            Evr::parse("~12.2.3-45"),
            Evr::parse("1.2.3-45"),
            Ordering::Less,
        );
        assert_evr_order(
            Evr::parse("~12.2.3-45"),
            Evr::parse("~1.2.3-45"),
            Ordering::Greater,
        );
        // higher epoch dominates even with tilde in version
        assert_evr_order(
            Evr::parse("3:~1.2.3-45"),
            Evr::parse("0:1.2.3-45"),
            Ordering::Greater,
        );

        // release ordering
        assert_evr_order(
            Evr::parse("1.2.3-45"),
            Evr::parse("1.2.3-46"),
            Ordering::Less,
        );
        assert_evr_order(
            Evr::parse("1.2.3-45.fc39"),
            Evr::parse("1.2.3-46.fc38"),
            Ordering::Less,
        );
        assert_evr_order(
            Evr::parse("1.2.3-3"),
            Evr::parse("1.2.3-10"),
            Ordering::Less,
        );
        assert_evr_order(
            Evr::parse("1.2.3-3.fc40"),
            Evr::parse("1.2.3-10.fc39"),
            Ordering::Less,
        );
    }

    /// Test many different combinations of version string comparison behavior
    #[test]
    fn test_compare_version_string() {
        assert_ver_order("1.0", "1.0", Ordering::Equal);
        assert_ver_order("1.0", "2.0", Ordering::Less);
        assert_ver_order("2.0", "1.0", Ordering::Greater);

        assert_ver_order("2.0.1", "2.0.1", Ordering::Equal);
        assert_ver_order("2.0", "2.0.1", Ordering::Less);
        assert_ver_order("2.0.1", "2.0", Ordering::Greater);

        assert_ver_order("5.0.1", "5.0.1a", Ordering::Less);
        assert_ver_order("5.0.1a", "5.0.1", Ordering::Greater);

        assert_ver_order("5.0.a1", "5.0.a1", Ordering::Equal);
        assert_ver_order("5.0.1a", "5.0.1a", Ordering::Equal);
        assert_ver_order("5.0.a1", "5.0.a2", Ordering::Less);
        assert_ver_order("5.0.a2", "5.0.a1", Ordering::Greater);

        assert_ver_order("10abc", "10.1abc", Ordering::Less);
        assert_ver_order("10.1abc", "10abc", Ordering::Greater);

        assert_ver_order("8.0", "8.0.rc1", Ordering::Less);
        assert_ver_order("8.0.rc1", "8.0", Ordering::Greater);

        assert_ver_order("10b2", "10a1", Ordering::Greater);
        assert_ver_order("10a2", "10b2", Ordering::Less);

        assert_ver_order("6.6p1", "7.5p1", Ordering::Less);
        assert_ver_order("7.5p1", "6.6p1", Ordering::Greater);

        assert_ver_order("6.5p1", "6.5p1", Ordering::Equal);
        assert_ver_order("6.5p1", "6.5p2", Ordering::Less);
        assert_ver_order("6.5p2", "6.5p1", Ordering::Greater);
        assert_ver_order("6.5p2", "6.6p1", Ordering::Less);
        assert_ver_order("6.6p1", "6.5p2", Ordering::Greater);

        assert_ver_order("6.5p10", "6.5p10", Ordering::Equal);
        assert_ver_order("6.5p1", "6.5p10", Ordering::Less);
        assert_ver_order("6.5p10", "6.5p1", Ordering::Greater);

        assert_ver_order("abc10", "abc10", Ordering::Equal);
        assert_ver_order("abc10", "abc10.1", Ordering::Less);
        assert_ver_order("abc10.1", "abc10", Ordering::Greater);

        assert_ver_order("abc.4", "abc.4", Ordering::Equal);
        assert_ver_order("abc.4", "8", Ordering::Less);
        assert_ver_order("8", "abc.4", Ordering::Greater);
        assert_ver_order("abc.4", "2", Ordering::Less);
        assert_ver_order("2", "abc.4", Ordering::Greater);

        assert_ver_order("1.0aa", "1.0aa", Ordering::Equal);
        assert_ver_order("1.0a", "1.0aa", Ordering::Less);
        assert_ver_order("1.0aa", "1.0a", Ordering::Greater);
    }

    /// test handling of numeric-like values in version strings
    #[test]
    fn test_version_comparison_numeric_handling() {
        assert_ver_order("10.0001", "10.0001", Ordering::Equal);
        // sequences of leading zeroes are meant to be ignored - it's not *actually* treated like a numeric value
        assert_ver_order("10.0001", "10.1", Ordering::Equal);
        assert_ver_order("10.1", "10.0001", Ordering::Equal);
        assert_ver_order("10.0001", "10.0039", Ordering::Less);
        assert_ver_order("10.0039", "10.0001", Ordering::Greater);
        // but sequences of zeroes within a numeric segment are not ignored
        assert_ver_order("10.1", "10.10001", Ordering::Less);
        assert_ver_order("10.1111", "10.10001", Ordering::Less);
        assert_ver_order("10.11111", "10.10001", Ordering::Greater);

        assert_ver_order("20240521", "20240521", Ordering::Equal);
        assert_ver_order("20240521", "20240522", Ordering::Less);
        assert_ver_order("20240522", "20240521", Ordering::Greater);
        assert_ver_order("20240521", "202405210", Ordering::Less);
    }

    /// Test behavior of tilde and caret operators
    #[test]
    fn test_version_comparison_tilde_and_caret() {
        assert_ver_order("1.0~rc1", "1.0~rc1", Ordering::Equal);
        assert_ver_order("1.0~rc1", "1.0", Ordering::Less);
        assert_ver_order("1.0", "1.0~rc1", Ordering::Greater);
        assert_ver_order("1.0~rc1", "1.0~rc2", Ordering::Less);
        assert_ver_order("1.0~rc2", "1.0~rc1", Ordering::Greater);
        assert_ver_order("1.0~rc1~git123", "1.0~rc1~git123", Ordering::Equal);
        assert_ver_order("1.0~rc1~git123", "1.0~rc1", Ordering::Less);
        assert_ver_order("1.0~rc1", "1.0~rc1~git123", Ordering::Greater);

        assert_ver_order("1.0^", "1.0^", Ordering::Equal);
        assert_ver_order("1.0", "1.0^", Ordering::Less);
        assert_ver_order("1.0^", "1.0", Ordering::Greater);

        assert_ver_order("1.0", "1.0git1^", Ordering::Less);
        assert_ver_order("1.0^git1", "1.0^git2", Ordering::Less);
        assert_ver_order("1.01", "1.0^git1", Ordering::Greater);
        assert_ver_order("1.0^20240501", "1.0^20240501", Ordering::Equal);
        assert_ver_order("1.0^20240501", "1.0.1", Ordering::Less);
        assert_ver_order("1.0^20240501^git1", "1.0^20240501^git1", Ordering::Equal);
        assert_ver_order("1.0^20240502", "1.0^20240501^git1", Ordering::Greater);
        assert_ver_order("1.0~rc1^git1", "1.0~rc1^git1", Ordering::Equal);
        assert_ver_order("1.0~rc1", "1.0~rc1^git1", Ordering::Less);
        assert_ver_order("1.0~rc1^git1", "1.0~rc1", Ordering::Greater);
        assert_ver_order("1.0^git1~pre", "1.0^git1~pre", Ordering::Equal);
        assert_ver_order("1.0^git1~pre", "1.0^git1", Ordering::Less);
        assert_ver_order("1.0^git1", "1.0^git1~pre", Ordering::Greater);
    }

    /// Test some version comparison behavior that is a bit non-intuitive
    /// (but needs to be maintained for compatibility)
    #[test]
    fn test_non_intuitive_comparison_behavior() {
        assert_ver_order("1e.fc33", "1.fc33", Ordering::Less);
        assert_ver_order("1g.fc33", "1.fc33", Ordering::Greater);
    }

    /// Test handling of non-alphanumeric ascii characters (excluding separators)
    #[test]
    fn test_non_alphanumeric_equivalence() {
        // the existence of sequences of non-alphanumeric characters should not impact the version comparison at all
        assert_ver_order("b", "b", Ordering::Equal);
        assert_ver_order("b+", "b+", Ordering::Equal);
        assert_ver_order("b+", "b_", Ordering::Equal);
        assert_ver_order("b_", "b+", Ordering::Equal);
        assert_ver_order("+b", "+b", Ordering::Equal);
        assert_ver_order("+b", "_b", Ordering::Equal);
        assert_ver_order("_b", "+b", Ordering::Equal);

        assert_ver_order("+b", "++b", Ordering::Equal);
        assert_ver_order("+b", "+b+", Ordering::Equal);

        assert_ver_order("+.", "+_", Ordering::Equal);
        assert_ver_order("_+", "+.", Ordering::Equal);
        assert_ver_order("+", ".", Ordering::Equal);
        assert_ver_order(",", "+", Ordering::Equal);

        assert_ver_order("++", "_", Ordering::Equal);
        assert_ver_order("+", "..", Ordering::Equal);

        assert_ver_order("4_0", "4_0", Ordering::Equal);
        assert_ver_order("4_0", "4.0", Ordering::Equal);
        assert_ver_order("4.0", "4_0", Ordering::Equal);

        assert_ver_order("4.999", "5.0", Ordering::Less);
        assert_ver_order("4.999.9", "5.0", Ordering::Less);
        assert_ver_order("5.0", "4.999_9", Ordering::Greater);

        // except when it comes to breaking up sequences of alphanumeric characters that do impact the comparison
        assert_ver_order("4.999", "4.999.9", Ordering::Less);
        assert_ver_order("4.999", "4.99.9", Ordering::Greater);
    }

    /// Test handling of non-ascii characters
    #[test]
    fn test_non_ascii_character_equivalence() {
        // the existence of sequences of non-ascii characters should not impact the version comparison at all
        assert_ver_order("1.1.Á.1", "1.1.1", Ordering::Equal);
        assert_ver_order("1.1.Á", "1.1.Á", Ordering::Equal);
        assert_ver_order("1.1.Á", "1.1.Ê", Ordering::Equal);
        assert_ver_order("1.1.ÁÁ", "1.1.Á", Ordering::Equal);
        assert_ver_order("1.1.Á", "1.1.ÊÊ", Ordering::Equal);

        // except when it comes to breaking up sequences of ascii characters that do impact the comparison
        assert_ver_order("1.1Á1", "1.11", Ordering::Less);
    }

    /// Test that Hash is consistent with PartialEq (equal values must hash the same)
    #[test]
    fn test_evr_hash_consistency() {
        use std::hash::{DefaultHasher, Hash, Hasher};

        fn hash_of<T: Hash>(val: &T) -> u64 {
            let mut h = DefaultHasher::new();
            val.hash(&mut h);
            h.finish()
        }

        // empty epoch and "0" epoch are equal, so must hash the same
        let evr1 = Evr::parse("1.2.3-45");
        let evr2 = Evr::parse("0:1.2.3-45");
        assert_eq!(evr1, evr2);
        assert_eq!(hash_of(&evr1), hash_of(&evr2));

        // identical EVRs hash the same
        let evr3 = Evr::parse("2:1.2.3-45");
        let evr4 = Evr::parse("2:1.2.3-45");
        assert_eq!(hash_of(&evr3), hash_of(&evr4));

        // different EVRs should (almost certainly) hash differently
        assert_ne!(hash_of(&evr1), hash_of(&evr3));
    }

    /// Test that Nevra Hash is consistent with PartialEq
    #[test]
    fn test_nevra_hash_consistency() {
        use std::hash::{DefaultHasher, Hash, Hasher};

        fn hash_of<T: Hash>(val: &T) -> u64 {
            let mut h = DefaultHasher::new();
            val.hash(&mut h);
            h.finish()
        }

        let nevra1 = Nevra::parse("foo-1.2.3-45.noarch");
        let nevra2 = Nevra::parse("foo-0:1.2.3-45.noarch");
        assert_eq!(nevra1, nevra2);
        assert_eq!(hash_of(&nevra1), hash_of(&nevra2));

        let nevra3 = Nevra::parse("foo-1:1.2.3-45.noarch");
        assert_ne!(hash_of(&nevra1), hash_of(&nevra3));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_evr_serde_roundtrip() {
        let evr = Evr::parse("1:2.3.4-5");
        let json = serde_json::to_string(&evr).unwrap();
        let evr2: Evr = serde_json::from_str(&json).unwrap();
        assert_eq!(evr, evr2);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_nevra_serde_roundtrip() {
        let nevra = Nevra::parse("foo-1:2.3.4-5.x86_64");
        let json = serde_json::to_string(&nevra).unwrap();
        let nevra2: Nevra = serde_json::from_str(&json).unwrap();
        assert_eq!(nevra, nevra2);
    }

    #[test]
    fn test_requirement_no_constraint() {
        let req = Requirement::new("foo");
        assert!(req.satisfies("foo", &Evr::parse("1.0-1")));
        assert!(req.satisfies("foo", &Evr::parse("999.0-1")));
        assert!(!req.satisfies("bar", &Evr::parse("1.0-1")));
    }

    #[test]
    fn test_requirement_eq() {
        let req = Requirement::with_constraint("foo", ReqOperator::EQ, Evr::parse("1.0-1"));
        assert!(req.satisfies("foo", &Evr::parse("1.0-1")));
        assert!(req.satisfies("foo", &Evr::parse("0:1.0-1")));
        assert!(!req.satisfies("foo", &Evr::parse("1.0-2")));
        assert!(!req.satisfies("foo", &Evr::parse("2.0-1")));
    }

    #[test]
    fn test_requirement_ge() {
        let req = Requirement::with_constraint("foo", ReqOperator::GE, Evr::parse("1.0-1"));
        assert!(req.satisfies("foo", &Evr::parse("1.0-1")));
        assert!(req.satisfies("foo", &Evr::parse("2.0-1")));
        assert!(!req.satisfies("foo", &Evr::parse("0.9-1")));
    }

    #[test]
    fn test_requirement_lt() {
        let req = Requirement::with_constraint("foo", ReqOperator::LT, Evr::parse("2.0-1"));
        assert!(req.satisfies("foo", &Evr::parse("1.0-1")));
        assert!(!req.satisfies("foo", &Evr::parse("2.0-1")));
        assert!(!req.satisfies("foo", &Evr::parse("3.0-1")));
    }

    #[test]
    fn test_requirement_display() {
        let req = Requirement::new("foo");
        assert_eq!(req.to_string(), "foo");

        let req = Requirement::with_constraint("foo", ReqOperator::GE, Evr::parse("1:2.0-1"));
        assert_eq!(req.to_string(), "foo >= 1:2.0-1");
    }
}