-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathversion.rs
2567 lines (2399 loc) · 87.3 KB
/
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
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::sync::LazyLock;
use std::{
borrow::Borrow,
cmp::Ordering,
hash::{Hash, Hasher},
str::FromStr,
sync::Arc,
};
/// One of `~=` `==` `!=` `<=` `>=` `<` `>` `===`
#[derive(Eq, Ord, PartialEq, PartialOrd, Debug, Hash, Clone, Copy)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize,)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug, Eq, PartialEq, PartialOrd, Ord)))]
pub enum Operator {
/// `== 1.2.3`
Equal,
/// `== 1.2.*`
EqualStar,
/// `===` (discouraged)
///
/// <https://peps.python.org/pep-0440/#arbitrary-equality>
///
/// "Use of this operator is heavily discouraged and tooling MAY display a warning when it is used"
// clippy doesn't like this: #[deprecated = "Use of this operator is heavily discouraged"]
ExactEqual,
/// `!= 1.2.3`
NotEqual,
/// `!= 1.2.*`
NotEqualStar,
/// `~=`
///
/// Invariant: With `~=`, there are always at least 2 release segments.
TildeEqual,
/// `<`
LessThan,
/// `<=`
LessThanEqual,
/// `>`
GreaterThan,
/// `>=`
GreaterThanEqual,
}
impl Operator {
/// Negates this operator, if a negation exists, so that it has the
/// opposite meaning.
///
/// This returns a negated operator in every case except for the `~=`
/// operator. In that case, `None` is returned and callers may need to
/// handle its negation at a higher level. (For example, if it's negated
/// in the context of a marker expression, then the "compatible" version
/// constraint can be split into its component parts and turned into a
/// disjunction of the negation of each of those parts.)
///
/// Note that this routine is not reversible in all cases. For example
/// `Operator::ExactEqual` negates to `Operator::NotEqual`, and
/// `Operator::NotEqual` in turn negates to `Operator::Equal`.
pub fn negate(self) -> Option<Operator> {
Some(match self {
Operator::Equal => Operator::NotEqual,
Operator::EqualStar => Operator::NotEqualStar,
Operator::ExactEqual => Operator::NotEqual,
Operator::NotEqual => Operator::Equal,
Operator::NotEqualStar => Operator::EqualStar,
Operator::TildeEqual => return None,
Operator::LessThan => Operator::GreaterThanEqual,
Operator::LessThanEqual => Operator::GreaterThan,
Operator::GreaterThan => Operator::LessThanEqual,
Operator::GreaterThanEqual => Operator::LessThan,
})
}
/// Returns true if and only if this operator can be used in a version
/// specifier with a version containing a non-empty local segment.
///
/// Specifically, this comes from the "Local version identifiers are
/// NOT permitted in this version specifier." phrasing in the version
/// specifiers [spec].
///
/// [spec]: https://packaging.python.org/en/latest/specifications/version-specifiers/
pub(crate) fn is_local_compatible(self) -> bool {
!matches!(
self,
Self::GreaterThan
| Self::GreaterThanEqual
| Self::LessThan
| Self::LessThanEqual
| Self::TildeEqual
| Self::EqualStar
| Self::NotEqualStar
)
}
/// Returns the wildcard version of this operator, if appropriate.
///
/// This returns `None` when this operator doesn't have an analogous
/// wildcard operator.
pub(crate) fn to_star(self) -> Option<Self> {
match self {
Self::Equal => Some(Self::EqualStar),
Self::NotEqual => Some(Self::NotEqualStar),
_ => None,
}
}
/// Returns `true` if this operator represents a wildcard.
pub fn is_star(self) -> bool {
matches!(self, Self::EqualStar | Self::NotEqualStar)
}
}
impl FromStr for Operator {
type Err = OperatorParseError;
/// Notably, this does not know about star versions, it just assumes the base operator
fn from_str(s: &str) -> Result<Self, Self::Err> {
let operator = match s {
"==" => Self::Equal,
"===" => {
#[cfg(feature = "tracing")]
{
tracing::warn!("Using arbitrary equality (`===`) is discouraged");
}
#[allow(deprecated)]
Self::ExactEqual
}
"!=" => Self::NotEqual,
"~=" => Self::TildeEqual,
"<" => Self::LessThan,
"<=" => Self::LessThanEqual,
">" => Self::GreaterThan,
">=" => Self::GreaterThanEqual,
other => {
return Err(OperatorParseError {
got: other.to_string(),
})
}
};
Ok(operator)
}
}
impl std::fmt::Display for Operator {
/// Note the `EqualStar` is also `==`.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let operator = match self {
Self::Equal => "==",
// Beware, this doesn't print the star
Self::EqualStar => "==",
#[allow(deprecated)]
Self::ExactEqual => "===",
Self::NotEqual => "!=",
Self::NotEqualStar => "!=",
Self::TildeEqual => "~=",
Self::LessThan => "<",
Self::LessThanEqual => "<=",
Self::GreaterThan => ">",
Self::GreaterThanEqual => ">=",
};
write!(f, "{operator}")
}
}
/// An error that occurs when parsing an invalid version specifier operator.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OperatorParseError {
pub(crate) got: String,
}
impl std::error::Error for OperatorParseError {}
impl std::fmt::Display for OperatorParseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"no such comparison operator {:?}, must be one of ~= == != <= >= < > ===",
self.got
)
}
}
// NOTE: I did a little bit of experimentation to determine what most version
// numbers actually look like. The idea here is that if we know what most look
// like, then we can optimize our representation for the common case, while
// falling back to something more complete for any cases that fall outside of
// that.
//
// The experiment downloaded PyPI's distribution metadata from Google BigQuery,
// and then counted the number of versions with various qualities:
//
// total: 11264078
// release counts:
// 01: 51204 (0.45%)
// 02: 754520 (6.70%)
// 03: 9757602 (86.63%)
// 04: 527403 (4.68%)
// 05: 77994 (0.69%)
// 06: 91346 (0.81%)
// 07: 1421 (0.01%)
// 08: 205 (0.00%)
// 09: 72 (0.00%)
// 10: 2297 (0.02%)
// 11: 5 (0.00%)
// 12: 2 (0.00%)
// 13: 4 (0.00%)
// 20: 2 (0.00%)
// 39: 1 (0.00%)
// JUST release counts:
// 01: 48297 (0.43%)
// 02: 604692 (5.37%)
// 03: 8460917 (75.11%)
// 04: 465354 (4.13%)
// 05: 49293 (0.44%)
// 06: 25909 (0.23%)
// 07: 1413 (0.01%)
// 08: 192 (0.00%)
// 09: 72 (0.00%)
// 10: 2292 (0.02%)
// 11: 5 (0.00%)
// 12: 2 (0.00%)
// 13: 4 (0.00%)
// 20: 2 (0.00%)
// 39: 1 (0.00%)
// non-zero epochs: 1902 (0.02%)
// pre-releases: 752184 (6.68%)
// post-releases: 134383 (1.19%)
// dev-releases: 765099 (6.79%)
// locals: 1 (0.00%)
// fitsu8: 10388430 (92.23%)
// sweetspot: 10236089 (90.87%)
//
// The "JUST release counts" corresponds to versions that only have a release
// component and nothing else. The "fitsu8" property indicates that all numbers
// (except for local numeric segments) fit into `u8`. The "sweetspot" property
// consists of any version number with no local part, 4 or fewer parts in the
// release version and *all* numbers fit into a u8.
//
// This somewhat confirms what one might expect: the vast majority of versions
// (75%) are precisely in the format of `x.y.z`. That is, a version with only a
// release version of 3 components.
//
// ---AG
/// A version number such as `1.2.3` or `4!5.6.7-a8.post9.dev0`.
///
/// Beware that the sorting implemented with [Ord] and [Eq] is not consistent with the operators
/// from PEP 440, i.e. compare two versions in rust with `>` gives a different result than a
/// `VersionSpecifier` with `>` as operator.
///
/// Parse with [`Version::from_str`]:
///
/// ```rust
/// use std::str::FromStr;
/// use pep440_rs::Version;
///
/// let version = Version::from_str("1.19").unwrap();
/// ```
#[derive(Clone)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug, Eq, PartialEq, PartialOrd, Ord)))]
pub struct Version {
inner: Arc<VersionInner>,
}
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug, Eq, PartialEq, PartialOrd, Ord)))]
enum VersionInner {
Small { small: VersionSmall },
Full { full: VersionFull },
}
impl Version {
/// Create a new version from an iterator of segments in the release part
/// of a version.
///
/// # Panics
///
/// When the iterator yields no elements.
#[inline]
pub fn new<I, R>(release_numbers: I) -> Self
where
I: IntoIterator<Item = R>,
R: Borrow<u64>,
{
Self {
inner: Arc::new(VersionInner::Small {
small: VersionSmall::new(),
}),
}
.with_release(release_numbers)
}
/// Whether this is an alpha/beta/rc or dev version
#[inline]
pub fn any_prerelease(&self) -> bool {
self.is_pre() || self.is_dev()
}
/// Whether this is a stable version (i.e., _not_ an alpha/beta/rc or dev version)
#[inline]
pub fn is_stable(&self) -> bool {
!self.is_pre() && !self.is_dev()
}
/// Whether this is an alpha/beta/rc version
#[inline]
pub fn is_pre(&self) -> bool {
self.pre().is_some()
}
/// Whether this is a dev version
#[inline]
pub fn is_dev(&self) -> bool {
self.dev().is_some()
}
/// Whether this is a post version
#[inline]
pub fn is_post(&self) -> bool {
self.post().is_some()
}
/// Whether this is a local version (e.g. `1.2.3+localsuffixesareweird`)
///
/// When true, it is guaranteed that the slice returned by
/// [`Version::local`] is non-empty.
#[inline]
pub fn is_local(&self) -> bool {
!self.local().is_empty()
}
/// Returns the epoch of this version.
#[inline]
pub fn epoch(&self) -> u64 {
match *self.inner {
VersionInner::Small { ref small } => small.epoch(),
VersionInner::Full { ref full } => full.epoch,
}
}
/// Returns the release number part of the version.
#[inline]
pub fn release(&self) -> &[u64] {
match *self.inner {
VersionInner::Small { ref small } => small.release(),
VersionInner::Full { ref full, .. } => &full.release,
}
}
/// Returns the pre-release part of this version, if it exists.
#[inline]
pub fn pre(&self) -> Option<Prerelease> {
match *self.inner {
VersionInner::Small { ref small } => small.pre(),
VersionInner::Full { ref full } => full.pre,
}
}
/// Returns the post-release part of this version, if it exists.
#[inline]
pub fn post(&self) -> Option<u64> {
match *self.inner {
VersionInner::Small { ref small } => small.post(),
VersionInner::Full { ref full } => full.post,
}
}
/// Returns the dev-release part of this version, if it exists.
#[inline]
pub fn dev(&self) -> Option<u64> {
match *self.inner {
VersionInner::Small { ref small } => small.dev(),
VersionInner::Full { ref full } => full.dev,
}
}
/// Returns the local segments in this version, if any exist.
#[inline]
pub fn local(&self) -> LocalVersionSlice {
match *self.inner {
VersionInner::Small { ref small } => small.local_slice(),
VersionInner::Full { ref full } => full.local.as_slice(),
}
}
/// Returns the min-release part of this version, if it exists.
///
/// The "min" component is internal-only, and does not exist in PEP 440.
/// The version `1.0min0` is smaller than all other `1.0` versions,
/// like `1.0a1`, `1.0dev0`, etc.
#[inline]
pub fn min(&self) -> Option<u64> {
match *self.inner {
VersionInner::Small { ref small } => small.min(),
VersionInner::Full { ref full } => full.min,
}
}
/// Returns the max-release part of this version, if it exists.
///
/// The "max" component is internal-only, and does not exist in PEP 440.
/// The version `1.0max0` is larger than all other `1.0` versions,
/// like `1.0.post1`, `1.0+local`, etc.
#[inline]
pub fn max(&self) -> Option<u64> {
match *self.inner {
VersionInner::Small { ref small } => small.max(),
VersionInner::Full { ref full } => full.max,
}
}
/// Set the release numbers and return the updated version.
///
/// Usually one can just use `Version::new` to create a new version with
/// the updated release numbers, but this is useful when one wants to
/// preserve the other components of a version number while only changing
/// the release numbers.
///
/// # Panics
///
/// When the iterator yields no elements.
#[inline]
#[must_use]
pub fn with_release<I, R>(mut self, release_numbers: I) -> Self
where
I: IntoIterator<Item = R>,
R: Borrow<u64>,
{
self.clear_release();
for n in release_numbers {
self.push_release(*n.borrow());
}
assert!(
!self.release().is_empty(),
"release must have non-zero size"
);
self
}
/// Push the given release number into this version. It will become the
/// last number in the release component.
#[inline]
fn push_release(&mut self, n: u64) {
if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) {
if small.push_release(n) {
return;
}
}
self.make_full().release.push(n);
}
/// Clears the release component of this version so that it has no numbers.
///
/// Generally speaking, this empty state should not be exposed to callers
/// since all versions should have at least one release number.
#[inline]
fn clear_release(&mut self) {
match Arc::make_mut(&mut self.inner) {
VersionInner::Small { ref mut small } => small.clear_release(),
VersionInner::Full { ref mut full } => {
full.release.clear();
}
}
}
/// Set the epoch and return the updated version.
#[inline]
#[must_use]
pub fn with_epoch(mut self, value: u64) -> Self {
if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) {
if small.set_epoch(value) {
return self;
}
}
self.make_full().epoch = value;
self
}
/// Set the pre-release component and return the updated version.
#[inline]
#[must_use]
pub fn with_pre(mut self, value: Option<Prerelease>) -> Self {
if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) {
if small.set_pre(value) {
return self;
}
}
self.make_full().pre = value;
self
}
/// Set the post-release component and return the updated version.
#[inline]
#[must_use]
pub fn with_post(mut self, value: Option<u64>) -> Self {
if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) {
if small.set_post(value) {
return self;
}
}
self.make_full().post = value;
self
}
/// Set the dev-release component and return the updated version.
#[inline]
#[must_use]
pub fn with_dev(mut self, value: Option<u64>) -> Self {
if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) {
if small.set_dev(value) {
return self;
}
}
self.make_full().dev = value;
self
}
/// Set the local segments and return the updated version.
#[inline]
#[must_use]
pub fn with_local_segments(mut self, value: Vec<LocalSegment>) -> Self {
if value.is_empty() {
self.without_local()
} else {
self.make_full().local = LocalVersion::Segments(value);
self
}
}
/// Set the local version and return the updated version.
#[inline]
#[must_use]
pub fn with_local(mut self, value: LocalVersion) -> Self {
match value {
LocalVersion::Segments(segments) => self.with_local_segments(segments),
LocalVersion::Max => {
if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) {
if small.set_local(LocalVersion::Max) {
return self;
}
}
self.make_full().local = value;
self
}
}
}
/// For PEP 440 specifier matching: "Except where specifically noted below,
/// local version identifiers MUST NOT be permitted in version specifiers,
/// and local version labels MUST be ignored entirely when checking if
/// candidate versions match a given version specifier."
#[inline]
#[must_use]
pub fn without_local(mut self) -> Self {
if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) {
if small.set_local(LocalVersion::empty()) {
return self;
}
}
self.make_full().local = LocalVersion::empty();
self
}
/// Return the version with any segments apart from the release removed.
#[inline]
#[must_use]
pub fn only_release(&self) -> Self {
Self::new(self.release().iter().copied())
}
/// Set the min-release component and return the updated version.
///
/// The "min" component is internal-only, and does not exist in PEP 440.
/// The version `1.0min0` is smaller than all other `1.0` versions,
/// like `1.0a1`, `1.0dev0`, etc.
#[inline]
#[must_use]
pub fn with_min(mut self, value: Option<u64>) -> Self {
debug_assert!(!self.is_pre(), "min is not allowed on pre-release versions");
debug_assert!(!self.is_dev(), "min is not allowed on dev versions");
if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) {
if small.set_min(value) {
return self;
}
}
self.make_full().min = value;
self
}
/// Set the max-release component and return the updated version.
///
/// The "max" component is internal-only, and does not exist in PEP 440.
/// The version `1.0max0` is larger than all other `1.0` versions,
/// like `1.0.post1`, `1.0+local`, etc.
#[inline]
#[must_use]
pub fn with_max(mut self, value: Option<u64>) -> Self {
debug_assert!(
!self.is_post(),
"max is not allowed on post-release versions"
);
debug_assert!(!self.is_dev(), "max is not allowed on dev versions");
if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) {
if small.set_max(value) {
return self;
}
}
self.make_full().max = value;
self
}
/// Convert this version to a "full" representation in-place and return a
/// mutable borrow to the full type.
fn make_full(&mut self) -> &mut VersionFull {
if let VersionInner::Small { ref small } = *self.inner {
let full = VersionFull {
epoch: small.epoch(),
release: small.release().to_vec(),
min: small.min(),
max: small.max(),
pre: small.pre(),
post: small.post(),
dev: small.dev(),
local: small.local(),
};
*self = Self {
inner: Arc::new(VersionInner::Full { full }),
};
}
match Arc::make_mut(&mut self.inner) {
VersionInner::Full { ref mut full } => full,
VersionInner::Small { .. } => unreachable!(),
}
}
/// Performs a "slow" but complete comparison between two versions.
///
/// This comparison is done using only the public API of a `Version`, and
/// is thus independent of its specific representation. This is useful
/// to use when comparing two versions that aren't *both* the small
/// representation.
#[cold]
#[inline(never)]
fn cmp_slow(&self, other: &Self) -> Ordering {
match self.epoch().cmp(&other.epoch()) {
Ordering::Less => {
return Ordering::Less;
}
Ordering::Equal => {}
Ordering::Greater => {
return Ordering::Greater;
}
}
match compare_release(self.release(), other.release()) {
Ordering::Less => {
return Ordering::Less;
}
Ordering::Equal => {}
Ordering::Greater => {
return Ordering::Greater;
}
}
// release is equal, so compare the other parts
sortable_tuple(self).cmp(&sortable_tuple(other))
}
}
/// <https://github.com/serde-rs/serde/issues/1316#issue-332908452>
impl<'de> Deserialize<'de> for Version {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
FromStr::from_str(&s).map_err(de::Error::custom)
}
}
/// <https://github.com/serde-rs/serde/issues/1316#issue-332908452>
impl Serialize for Version {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(self)
}
}
/// Shows normalized version
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let epoch = if self.epoch() == 0 {
String::new()
} else {
format!("{}!", self.epoch())
};
let release = self
.release()
.iter()
.map(ToString::to_string)
.collect::<Vec<String>>()
.join(".");
let pre = self
.pre()
.as_ref()
.map(|Prerelease { kind, number }| format!("{kind}{number}"))
.unwrap_or_default();
let post = self
.post()
.map(|post| format!(".post{post}"))
.unwrap_or_default();
let dev = self
.dev()
.map(|dev| format!(".dev{dev}"))
.unwrap_or_default();
let local = if self.local().is_empty() {
String::new()
} else {
match self.local() {
LocalVersionSlice::Segments(_) => {
format!("+{}", self.local())
}
LocalVersionSlice::Max => "+".to_string(),
}
};
write!(f, "{epoch}{release}{pre}{post}{dev}{local}")
}
}
impl std::fmt::Debug for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "\"{self}\"")
}
}
impl PartialEq<Self> for Version {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Version {}
impl Hash for Version {
/// Custom implementation to ignoring trailing zero because `PartialEq` zero pads
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.epoch().hash(state);
// Skip trailing zeros
for i in self.release().iter().rev().skip_while(|x| **x == 0) {
i.hash(state);
}
self.pre().hash(state);
self.dev().hash(state);
self.post().hash(state);
self.local().hash(state);
}
}
impl PartialOrd<Self> for Version {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Version {
/// 1.0.dev456 < 1.0a1 < 1.0a2.dev456 < 1.0a12.dev456 < 1.0a12 < 1.0b1.dev456 < 1.0b2
/// < 1.0b2.post345.dev456 < 1.0b2.post345 < 1.0b2-346 < 1.0c1.dev456 < 1.0c1 < 1.0rc2 < 1.0c3
/// < 1.0 < 1.0.post456.dev34 < 1.0.post456
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
match (&*self.inner, &*other.inner) {
(VersionInner::Small { small: small1 }, VersionInner::Small { small: small2 }) => {
small1.repr.cmp(&small2.repr)
}
_ => self.cmp_slow(other),
}
}
}
impl FromStr for Version {
type Err = VersionParseError;
/// Parses a version such as `1.19`, `1.0a1`,`1.0+abc.5` or `1!2012.2`
///
/// Note that this doesn't allow wildcard versions.
fn from_str(version: &str) -> Result<Self, Self::Err> {
Parser::new(version.as_bytes()).parse()
}
}
/// A "small" representation of a version.
///
/// This representation is used for a (very common) subset of versions: the
/// set of all versions with ~small numbers and no local component. The
/// representation is designed to be (somewhat) compact, but also laid out in
/// a way that makes comparisons between two small versions equivalent to a
/// simple `memcmp`.
///
/// The methods on this type encapsulate the representation. Since this type
/// cannot represent the full range of all versions, setters on this type will
/// return `false` if the value could not be stored. In this case, callers
/// should generally convert a version into its "full" representation and then
/// set the value on the full type.
///
/// # Representation
///
/// At time of writing, this representation supports versions that meet all of
/// the following criteria:
///
/// * The epoch must be `0`.
/// * The release portion must have 4 or fewer segments.
/// * All release segments, except for the first, must be representable in a
/// `u8`. The first segment must be representable in a `u16`. (This permits
/// calendar versions, like `2023.03`, to be represented.)
/// * There is *at most* one of the following components: pre, dev or post.
/// * If there is a pre segment, then its numeric value is less than 64.
/// * If there is a dev or post segment, then its value is less than `u8::MAX`.
/// * There are zero "local" segments.
///
/// The above constraints were chosen as a balancing point between being able
/// to represent all parts of a version in a very small amount of space,
/// and for supporting as many versions in the wild as possible. There is,
/// however, another constraint in play here: comparisons between two `Version`
/// values. It turns out that we do a lot of them as part of resolution, and
/// the cheaper we can make that, the better. This constraint pushes us
/// toward using as little space as possible. Indeed, here, comparisons are
/// implemented via `u64::cmp`.
///
/// We pack versions fitting the above constraints into a `u64` in such a way
/// that it preserves the ordering between versions as prescribed in PEP 440.
/// Namely:
///
/// * Bytes 6 and 7 correspond to the first release segment as a `u16`.
/// * Bytes 5, 4 and 3 correspond to the second, third and fourth release
/// segments, respectively.
/// * Bytes 2, 1 and 0 represent *one* of the following:
/// `min, .devN, aN, bN, rcN, <no suffix>, local, .postN, max`.
/// Its representation is thus:
/// * The most significant 4 bits of Byte 2 corresponds to a value in
/// the range 0-8 inclusive, corresponding to min, dev, pre-a, pre-b,
/// pre-rc, no-suffix, post or max releases, respectively. `min` is a
/// special version that does not exist in PEP 440, but is used here to
/// represent the smallest possible version, preceding any `dev`, `pre`,
/// `post` or releases. `max` is an analogous concept for the largest
/// possible version, following any `post` or local releases.
/// * The low 4 bits combined with the bits in bytes 1 and 0 correspond
/// to the release number of the suffix, if one exists. If there is no
/// suffix, then these bits are always 0.
///
/// The order of the encoding above is significant. For example, suffixes are
/// encoded at a less significant location than the release numbers, so that
/// `1.2.3 < 1.2.3.post4`.
///
/// In a previous representation, we tried to encode the suffixes in different
/// locations so that, in theory, you could represent `1.2.3.dev2.post3` in the
/// packed form. But getting the ordering right for this is difficult (perhaps
/// impossible without extra space?). So we limited to only storing one suffix.
/// But even then, we wound up with a bug where `1.0dev1 > 1.0a1`, when of
/// course, all dev releases should compare less than pre releases. This was
/// because the encoding recorded the pre-release as "absent", and this in turn
/// screwed up the order comparisons.
///
/// Thankfully, such versions are incredibly rare. Virtually all versions have
/// zero or one pre, dev or post release components.
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[cfg_attr(feature = "rkyv", rkyv(derive(Debug, Eq, PartialEq, PartialOrd, Ord)))]
struct VersionSmall {
/// The representation discussed above.
repr: u64,
/// The `u64` numbers in the release component.
///
/// These are *only* used to implement the public API `Version::release`
/// method. This is necessary in order to provide a `&[u64]` to the caller.
/// If we didn't need the public API, or could re-work it, then we could
/// get rid of this extra storage. (Which is indeed duplicative of what is
/// stored in `repr`.) Note that this uses `u64` not because it can store
/// bigger numbers than what's in `repr` (it can't), but so that it permits
/// us to return a `&[u64]`.
///
/// I believe there is only one way to get rid of this extra storage:
/// change the public API so that it doesn't return a `&[u64]`. Instead,
/// we'd return a new type that conceptually represents a `&[u64]`, but may
/// use a different representation based on what kind of `Version` it came
/// from. The downside of this approach is that one loses the flexibility
/// of a simple `&[u64]`. (Which, at time of writing, is taken advantage of
/// in several places via slice patterns.) But, if we needed to change it,
/// we could do it without losing expressivity, but losing convenience.
release: [u64; 4],
/// The number of segments in the release component.
///
/// Strictly speaking, this isn't necessary since `1.2` is considered
/// equivalent to `1.2.0.0`. But in practice it's nice to be able
/// to truncate the zero components. And always filling out to 4
/// places somewhat exposes internal details, since the "full" version
/// representation would not do that.
len: u8,
}
impl VersionSmall {
// Constants for each suffix kind. They form an enumeration.
//
// The specific values are assigned in a way that provides the suffix kinds
// their ordering. i.e., No suffix should sort after a dev suffix but
// before a post suffix.
//
// The maximum possible suffix value is SUFFIX_KIND_MASK. If you need to
// add another suffix value and you're at the max, then the mask must gain
// another bit. And adding another bit to the mask will require taking it
// from somewhere else. (Usually the suffix version.)
//
// NOTE: If you do change the bit format here, you'll need to bump any
// cache versions in uv that use rkyv with `Version` in them. That includes
// *at least* the "simple" cache.
const SUFFIX_MIN: u64 = 0;
const SUFFIX_DEV: u64 = 1;
const SUFFIX_PRE_ALPHA: u64 = 2;
const SUFFIX_PRE_BETA: u64 = 3;
const SUFFIX_PRE_RC: u64 = 4;
const SUFFIX_NONE: u64 = 5;
const SUFFIX_LOCAL: u64 = 6;
const SUFFIX_POST: u64 = 7;
const SUFFIX_MAX: u64 = 8;
// The mask to get only the release segment bits.
//
// NOTE: If you change the release mask to have more or less bits,
// then you'll also need to change `push_release` below and also
// `Parser::parse_fast`.
const SUFFIX_RELEASE_MASK: u64 = 0xFFFF_FFFF_FF00_0000;
// The mask to get the version suffix.
const SUFFIX_VERSION_MASK: u64 = 0x000F_FFFF;
// The number of bits used by the version suffix. Shifting the `repr`
// right by this number of bits should put the suffix kind in the least
// significant bits.
const SUFFIX_VERSION_BIT_LEN: u64 = 20;
// The mask to get only the suffix kind, after shifting right by the
// version bits. If you need to add a bit here, then you'll probably need
// to take a bit from the suffix version. (Which requires a change to both
// the mask and the bit length above.)
const SUFFIX_KIND_MASK: u64 = 0b1111;
#[inline]
fn new() -> Self {
Self {
repr: Self::SUFFIX_NONE << Self::SUFFIX_VERSION_BIT_LEN,
release: [0, 0, 0, 0],
len: 0,
}
}
#[inline]
#[allow(clippy::unused_self)]
fn epoch(&self) -> u64 {
0
}
#[inline]
#[allow(clippy::unused_self)]
fn set_epoch(&mut self, value: u64) -> bool {
if value != 0 {
return false;
}
true
}
#[inline]
fn release(&self) -> &[u64] {
&self.release[..usize::from(self.len)]
}
#[inline]
fn clear_release(&mut self) {
self.repr &= !Self::SUFFIX_RELEASE_MASK;
self.release = [0, 0, 0, 0];
self.len = 0;
}
#[inline]
fn push_release(&mut self, n: u64) -> bool {