nextver 0.8.4

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

/// An error that occurred while incrementing a [`Version`](crate::Version).
#[non_exhaustive]
#[derive(thiserror::Error, Debug, PartialEq)]
pub enum NextError {
    /// When updating a [`Cal`](crate::Cal) version, the date provided yielded an identical version.
    #[error("date provided should yield a version that is newer/greater than the current version")]
    NoCalendarChange,

    /// When updating a [`Cal`](crate::Cal) or [`CalSem`](crate::CalSem) version, the date year was
    /// negative.
    #[error("year `{year}` should not be negative when formatted`")]
    NegativeYearValue {
        /// The year value
        year: i32,
    },

    /// When updating/incrementing a [`Sem`](crate::Sem) or [`CalSem`](crate::CalSem) version, the
    /// semantic level is not in the format.
    #[error("`{spec}` was not found in format, use one that is")]
    SemLevelNotInFormat {
        /// The semantic specifier
        spec: String,
    },

    /// The new date passed to a `next` call was *before* the date represented by the current
    /// version.
    #[error("new date should be after date in version")]
    NewDateIsBefore,
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum VersionToken<'vs, S: Scheme> {
    Value {
        value: SpecValue,
        spec: &'static S::Specifier,
    },
    Literal(&'vs [u8]),
}

impl<'vs, S: Scheme> Clone for VersionToken<'vs, S> {
    fn clone(&self) -> Self {
        match self {
            VersionToken::Value { value, spec } => VersionToken::Value {
                value: *value,
                spec: *spec,
            },
            VersionToken::Literal(text) => VersionToken::Literal(text),
        }
    }
}

impl<'vs, S: Scheme> Display for VersionToken<'vs, S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VersionToken::Value { value, spec } => {
                let formatted = spec.format_value(*value);
                f.write_str(&formatted)
            }
            VersionToken::Literal(text) => {
                let text_str = unsafe { str::from_utf8_unchecked(text) };
                f.write_str(text_str)
            }
        }
    }
}

impl<'vs, S: Scheme> PartialOrd for VersionToken<'vs, S> {
    /// Compares two version tokens. This is only a partial ordering it is only meaningful to
    /// compare two version tokens when they come from the equivalent formats.
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        // it only makes sense to compare values if they are the same type, thus, only a partial
        // ordering.
        use VersionToken::{Literal, Value};
        match (self, other) {
            (Literal(a), Literal(b)) => {
                // there is no ordering for literals: they're either equal or not
                if a.eq(b) {
                    Some(std::cmp::Ordering::Equal)
                } else {
                    None
                }
            }

            (
                Value {
                    value: val_a,
                    spec: spec_a,
                },
                Value {
                    value: val_b,
                    spec: spec_b,
                },
            ) => {
                if ptr::eq(*spec_a, *spec_b) {
                    val_a.partial_cmp(val_b)
                } else {
                    None
                }
            }

            _ => None,
        }
    }
}

/// Just like a [`FormatToken`], but holds the literal text unescaped, so it can be quickly matched
/// against a version string (instead of having to recompute the unescaped text each time).
enum UnescapedFormatToken<S: Scheme> {
    Specifier(&'static S::Specifier),
    Literal(String),
}

impl<'fs, S: Scheme> From<&FormatToken<'fs, S>> for UnescapedFormatToken<S> {
    fn from(token: &FormatToken<'fs, S>) -> Self {
        match token {
            FormatToken::Specifier(spec) => UnescapedFormatToken::Specifier(*spec),
            FormatToken::Literal(literal) => {
                let unescaped = unsafe { std::str::from_utf8_unchecked(literal) }
                    .replace("<<", "<")
                    .replace(">>", ">");
                UnescapedFormatToken::Literal(unescaped)
            }
        }
    }
}

/// An error that occurred while parsing a version string.
#[allow(clippy::module_name_repetitions)]
#[non_exhaustive]
#[derive(thiserror::Error, Debug, PartialEq)]
pub enum VersionError {
    /// The format string's structure doesn't match the version string's.
    #[error("version `{version_string}` should match format `{format_string}`")]
    VersionFormatMismatch {
        /// The version string
        version_string: String,
        /// The format string
        format_string: String,
    },
}

/// A Version object represents a specific point in a project's development, comprised of *values*
/// and *literal text*. It's structure is defined by a [`Format`]. Versions can be displayed
/// (`to_string()`), incremented (`next()`), and compared (`partial_cmp()`).
///
/// Version objects are created with the [`Scheme::new_version`] or [`Format::new_version`] methods.
///
/// # (In)Equality
///
/// `Version` objects only implement a partial ordering. This is because the ordering only makes
/// sense when they have the same format. Therefore, comparisons between versions with different
/// formats will always return `false`.
///
/// # Examples
///
/// ```
/// use nextver::prelude::*;
///
/// let version = Sem::new_version("<MAJOR>.<MINOR>.<PATCH>", "1.2.3")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
///```
///
/// Or, use a previously created [`Format`] object:
///
/// ```
/// use nextver::prelude::*;
///
/// let format = Sem::new_format("<MAJOR>.<MINOR>.<PATCH>")?;
/// let version = format.new_version("1.2.3")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Version<'vs, S: Scheme> {
    pub(crate) tokens: Vec<VersionToken<'vs, S>>,
}

impl<'vs, S: Scheme> Version<'vs, S> {
    pub(crate) fn new(tokens: Vec<VersionToken<'vs, S>>) -> Self {
        Self { tokens }
    }
    pub(crate) fn parse(version_str: &'vs str, format: &Format<S>) -> Result<Self, VersionError> {
        let unescaped_format_tokens: Vec<UnescapedFormatToken<S>> =
            format.tokens.iter().map(Into::into).collect();
        Self::parse_rec(version_str.as_bytes(), &unescaped_format_tokens, &[])
            .map(|tokens| Version::new(tokens))
            .ok_or(VersionError::VersionFormatMismatch {
                version_string: version_str.to_owned(),
                format_string: format.to_string(),
            })
    }

    fn parse_rec(
        version_str: &'vs [u8],
        fmt_tokens: &[UnescapedFormatToken<S>],
        ver_tokens: &[VersionToken<'vs, S>],
    ) -> Option<Vec<VersionToken<'vs, S>>> {
        if version_str.is_empty() && fmt_tokens.is_empty() {
            return Some(ver_tokens.to_vec());
        }

        let first_fmt_token = fmt_tokens.first()?;

        match first_fmt_token {
            UnescapedFormatToken::Literal(literal) => {
                if version_str.starts_with(literal.as_bytes()) {
                    let mut new_ver_tokens = ver_tokens.to_vec();
                    let (literal, version_str) = version_str.split_at(literal.len());
                    new_ver_tokens.push(VersionToken::Literal(literal));
                    Self::parse_rec(version_str, &fmt_tokens[1..], &new_ver_tokens)
                } else {
                    None
                }
            }
            UnescapedFormatToken::Specifier(specifier) => {
                let min_parse_width = specifier.parse_width().min_width();
                let max_parse_width = specifier.parse_width().max_width().min(version_str.len());
                let mut value: SpecValue = 0;
                let mut continue_iterating = true;

                for idx in 0..max_parse_width {
                    let next = version_str[idx];
                    if !next.is_ascii_digit() {
                        return None; // all specs only match digits, so this idx is unparseable
                    }
                    value = value * 10 + u32::from(next - b'0');

                    let cur_width = idx + 1;
                    if cur_width < min_parse_width {
                        // keep going until we have enough characters
                        continue;
                    }

                    if value == 0 {
                        if !specifier.can_be_zero() {
                            return None;
                        }
                        if !specifier.has_zero_padding() {
                            // if the value is zero, and this spec has no zero-padding, then the
                            // only way we could parse a leading zero is if the value is just that
                            // single '0'. so, do this iteration, but don't continue.
                            continue_iterating = false;
                        }
                    }

                    let mut new_ver_tokens = ver_tokens.to_vec();
                    new_ver_tokens.push(VersionToken::Value {
                        value,
                        spec: specifier,
                    });
                    if let Some(new_ver_tokens) =
                        Self::parse_rec(&version_str[idx + 1..], &fmt_tokens[1..], &new_ver_tokens)
                    {
                        return Some(new_ver_tokens);
                    }
                    if !continue_iterating {
                        break;
                    }
                }
                None
            }
        }
    }

    fn new_map_value_tokens<F>(&self, mut f: F) -> Result<Self, NextError>
    where
        F: FnMut((SpecValue, &S::Specifier)) -> SpecValueResult,
    {
        let mut new_tokens = Vec::with_capacity(self.tokens.len());

        for token in &self.tokens {
            let new_token = match token {
                VersionToken::Value { value, spec } => {
                    let new_value = f((*value, spec))?;
                    VersionToken::Value {
                        value: new_value,
                        spec: *spec,
                    }
                }
                VersionToken::Literal(_) => token.clone(),
            };
            new_tokens.push(new_token);
        }

        Ok(Version::new(new_tokens))
    }
}

impl<'vs, S: Scheme> PartialOrd for Version<'vs, S> {
    /// Compares two versions. This is only a partial ordering it is only meaningful to compare two
    /// versions when they come from the same format.
    ///
    /// Returns `None` when either of the following are true:
    ///
    /// - The number of *tokens* in the versions are different. Tokens are either literal text or
    ///   specifier values.
    /// - For two given tokens, they are not of the same type. E.g., one is a literal, one is a
    ///   value.
    /// - For two given literal tokens, the text is not the same.
    /// - For two given value tokens, they are not of the same specifier type. E.g., one is a
    ///  `<YYYY>` value, one is a `<YY>` value.
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        if self.tokens.len() == other.tokens.len() {
            self.tokens.partial_cmp(&other.tokens)
        } else {
            None
        }
    }
}

impl<'vs> Version<'vs, Sem> {
    /// Returns a new version where the value of specifier given by `level` is incremented, and all
    /// lesser semantic values are reset to zero. This is similar to how an
    /// [odometer](https://en.wikipedia.org/wiki/Odometer) works.
    ///
    /// # Example
    ///
    /// ```
    /// use nextver::prelude::*;;
    ///
    /// let cur = Sem::new_version("<MAJOR>.<MINOR>.<PATCH>", "1.2.3")?;
    /// let next = cur.next(SemLevel::Major)?;
    /// assert_eq!("2.0.0", &next.to_string());
    /// assert!(cur < next);
    ///
    /// let next_next = next.next(SemLevel::Patch)?;
    /// assert_eq!("2.0.1", &next_next.to_string());
    /// assert!(next < next_next);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a [`Result::Err`] of...
    ///
    /// - [`NextError::SemLevelNotInFormat`] if the specifier of `level` is not in format.
    pub fn next(&self, level: SemLevel) -> Result<Self, NextError> {
        let mut spec_found = false;
        let level_spec = level.as_ref().spec();

        let next_version = self.new_map_value_tokens(|(cur_value, this_spec)| {
            if level_spec == this_spec {
                spec_found = true;
            };
            let next_value = this_spec.next_value(cur_value, level);
            Ok(next_value)
        })?;

        if !spec_found {
            return Err(NextError::SemLevelNotInFormat {
                spec: level_spec.to_string(),
            });
        }

        Ok(next_version)
    }
}

/// Errors around dates, as used to update [`Cal`](crate::Cal) and [`CalSem`](crate::CalSem)
/// versions.
#[non_exhaustive]
#[derive(thiserror::Error, Debug, PartialEq)]
pub enum DateError {
    /// Arguments to [`Date::explicit`](crate::Date::explicit) do not represent a valid date.
    #[error("year ({year}), month ({month}), and day ({day}) should represent a valid date")]
    InvalidDateArguments {
        /// The year value
        year: i32,
        /// The month value
        month: u32,
        /// The day value
        day: u32,
    },

    /// The date string could not be parsed.
    ///
    /// See [`chrono::NaiveDate::from_str`] and [`chrono::ParseError`].
    #[error(transparent)]
    UnparseableDate(#[from] chrono::ParseError),
}

/// Ways to specify a date.
///
/// ```
/// use nextver::Date;
///
/// let utc_now = Date::utc_now();
/// let local_now = Date::local_now();
/// let explicit = Date::explicit(2021, 2, 3).unwrap();
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Date(NaiveDate);

impl Date {
    /// Returns a new [`Date`] representing the current date in UTC at the time of this call.
    #[must_use]
    pub fn utc_now() -> Self {
        Self(Utc::now().date_naive())
    }

    /// Returns a new [`Date`] representing the current date in the system's local timezone at the
    /// time of this call.
    #[must_use]
    pub fn local_now() -> Self {
        Self(Local::now().date_naive())
    }

    /// Returns result of a new [`Date`] representing the given Date.
    ///
    /// # Errors
    ///
    /// Returns [`DateError::InvalidDateArguments`] if the date values do not represent a valid
    /// date.
    pub fn explicit(year: i32, month: u32, day: u32) -> Result<Self, DateError> {
        NaiveDate::from_ymd_opt(year, month, day)
            .map(Self)
            .ok_or(DateError::InvalidDateArguments { year, month, day })
    }

    pub(crate) fn as_naive_date(self) -> NaiveDate {
        self.0
    }
}

impl FromStr for Date {
    type Err = DateError;

    /// Parses a date string into a [`Date`]. The string must be in the format `YYYY-MM-DD`, where
    /// `YYYY` is the year zero-padded to 4 digits, `MM` is the month zero-padded to 2 digits, and
    /// `DD` is the day zero-padded to 2 digits.
    ///
    /// See [`NaiveDate::from_str`].
    ///
    /// # Errors
    ///
    /// Returns a [`DateError::UnparseableDate`] if the date string is not parseable.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(NaiveDate::from_str(s)?))
    }
}

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

impl<'vs> Version<'vs, Cal> {
    /// Returns a new version where the values of all date specifiers is advanced to those in
    /// `date`.
    ///
    /// If `date` is before the date in this version, an error is returned. (See
    /// [`Self::next_unchecked`] to skip this check.)
    ///
    /// # Example
    ///
    /// ```
    /// use nextver::prelude::*;;
    ///
    /// let date = Date::utc_now();  // assume today is 2024-02-23
    /// # let date = Date::explicit(2024, 2, 23)?;
    ///
    /// let cur = Cal::new_version("<YYYY>.<MM>", "2024.1")?;
    /// let next = cur.next(date)?;
    /// assert_eq!("2024.2", &next.to_string());
    /// assert!(cur < next);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a [`Result::Err`] of...
    ///
    /// - [`NextError::NoCalendarChange`] if the date does not change the calendar values.
    /// - [`NextError::NewDateIsBefore`] if `date` is before the date in this version.
    /// - [`NextError::NegativeYearValue`] if the year value would be negative. (Year specifiers
    ///   have lower bounds. See the [table](crate#table) for more information.)
    pub fn next(&self, date: Date) -> Result<Self, NextError> {
        // track if the calendar was moved forward in time, so we can error if not
        let mut cal_moved_fwd = false;

        let next_version = self.new_map_value_tokens(|(cur_value, this_spec)| {
            let next_value = this_spec.next_value(date.as_naive_date())?;

            if !cal_moved_fwd {
                match next_value.cmp(&cur_value) {
                    Ordering::Greater => cal_moved_fwd = true,
                    Ordering::Less => {
                        return Err(NextError::NewDateIsBefore);
                    }
                    Ordering::Equal => {}
                }
            }

            Ok(next_value)
        })?;

        if !cal_moved_fwd {
            return Err(NextError::NoCalendarChange);
        }

        Ok(next_version)
    }

    /// Same as [`next`](struct.Version.html#method.next-1), but without checking if `date` is after
    /// the date in this version.
    ///
    /// # Errors
    ///
    /// Same as [`next`](struct.Version.html#method.next-1), but without
    /// [`NextError::NewDateIsBefore`].
    pub fn next_unchecked(&self, date: Date) -> Result<Self, NextError> {
        let new_version =
            self.new_map_value_tokens(|(_, this_spec)| this_spec.next_value(date.as_naive_date()))?;
        Ok(new_version)
    }
}

impl<'vs> Version<'vs, CalSem> {
    fn next_base(
        &self,
        date: Date,
        level: CalSemLevel,
        err_on_date_before: bool,
    ) -> Result<Self, NextError> {
        // track if the semantic level was found in the format string.
        let mut sem_spec_found = false;
        let level_spec = level.spec();

        // track if the calendar was updated, so we know if we need to do semantic updates
        let mut cal_moved_fwd = false;

        let next_version = self.new_map_value_tokens(|(cur_value, this_spec)| {
            let next_value = match this_spec {
                CalSemSpecifier::Cal(cal_spec) => {
                    let new_value = cal_spec.next_value(date.as_naive_date())?;
                    if !cal_moved_fwd {
                        match new_value.cmp(&cur_value) {
                            Ordering::Greater => cal_moved_fwd = true,
                            Ordering::Less if err_on_date_before => {
                                return Err(NextError::NewDateIsBefore);
                            }
                            _ => {}
                        }
                    }
                    new_value
                }
                CalSemSpecifier::Sem(sem_spec) => {
                    if level_spec == this_spec {
                        sem_spec_found = true;
                    }
                    if cal_moved_fwd {
                        0
                    } else {
                        sem_spec.next_value(cur_value, level)
                    }
                }
            };

            Ok(next_value)
        })?;

        if !sem_spec_found {
            return Err(NextError::SemLevelNotInFormat {
                spec: level_spec.to_string(),
            });
        }

        Ok(next_version)
    }

    /// Returns a new version where the following are done in order:
    ///
    /// 1. The values of all calendar specifiers are changed to those in `date`.
    /// 2. A check is performed to see if the date has advanced. Then, one of the following is
    ///    performed:
    ///    - (*date-is-different*) Iff the date has advanced, all semantic values are reset to zero.
    ///    - (*date-is-same*) Otherwise, the value of semantic specifier given by `level` is
    ///      incremented, and all lesser semantic values are reset to zero. This is similar to how
    ///      an [odometer](https://en.wikipedia.org/wiki/Odometer) works.
    ///
    /// If `date` is before the date in this version, an error is returned. (See
    /// [`next_unchecked`](struct.Version.html#method.next_unchecked-1) to skip this check.)
    ///
    /// # Example
    ///
    /// In the *date-is-different* case:
    ///
    /// ```
    /// use nextver::prelude::*;;
    ///
    /// let date = Date::utc_now();  // assume today is 2024-02-23
    /// # let date = Date::explicit(2024, 2, 23)?;
    ///
    /// let cur = CalSem::new_version("<YYYY>.<MM>.<PATCH>", "2024.1.123")?;
    /// let next = cur.next(date, CalSemLevel::Patch)?;
    /// assert_eq!("2024.2.0", &next.to_string());
    /// assert!(cur < next);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// In the *date-is-same* case:
    ///
    /// ```
    /// use nextver::prelude::*;;
    ///
    /// let date = Date::utc_now();  // assume today is 2024-02-23
    /// # let date = Date::explicit(2024, 2, 23)?;
    ///
    /// let cur = CalSem::new_version("<YYYY>.<MM>.<PATCH>", "2024.2.123")?;
    /// let next = cur.next(date, CalSemLevel::Patch)?;
    /// assert_eq!("2024.2.124", &next.to_string());
    /// assert!(cur < next);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a [`Result::Err`] of...
    ///
    /// - [`NextError::NoCalendarChange`] if the date does not change the calendar values.
    /// - [`NextError::NewDateIsBefore`] if `date` is before the date in this version.
    /// - [`NextError::NegativeYearValue`] if the year value would be negative. (Year specifiers
    ///   have lower bounds. See the [table](crate#table) for more information.)
    /// - [`NextError::SemLevelNotInFormat`] if the specifier of `level` is not in format.
    pub fn next(&self, date: Date, level: CalSemLevel) -> Result<Self, NextError> {
        self.next_base(date, level, true)
    }

    /// Same as [`next`](struct.Version.html#method.next-2), but without checking if `date` is after
    /// the date in this version.
    ///
    /// # Errors
    ///
    /// Same as [`next`](struct.Version.html#method.next-2), but without
    /// [`NextError::NewDateIsBefore`].
    pub fn next_unchecked(&self, date: Date, level: CalSemLevel) -> Result<Self, NextError> {
        self.next_base(date, level, false)
    }
}

impl<'vs, S: Scheme> Display for Version<'vs, S> {
    /// Returns the rendered version string
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for token in &self.tokens {
            write!(f, "{token}")?;
        }

        Ok(())
    }
}

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

    #[test]
    fn test_major_minor_patch_parse() {
        let version_strs = [
            ("01.2.3", false), // zero-padding disallowed
            ("1.02.3", false), // zero-padding disallowed
            ("1.2.03", false), // zero-padding disallowed
            ("1.2.3", true),
            ("10.20.30", true),
            ("11.22.33", true),
        ];

        for (version_str, passes) in &version_strs {
            let format = Sem::new_format("<MAJOR>.<MINOR>.<PATCH>").unwrap();
            let version = Version::parse(version_str, &format);
            if *passes {
                assert!(version.is_ok());
            } else {
                assert!(matches!(
                    version,
                    Err(VersionError::VersionFormatMismatch { .. })
                ));
            }
        }
    }

    /// test full year
    #[test]
    fn test_full_year_parse() {
        let format_str = "<YYYY>";
        let args = [
            ("01", false),  // zero-padding disallowed
            ("001", false), // zero-padding disallowed
            ("0", true),
            ("1", true),
            ("10", true),
            ("100", true),
        ];

        for (version_str, passes) in &args {
            let format = Cal::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format);
            if *passes {
                assert!(version.is_ok());
            } else {
                assert!(matches!(
                    version,
                    Err(VersionError::VersionFormatMismatch { .. })
                ));
            }
        }
    }

    /// test short year
    #[test]
    fn test_short_year_parse() {
        let format_str = "<YY>";
        let args = [
            ("01", false),  // zero-padding disallowed
            ("001", false), // zero-padding disallowed
            ("0", true),
            ("1", true),
            ("10", true),
            ("100", true),
        ];

        for (version_str, passes) in &args {
            let format = Cal::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format);
            if *passes {
                assert!(version.is_ok());
            } else {
                assert!(matches!(
                    version,
                    Err(VersionError::VersionFormatMismatch { .. })
                ));
            }
        }
    }

    /// test zero-padded year
    #[test]
    fn test_zp_year_parse() {
        let format_str = "<0Y>";
        let args = [
            ("0", false), // must be 2-digits
            ("1", false), // must be 2-digits
            ("00", true),
            ("01", true),
            ("10", true),
            ("100", true),
        ];

        for (version_str, passes) in &args {
            let format = Cal::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format);
            if *passes {
                assert!(version.is_ok());
            } else {
                assert!(matches!(
                    version,
                    Err(VersionError::VersionFormatMismatch { .. })
                ));
            }
        }
    }

    // test zero-padded week
    #[test]
    fn test_zp_week_parse() {
        let args = [
            ("<YYYY>.<0W>", "2024.0", false),   // must be two-digit
            ("<YYYY>.<0W>", "2024.122", false), // must be two-digit
            ("<YYYY>.<0W>", "2024.00", true),   // there is a week zero
            ("<YYYY>.<0W>", "2024.01", true),
            ("<YYYY>.<0W>", "2024.10", true),
            ("<YYYY>.<0W>", "2024.12", true),
        ];

        for (format_str, version_str, passes) in &args {
            let format = Cal::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format);
            if *passes {
                assert!(version.is_ok());
            } else {
                assert!(matches!(
                    version,
                    Err(VersionError::VersionFormatMismatch { .. })
                ));
            }
        }
    }

    // test short week
    #[test]
    fn test_short_week_parse() {
        let args = [
            ("<YYYY>.<WW>", "2024.01", false),  // zero-padding disallowed
            ("<YYYY>.<WW>", "2024.00", false),  // zero-padding disallowed
            ("<YYYY>.<WW>", "2024.122", false), // must be two-digit
            ("<YYYY>.<WW>", "2024.0", true),
            ("<YYYY>.<WW>", "2024.10", true),
            ("<YYYY>.<WW>", "2024.12", true),
        ];

        for (format_str, version_str, passes) in &args {
            let format = Cal::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format);
            if *passes {
                assert!(version.is_ok());
            } else {
                assert!(matches!(
                    version,
                    Err(VersionError::VersionFormatMismatch { .. })
                ));
            }
        }
    }

    /// test zero-padded month and day (same characteristics: no month/day 0, 2 digits).
    #[test]
    fn test_zp_month_day_parse() {
        let args = [
            // month
            ("<YYYY>.<0M>", "2024.0", false),   // must be two-digit
            ("<YYYY>.<0M>", "2024.00", false),  // no month 0
            ("<YYYY>.<0M>", "2024.122", false), // must be two-digit
            ("<YYYY>.<0M>", "2024.01", true),
            ("<YYYY>.<0M>", "2024.10", true),
            ("<YYYY>.<0M>", "2024.12", true),
            // day
            ("<YYYY>.<MM>.<0D>", "2024.1.0", false), // must be two-digit
            ("<YYYY>.<MM>.<0D>", "2024.1.00", false), // no day 0
            ("<YYYY>.<MM>.<0D>", "2024.1.122", false), // must be two-digit
            ("<YYYY>.<MM>.<0D>", "2024.1.01", true),
            ("<YYYY>.<MM>.<0D>", "2024.1.10", true),
            ("<YYYY>.<MM>.<0D>", "2024.1.12", true),
        ];

        for (format_str, version_str, passes) in &args {
            let format = Cal::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format);
            if *passes {
                assert!(version.is_ok());
            } else {
                assert!(matches!(
                    version,
                    Err(VersionError::VersionFormatMismatch { .. })
                ));
            }
        }
    }

    /// test short month, day, and week. (same characteristics: no month/day 0, 1-2 digits).
    #[test]
    fn test_short_mdw_parse() {
        let args = [
            // month
            ("<YYYY>.<MM>", "2024.0", false),   // no month 0
            ("<YYYY>.<MM>", "2024.00", false),  // zero-padding disallowed
            ("<YYYY>.<MM>", "2024.01", false),  // zero-padding disallowed
            ("<YYYY>.<MM>", "2024.122", false), // must be two-digit
            ("<YYYY>.<MM>", "2024.1", true),
            ("<YYYY>.<MM>", "2024.10", true),
            ("<YYYY>.<MM>", "2024.12", true),
            // day
            ("<YYYY>.<MM>.<DD>", "2024.1.0", false), // no month 0
            ("<YYYY>.<MM>.<DD>", "2024.1.00", false), // zero-padding disallowed
            ("<YYYY>.<MM>.<DD>", "2024.1.01", false), // zero-padding disallowed
            ("<YYYY>.<MM>.<DD>", "2024.1.122", false), // must be two-digit
            ("<YYYY>.<MM>.<DD>", "2024.1.1", true),
            ("<YYYY>.<MM>.<DD>", "2024.1.10", true),
            ("<YYYY>.<MM>.<DD>", "2024.1.12", true),
        ];

        for (format_str, version_str, passes) in &args {
            let format = Cal::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format);
            if *passes {
                assert!(version.is_ok());
            } else {
                assert!(matches!(
                    version,
                    Err(VersionError::VersionFormatMismatch { .. })
                ));
            }
        }
    }

    #[test]
    fn test_unicode_literal() {
        let format_str = "👍<MAJOR>👯‍♀️";
        let version_str = "👍1👯‍♀️";
        let format = Sem::new_format(format_str).unwrap();
        let version = Version::parse(version_str, &format);
        assert!(version.is_ok());
    }

    #[test]
    fn test_date_from_str() {
        let date_strs = [
            ("2021-02-03", true),
            ("2021-2-3", true),
            ("2021-02-30", false), // February 30th doesn't exist
        ];

        for (date_str, passes) in &date_strs {
            let date = Date::from_str(date_str);
            if *passes {
                assert!(date.is_ok());
            } else {
                assert!(matches!(date, Err(DateError::UnparseableDate { .. })));
            }
        }
    }

    #[test]
    fn test_date_explicit() {
        let date_strs = [
            (2021i32, 2u32, 3u32, true),
            (2021i32, 2u32, 30u32, false), // February 30th doesn't exist
        ];

        for (year, month, day, passes) in date_strs {
            let date = Date::explicit(year, month, day);
            if passes {
                assert!(date.is_ok());
            } else {
                assert!(matches!(date, Err(DateError::InvalidDateArguments { .. })));
            }
        }
    }

    #[test]
    fn test_sem_next() {
        let args = [
            ("<MAJOR>.<MINOR>.<PATCH>", "1.2.3", SemLevel::Major, "2.0.0"),
            ("<MAJOR>.<MINOR>.<PATCH>", "1.2.3", SemLevel::Minor, "1.3.0"),
            ("<MAJOR>.<MINOR>.<PATCH>", "1.2.3", SemLevel::Patch, "1.2.4"),
            ("<MAJOR>.<MINOR>", "1.2", SemLevel::Major, "2.0"),
            ("<MAJOR>.<MINOR>", "1.2", SemLevel::Minor, "1.3"),
            ("<MAJOR>", "1", SemLevel::Major, "2"),
        ];

        for (format_str, version_str, level, expected_str) in args {
            let format = Sem::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format).unwrap();
            let next = version.next(level).unwrap();
            assert_eq!(expected_str, next.to_string());
        }
    }

    #[test]
    fn test_cal_next() {
        let args = [
            (
                "<YYYY>.<0M>.<0D>",
                "2023.12.04",
                Date::explicit(2024, 1, 1),
                "2024.01.01",
            ),
            ("<YYYY>", "2023", Date::explicit(2024, 1, 1), "2024"),
            (
                "<YYYY>.<0W>",
                "2023.01",
                Date::explicit(2024, 1, 1),
                "2024.00",
            ),
            (
                "<YYYY>.<WW>",
                "2023.1",
                Date::explicit(2024, 1, 1),
                "2024.0",
            ),
        ];

        for (format_str, version_str, date, expected_str) in args {
            let format = Cal::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format).unwrap();
            let next = version.next(date.unwrap()).unwrap();
            assert_eq!(expected_str, next.to_string());
        }
    }

    #[test]
    fn test_calsem_next() {
        let args = [
            (
                "<YYYY>.<0M>.<0D>.<PATCH>",
                "2023.12.04.123",
                Date::explicit(2024, 1, 1),
                CalSemLevel::Patch,
                "2024.01.01.0",
            ),
            (
                "<YYYY>.<0M>.<0D>.<PATCH>",
                "2023.12.04.123",
                Date::explicit(2023, 12, 4),
                CalSemLevel::Patch,
                "2023.12.04.124",
            ),
            (
                "<YYYY>.<0M>.<DD>.<MINOR>.<PATCH>",
                "2023.12.4.5.123",
                Date::explicit(2024, 1, 1),
                CalSemLevel::Minor,
                "2024.01.1.0.0",
            ),
            (
                "<YYYY>.<0M>.<DD>.<MINOR>.<PATCH>",
                "2023.12.4.5.123",
                Date::explicit(2023, 12, 4),
                CalSemLevel::Minor,
                "2023.12.4.6.0",
            ),
            (
                "<YYYY>.<0M>.<DD>.<MINOR>.<PATCH>",
                "2023.12.4.5.123",
                Date::explicit(2023, 12, 4),
                CalSemLevel::Patch,
                "2023.12.4.5.124",
            ),
        ];

        for (format_str, version_str, date, level, expected_str) in args {
            let format = CalSem::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format).unwrap();
            let next = version.next(date.unwrap(), level).unwrap();
            assert_eq!(next.to_string(), expected_str);
        }
    }

    #[test]
    fn test_sem_not_in_format() {
        let args = [
            ("<MAJOR>.<MINOR>", "1.2", SemLevel::Patch),
            ("<MAJOR>", "1", SemLevel::Minor),
            ("<MAJOR>", "1", SemLevel::Patch),
        ];

        for (format_str, version_str, level) in args {
            let format = Sem::new_format(format_str).unwrap();
            let version = Version::parse(version_str, &format).unwrap();
            let next = version.next(level);
            assert!(matches!(next, Err(NextError::SemLevelNotInFormat { .. })));
        }
    }

    #[test]
    fn test_calsem_not_in_format() {
        let format = CalSem::new_format("<YYYY>.<0M>.<0D>.<PATCH>").unwrap();
        let version = Version::parse("2023.12.04.2", &format).unwrap();
        let next = version.next(Date::explicit(2024, 1, 1).unwrap(), CalSemLevel::Minor);
        assert!(matches!(next, Err(NextError::SemLevelNotInFormat { .. })));
    }

    #[test]
    fn test_cal_no_cal_change() {
        let format = Cal::new_format("<YYYY>.<0M>.<0D>").unwrap();
        let version = Version::parse("2023.12.04", &format).unwrap();
        let next = version.next(Date::explicit(2023, 12, 4).unwrap());
        assert!(matches!(next, Err(NextError::NoCalendarChange)));
    }

    #[test]
    fn test_cal_neg_year_full_year() {
        let format = Cal::new_format("<YYYY>").unwrap();
        let version = Version::parse("2023", &format).unwrap();
        let next = version.next(Date::explicit(-1, 1, 1).unwrap());
        assert!(matches!(next, Err(NextError::NegativeYearValue { .. })));
    }

    #[test]
    fn test_calsem_neg_year_full_year() {
        let format = CalSem::new_format("<YYYY>.<PATCH>").unwrap();
        let version = Version::parse("2023.1", &format).unwrap();
        let next = version.next(Date::explicit(-1, 1, 1).unwrap(), CalSemLevel::Patch);
        assert!(matches!(next, Err(NextError::NegativeYearValue { .. })));
    }

    #[test]
    fn test_cal_neg_year_short_year() {
        let format = Cal::new_format("<YY>").unwrap();
        let version = Version::parse("2023", &format).unwrap();
        let next = version.next(Date::explicit(1999, 1, 1).unwrap());
        assert!(matches!(next, Err(NextError::NegativeYearValue { .. })));
    }

    #[test]
    fn test_cal_neg_year_zp_year() {
        let format = Cal::new_format("<0Y>").unwrap();
        let version = Version::parse("23", &format).unwrap();
        let next = version.next(Date::explicit(1999, 1, 1).unwrap());
        assert!(matches!(next, Err(NextError::NegativeYearValue { .. })));
    }

    #[test]
    fn test_calsem_neg_year_short_year() {
        let format = CalSem::new_format("<YY>.<PATCH>").unwrap();
        let version = Version::parse("2023.1", &format).unwrap();
        let next = version.next(Date::explicit(1999, 1, 1).unwrap(), CalSemLevel::Patch);
        assert!(matches!(next, Err(NextError::NegativeYearValue { .. })));
    }

    #[test]
    fn test_calsem_neg_year_zp_year() {
        let format = CalSem::new_format("<0Y>.<PATCH>").unwrap();
        let version = Version::parse("23.1", &format).unwrap();
        let next = version.next(Date::explicit(1999, 1, 1).unwrap(), CalSemLevel::Patch);
        assert!(matches!(next, Err(NextError::NegativeYearValue { .. })));
    }

    #[test]
    fn test_sem_incomparable() {
        let format1 = Sem::new_format("<MAJOR>.<MINOR>").unwrap();
        let format2 = Sem::new_format("<MAJOR>.<MINOR>.<PATCH>").unwrap();
        let version1 = Version::parse("1.2", &format1).unwrap();
        let version2 = Version::parse("1.2.3", &format2).unwrap();
        let cmp = version1.partial_cmp(&version2);
        assert!(cmp.is_none());
    }

    #[test]
    fn test_sem_next_greater() {
        let format = Sem::new_format("<MAJOR>.<MINOR>.<PATCH>").unwrap();
        let cur = Version::parse("1.2.3", &format).unwrap();

        for level in [SemLevel::Major, SemLevel::Minor, SemLevel::Patch] {
            let next = cur.next(level).unwrap();
            assert!(cur < next);
        }
    }

    #[test]
    fn test_cal_next_greater() {
        let format = Cal::new_format("<YYYY>.<0M>.<0D>").unwrap();
        let cur = Version::parse("2023.12.04", &format).unwrap();
        let next = cur.next(Date::explicit(2024, 1, 1).unwrap()).unwrap();
        assert!(cur < next);
    }

    #[test]
    fn test_cal_next_not_greater() {
        let format = Cal::new_format("<YYYY>.<0M>.<0D>").unwrap();
        let cur = Version::parse("2023.12.04", &format).unwrap();
        let next = cur.next(Date::explicit(2022, 1, 1).unwrap());
        assert_eq!(next, Err(NextError::NewDateIsBefore));
    }

    #[test]
    fn test_cal_next_unchecked() {
        let format = Cal::new_format("<YYYY>.<0M>.<0D>").unwrap();
        let cur = Version::parse("2023.12.04", &format).unwrap();
        let next = cur
            .next_unchecked(Date::explicit(2022, 1, 1).unwrap())
            .unwrap();
        assert_eq!("2022.01.01", next.to_string());
    }

    #[test]
    fn test_calsem_next_greater() {
        let format = CalSem::new_format("<YYYY>.<0M>.<0D>.<PATCH>").unwrap();
        let cur = Version::parse("2023.12.04.123", &format).unwrap();

        let args = [
            (Date::explicit(2024, 1, 1), CalSemLevel::Patch), // date parts change
            (Date::explicit(2023, 12, 4), CalSemLevel::Patch), // semantic part changes
        ];

        for (date, level) in args {
            let next = cur.next(date.unwrap(), level).unwrap();
            assert!(cur < next);
        }
    }

    #[test]
    fn test_calsem_next_not_greater() {
        let format = CalSem::new_format("<YYYY>.<0M>.<0D>.<PATCH>").unwrap();
        let cur = Version::parse("2023.12.04.123", &format).unwrap();
        let next = cur.next(Date::explicit(2022, 1, 1).unwrap(), CalSemLevel::Patch);
        assert_eq!(next, Err(NextError::NewDateIsBefore));
    }

    #[test]
    fn test_calsem_next_unchecked() {
        let format = CalSem::new_format("<YYYY>.<0M>.<0D>.<PATCH>").unwrap();
        let cur = Version::parse("2023.12.04.123", &format).unwrap();
        let next = cur
            .next_unchecked(Date::explicit(2022, 1, 1).unwrap(), CalSemLevel::Patch)
            .unwrap();
        assert_eq!("2022.01.01.124", next.to_string());
    }

    #[test]
    fn test_non_greedy_parse() {
        let format_str = "<MAJOR><MINOR><PATCH>";
        let major = 111;
        let minor = 222;
        let patch = 333;
        let version_str = format!("{major}{minor}{patch}");

        // nextver is going to interpret: major=1, minor=1, patch=1222333, despite our intentions
        let next_str = Sem::next_version_string(format_str, &version_str, SemLevel::Minor).unwrap();

        // thus, the next version is: major=1, minor=2, patch=0
        assert_eq!("120", next_str);
    }
}