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
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;
use std::str::from_utf8_unchecked;

use parse::{ParseUintError, parse_uint, Parseable};


/// Rust release.
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Release {
    major: u16,
    minor: u16,
    patch: u16,
}
impl Release {
    /// Converts this `Release` into a version triple.
    pub fn triple(self) -> (u16, u16, u16) {
        (self.major, self.minor, self.patch)
    }

    /// Converts this `Release` into a version pair, discarding the patch number.
    pub fn pair(self) -> (u16, u16) {
        (self.major, self.minor)
    }

    /// The major version for this release.
    pub fn major(self) -> u16 {
        self.major
    }

    /// The minor version for this release.
    pub fn minor(self) -> u16 {
        self.major
    }

    /// The patch version for this release.
    pub fn patch(self) -> u16 {
        self.patch
    }

    /// Writes the release to a buffer.
    pub(crate) fn write_to(&self, buf: &mut [u8]) -> usize {
        let len = self.major.write_to(buf);
        buf[len] = b'.';
        let len = self.minor.write_to(&mut buf[len + 1..]) + len + 1;
        buf[len] = b'.';
        self.minor.write_to(&mut buf[len + 1..]) + len + 1
    }
}
impl<T: Into<u16>> From<(T, T, T)> for Release {
    fn from(triple: (T, T, T)) -> Release {
        let (major, minor, patch) = (triple.0.into(), triple.1.into(), triple.2.into());
        Release {
            major,
            minor,
            patch,
        }
    }
}
impl fmt::Debug for Release {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self, f)
    }
}
impl fmt::Display for Release {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buf = *b"65535.65535.65535";
        let len = self.write_to(&mut buf);
        f.pad(unsafe { from_utf8_unchecked(&buf[..len]) })
    }
}

impl<'a> TryFrom<&'a str> for Release {
    type Error = ParseReleaseError<'a>;
    fn try_from(s: &'a str) -> Result<Release, ParseReleaseError<'a>> {
        Release::try_from(s.as_bytes())
    }
}
impl<'a> TryFrom<&'a [u8]> for Release {
    type Error = ParseReleaseError<'a>;
    fn try_from(bytes: &'a [u8]) -> Result<Release, ParseReleaseError<'a>> {
        if let Some(idx) = bytes.iter().position(|b| *b == b'.') {
            let (major, rest) = bytes.split_at(idx);
            let rest = &rest[1..];
            if let Some(idx) = rest.iter().position(|b| *b == b'.') {
                let (minor, rest) = rest.split_at(idx);
                if rest[1..].contains(&b'.') {
                    return Err(ParseReleaseError::Format(bytes));
                }

                let patch = &rest[1..];
                let major = match parse_uint(major) {
                    Err(ParseUintError::Empty) => Err(ParseReleaseError::Format(bytes)),
                    Err(ParseUintError::BadByte(_)) => Err(ParseReleaseError::Number(major)),
                    Err(ParseUintError::Overflow) => Err(ParseReleaseError::Overflow(major)),
                    Ok(n) => Ok(n),
                }?;
                let minor = match parse_uint(minor) {
                    Err(ParseUintError::Empty) => Err(ParseReleaseError::Format(bytes)),
                    Err(ParseUintError::BadByte(_)) => Err(ParseReleaseError::Number(minor)),
                    Err(ParseUintError::Overflow) => Err(ParseReleaseError::Overflow(minor)),
                    Ok(n) => Ok(n),
                }?;
                let patch = match parse_uint(patch) {
                    Err(ParseUintError::Empty) => Err(ParseReleaseError::Format(bytes)),
                    Err(ParseUintError::BadByte(_)) => Err(ParseReleaseError::Number(patch)),
                    Err(ParseUintError::Overflow) => Err(ParseReleaseError::Overflow(patch)),
                    Ok(n) => Ok(n),
                }?;
                return Ok(Release {
                    major,
                    minor,
                    patch,
                });
            }
        }
        Err(ParseReleaseError::Format(bytes))
    }
}

/// Error encountered when parsing a [`Release`].
///
/// [`Release`]: struct.Release.html
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub enum ParseReleaseError<'a> {
    /// The string wasn't in the format `"major.minor.patch"`.
    Format(&'a [u8]),

    /// The given number was not valid.
    Number(&'a [u8]),

    /// The given number was too large fit in a `u16`.
    Overflow(&'a [u8]),
}
impl<'a> fmt::Debug for ParseReleaseError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ParseReleaseError::Format(bytes) => {
                f.debug_tuple("ParseReleaseError::Format")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
            ParseReleaseError::Number(bytes) => {
                f.debug_tuple("ParseReleaseError::Number")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
            ParseReleaseError::Overflow(bytes) => {
                f.debug_tuple("ParseReleaseError::Overflow")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
        }
    }
}
impl<'a> fmt::Display for ParseReleaseError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ParseReleaseError::Format(bytes) => {
                write!(
                    f,
                    "could not parse {:?} as \"major.minor.patch\"",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseReleaseError::Number(bytes) => {
                write!(
                    f,
                    "could not parse {:?} as a positive number",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseReleaseError::Overflow(bytes) => {
                write!(
                    f,
                    "could not parse {:?}; was greater than 65535",
                    String::from_utf8_lossy(bytes)
                )
            }
        }
    }
}
impl<'a> Error for ParseReleaseError<'a> {
    fn description(&self) -> &str {
        match *self {
            ParseReleaseError::Format(_) => "could not parse as \"major.minor.patch\"",
            ParseReleaseError::Number(_) => "could not parse part of release as a positive number",
            ParseReleaseError::Overflow(_) => {
                "could not parse part of release because the number was greater than 65535"
            }
        }
    }
}