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
#![doc = include_str!("../README.md")]

#[cfg(feature = "serde")]
mod serde;
#[cfg(test)]
mod tests;
mod util;

use std::{
    cmp::Ordering,
    error::Error,
    fmt::{self, Debug, Display},
    str::FromStr,
};

use util::SplitPrefix;

/// The characters that are hard delimiters for components.
/// This constant is public more as a matter of documentation than of utility.
pub const COMPONENT_SEPARATORS: &str = ".-+";

/// A component is a indivisible part of a version.
/// May be a number, or a alphabetic identifier.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Component {
    Identifier(Box<str>),
    Number(u16),
}

/// The default Component is the number zero.
impl Default for Component {
    fn default() -> Self {
        Self::Number(0)
    }
}

impl Display for Component {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Component::Number(number) => write!(f, "{}", number),
            Component::Identifier(id) => f.write_str(id),
        }
    }
}

impl Debug for Component {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(self, f)
    }
}

/// A parser for components.
/// This is an iterator which will parse many components in succession.
#[derive(Debug)]
struct ComponentParser<'a> {
    /// Flag to indicate whether we're parsing the first component.
    first: bool,
    /// The input yet to be parsed.
    input: &'a str,
}

impl<'a> From<&'a str> for ComponentParser<'a> {
    fn from(input: &'a str) -> Self {
        Self { first: true, input }
    }
}

impl<'a> Iterator for ComponentParser<'a> {
    type Item = Result<Component, ParseVersionError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.input.is_empty() {
            return None;
        }

        if self.first {
            self.first = false;
        } else if let Some(tail) = self // Only allow separators after the first component.
            .input
            .strip_prefix(|c| COMPONENT_SEPARATORS.contains(c))
        {
            self.input = tail;
        }
        // Some versions have the format "7.4.1 (4452929)", so we must be able to
        // parse the trailing parenthesized component.
        else if let Some(tail) = self.input.strip_prefix(" (") {
            self.input = tail;

            if self.parse_integer::<u32>().is_none() && self.parse_identifier().is_none() {
                return Some(Err(self.error()));
            }

            if let Some(tail) = self.input.strip_prefix(')') {
                self.input = tail;
            } else {
                return Some(Err(self.error()));
            }

            return if self.input.is_empty() {
                None
            } else {
                Some(Err(self.error()))
            };
        }

        // Try to parse a number.
        if let Some(component) = self.parse_number() {
            return Some(Ok(component));
        }

        // Try to parse an identifier.
        if let Some(component) = self.parse_identifier() {
            return Some(Ok(component));
        }

        Some(Err(self.error()))
    }
}

impl<'a> ComponentParser<'a> {
    /// Try to parse an integer of the given type.
    fn parse_integer<N: FromStr>(&mut self) -> Option<N> {
        if let Some((integer, tail)) = self.input.split_prefix(|c| c.is_ascii_digit()) {
            if let Ok(integer) = integer.parse() {
                self.input = tail;
                return Some(integer);
            }
        }

        None
    }

    /// Try to parse a number component.
    fn parse_number(&mut self) -> Option<Component> {
        self.parse_integer().map(Component::Number)
    }

    /// Try to parse an identifier component.
    fn parse_identifier(&mut self) -> Option<Component> {
        if let Some((identifier, tail)) = self.input.split_prefix(|c| c.is_ascii_alphabetic()) {
            self.input = tail;
            return Some(Component::Identifier(identifier.into()));
        }

        None
    }

    /// Generate a error with the current input.
    fn error(&self) -> ParseVersionError {
        ParseVersionError(self.input.to_owned())
    }
}

/// An error while parsing a version.
#[derive(Debug, Clone)]
pub struct ParseVersionError(String);

impl Display for ParseVersionError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid version: {}", self.0)
    }
}

impl Error for ParseVersionError {}

/// A version. Versions are composed of one or more components, and provide a total
/// ordering.
#[derive(Clone)]
pub struct Version(Box<[Component]>);

impl PartialEq for Version {
    fn eq(&self, other: &Self) -> bool {
        let mut self_iter = self.0.iter().fuse();
        let mut other_iter = other.0.iter().fuse();

        loop {
            match (self_iter.next(), other_iter.next()) {
                (None, None) => return true,

                (None, Some(Component::Number(0))) => continue,
                (Some(Component::Number(0)), None) => continue,

                (None, Some(_)) => return false,
                (Some(_), None) => return false,

                (Some(c1), Some(c2)) if c1 == c2 => continue,
                (Some(_), Some(_)) => return false,
            }
        }
    }
}

impl Eq for Version {}

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

impl Ord for Version {
    fn cmp(&self, other: &Self) -> Ordering {
        let mut self_iter = self.0.iter().fuse();
        let mut other_iter = other.0.iter().fuse();

        loop {
            match (self_iter.next(), other_iter.next()) {
                (None, None) => return Ordering::Equal,

                (None, Some(Component::Number(0))) => continue,
                (Some(Component::Number(0)), None) => continue,

                (None, Some(Component::Number(_))) => return Ordering::Less,
                (Some(Component::Number(_)), None) => return Ordering::Greater,

                (None, Some(Component::Identifier(_))) => return Ordering::Greater,
                (Some(Component::Identifier(_)), None) => return Ordering::Less,

                (Some(c1), Some(c2)) if c1.cmp(c2) == Ordering::Equal => continue,
                (Some(c1), Some(c2)) => return c1.cmp(c2),
            }
        }
    }
}

/// The default version is `0.0.0`.
impl Default for Version {
    fn default() -> Self {
        Self(vec![Component::default(); 3].into_boxed_slice())
    }
}

impl FromStr for Version {
    type Err = ParseVersionError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        ComponentParser::from(input)
            .collect::<Result<_, _>>()
            .map(Self)
    }
}

impl Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut iterator = self.0.iter();

        if let Some(first) = iterator.next() {
            write!(f, "{}", first)?;
        }

        for component in iterator {
            write!(f, ".{}", component)?;
        }

        Ok(())
    }
}

impl Debug for Version {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(self, f)
    }
}