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
// SPDX-License-Identifier: MPL-2.0

//! Traits and implementations to create and compare versions.

use std::fmt::{self, Debug, Display};
use std::str::FromStr;
use thiserror::Error;

/// Type for semantic versions: major.minor.patch.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct SemanticVersion {
    major: u32,
    minor: u32,
    patch: u32,
}

#[cfg(feature = "serde")]
impl serde::Serialize for SemanticVersion {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!("{}", self))
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for SemanticVersion {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        FromStr::from_str(&s).map_err(serde::de::Error::custom)
    }
}

// Constructors
impl SemanticVersion {
    /// Create a version with "major", "minor" and "patch" values.
    /// `version = major.minor.patch`
    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    /// Version 0.0.0.
    pub fn zero() -> Self {
        Self::new(0, 0, 0)
    }

    /// Version 1.0.0.
    pub fn one() -> Self {
        Self::new(1, 0, 0)
    }

    /// Version 2.0.0.
    pub fn two() -> Self {
        Self::new(2, 0, 0)
    }
}

// Convert a tuple (major, minor, patch) into a version.
impl From<(u32, u32, u32)> for SemanticVersion {
    fn from(tuple: (u32, u32, u32)) -> Self {
        let (major, minor, patch) = tuple;
        Self::new(major, minor, patch)
    }
}

// Convert a &(major, minor, patch) into a version.
impl From<&(u32, u32, u32)> for SemanticVersion {
    fn from(tuple: &(u32, u32, u32)) -> Self {
        let (major, minor, patch) = *tuple;
        Self::new(major, minor, patch)
    }
}

// Convert an &version into a version.
impl From<&SemanticVersion> for SemanticVersion {
    fn from(v: &SemanticVersion) -> Self {
        *v
    }
}

// Convert a version into a tuple (major, minor, patch).
impl From<SemanticVersion> for (u32, u32, u32) {
    fn from(v: SemanticVersion) -> Self {
        (v.major, v.minor, v.patch)
    }
}

// Bump versions.
impl SemanticVersion {
    /// Bump the patch number of a version.
    pub fn bump_patch(self) -> Self {
        Self::new(self.major, self.minor, self.patch + 1)
    }

    /// Bump the minor number of a version.
    pub fn bump_minor(self) -> Self {
        Self::new(self.major, self.minor + 1, 0)
    }

    /// Bump the major number of a version.
    pub fn bump_major(self) -> Self {
        Self::new(self.major + 1, 0, 0)
    }
}

/// Error creating [SemanticVersion] from [String].
#[derive(Error, Debug, PartialEq, Eq)]
pub enum VersionParseError {
    /// [SemanticVersion] must contain major, minor, patch versions.
    #[error("version {full_version} must contain 3 numbers separated by dot")]
    NotThreeParts {
        /// [SemanticVersion] that was being parsed.
        full_version: String,
    },
    /// Wrapper around [ParseIntError](core::num::ParseIntError).
    #[error("cannot parse '{version_part}' in '{full_version}' as u32: {parse_error}")]
    ParseIntError {
        /// [SemanticVersion] that was being parsed.
        full_version: String,
        /// A version part where parsing failed.
        version_part: String,
        /// A specific error resulted from parsing a part of the version as [u32].
        parse_error: String,
    },
}

impl FromStr for SemanticVersion {
    type Err = VersionParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parse_u32 = |part: &str| {
            part.parse::<u32>().map_err(|e| Self::Err::ParseIntError {
                full_version: s.to_string(),
                version_part: part.to_string(),
                parse_error: e.to_string(),
            })
        };

        let mut parts = s.split('.');
        match (parts.next(), parts.next(), parts.next(), parts.next()) {
            (Some(major), Some(minor), Some(patch), None) => {
                let major = parse_u32(major)?;
                let minor = parse_u32(minor)?;
                let patch = parse_u32(patch)?;
                Ok(Self {
                    major,
                    minor,
                    patch,
                })
            }
            _ => Err(Self::Err::NotThreeParts {
                full_version: s.to_string(),
            }),
        }
    }
}

#[test]
fn from_str_for_semantic_version() {
    let parse = |str: &str| str.parse::<SemanticVersion>();
    assert!(parse(
        &SemanticVersion {
            major: 0,
            minor: 1,
            patch: 0
        }
        .to_string()
    )
    .is_ok());
    assert!(parse("1.2.3").is_ok());
    assert_eq!(
        parse("1.abc.3"),
        Err(VersionParseError::ParseIntError {
            full_version: "1.abc.3".to_owned(),
            version_part: "abc".to_owned(),
            parse_error: "invalid digit found in string".to_owned(),
        })
    );
    assert_eq!(
        parse("1.2.-3"),
        Err(VersionParseError::ParseIntError {
            full_version: "1.2.-3".to_owned(),
            version_part: "-3".to_owned(),
            parse_error: "invalid digit found in string".to_owned(),
        })
    );
    assert_eq!(
        parse("1.2.9876543210"),
        Err(VersionParseError::ParseIntError {
            full_version: "1.2.9876543210".to_owned(),
            version_part: "9876543210".to_owned(),
            parse_error: "number too large to fit in target type".to_owned(),
        })
    );
    assert_eq!(
        parse("1.2"),
        Err(VersionParseError::NotThreeParts {
            full_version: "1.2".to_owned(),
        })
    );
    assert_eq!(
        parse("1.2.3."),
        Err(VersionParseError::NotThreeParts {
            full_version: "1.2.3.".to_owned(),
        })
    );
}

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