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

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

/// Version for a Rust beta. This is either "beta" or "beta.N", where N is an integer.
///
/// Beta versions only implement `PartialEq` and `PartialOrd` because betas which don't have a
/// version are not comparable to other beta versions.
#[derive(Debug, Clone, Copy)]
pub struct BetaNum(u8);
impl BetaNum {
    /// Creates a beta with a version number.
    ///
    /// If zero is given, this is equivalent to `BetaNum::ambiguous()`.
    pub fn new(n: u8) -> BetaNum {
        BetaNum(n)
    }

    /// Creates a beta without a version number.
    pub fn ambiguous() -> BetaNum {
        BetaNum(0)
    }

    /// Gets the version for this beta, if given.
    pub fn num(self) -> Option<u8> {
        if self.0 == 0 { None } else { Some(self.0) }
    }
}

impl From<Option<u8>> for BetaNum {
    fn from(opt: Option<u8>) -> BetaNum {
        BetaNum::new(opt.unwrap_or(0))
    }
}
impl From<BetaNum> for Option<u8> {
    fn from(beta: BetaNum) -> Option<u8> {
        beta.num()
    }
}

impl fmt::Display for BetaNum {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.0 == 0 {
            f.pad("beta")
        } else {
            let mut buf = *b"beta.255";
            let len = self.0.write_to(&mut buf[b"beta.".len()..]);
            f.pad(unsafe { from_utf8_unchecked(&buf[..b"beta.".len() + len]) })
        }
    }
}

impl PartialEq for BetaNum {
    fn eq(&self, rhs: &BetaNum) -> bool {
        match (self.0, rhs.0) {
            (0, _) | (_, 0) => false,
            (a, b) => a == b,
        }
    }
}
impl PartialOrd for BetaNum {
    fn partial_cmp(&self, rhs: &BetaNum) -> Option<Ordering> {
        match (self.0, rhs.0) {
            (0, _) | (_, 0) => None,
            (a, b) => a.partial_cmp(&b),
        }
    }
}

impl PartialEq<u8> for BetaNum {
    fn eq(&self, rhs: &u8) -> bool {
        *self == BetaNum::new(*rhs)
    }
}
impl PartialEq<BetaNum> for u8 {
    fn eq(&self, rhs: &BetaNum) -> bool {
        BetaNum::new(*self) == *rhs
    }
}
impl PartialOrd<u8> for BetaNum {
    fn partial_cmp(&self, rhs: &u8) -> Option<Ordering> {
        self.partial_cmp(&BetaNum::new(*rhs))
    }
}
impl PartialOrd<BetaNum> for u8 {
    fn partial_cmp(&self, rhs: &BetaNum) -> Option<Ordering> {
        BetaNum::new(*self).partial_cmp(rhs)
    }
}

impl<'a> TryFrom<&'a str> for BetaNum {
    type Error = ParseBetaError<'a>;
    fn try_from(s: &'a str) -> Result<BetaNum, ParseBetaError<'a>> {
        BetaNum::try_from(s.as_bytes())
    }
}
impl<'a> TryFrom<&'a [u8]> for BetaNum {
    type Error = ParseBetaError<'a>;
    fn try_from(bytes: &'a [u8]) -> Result<BetaNum, ParseBetaError<'a>> {
        if bytes.starts_with(b"beta") {
            let rest = &bytes[b"beta".len()..];
            if rest.is_empty() {
                Ok(BetaNum::ambiguous())
            } else if rest.starts_with(b".") {
                match parse_uint(&rest[1..]) {
                    Err(ParseUintError::Empty) => Err(ParseBetaError::Format(bytes)),
                    Err(ParseUintError::BadByte(_)) |
                    Ok(0) => Err(ParseBetaError::Number(&rest[1..])),
                    Err(ParseUintError::Overflow) => Err(ParseBetaError::Overflow(&rest[1..])),
                    Ok(n) => Ok(BetaNum::new(n)),
                }
            } else {
                Err(ParseBetaError::Format(bytes))
            }
        } else {
            Err(ParseBetaError::Format(bytes))
        }
    }
}

/// Error encountered when parsing a [`BetaNum`].
///
/// [`BetaNum`]: struct.BetaNum.html
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub enum ParseBetaError<'a> {
    /// The string wasn't `"beta"` or `"beta.N"`.
    Format(&'a [u8]),

    /// The number in `"beta.N"` could not be parsed as a positive number.
    Number(&'a [u8]),

    /// The number in `"beta.N"` was too large.
    Overflow(&'a [u8]),
}
impl<'a> fmt::Debug for ParseBetaError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ParseBetaError::Format(bytes) => {
                f.debug_tuple("ParseBetaError::Format")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
            ParseBetaError::Number(bytes) => {
                f.debug_tuple("ParseBetaError::Number")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
            ParseBetaError::Overflow(bytes) => {
                f.debug_tuple("ParseBetaError::Overflow")
                    .field(&String::from_utf8_lossy(bytes))
                    .finish()
            }
        }
    }
}
impl<'a> fmt::Display for ParseBetaError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ParseBetaError::Format(bytes) => {
                write!(
                    f,
                    "could not parse {:?} as \"beta\" or \"beta.N\"",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseBetaError::Number(bytes) => {
                write!(
                    f,
                    "could not parse {:?} as a positive number",
                    String::from_utf8_lossy(bytes)
                )
            }
            ParseBetaError::Overflow(bytes) => {
                write!(
                    f,
                    "could not parse {:?}; was greater than 255",
                    String::from_utf8_lossy(bytes)
                )
            }
        }
    }
}
impl<'a> Error for ParseBetaError<'a> {
    fn description(&self) -> &str {
        match *self {
            ParseBetaError::Format(_) => "could not parse as \"beta\" or \"beta.N\"",
            ParseBetaError::Number(_) => {
                "could not parse \"beta.N\" with \"N\" as a positive number"
            }
            ParseBetaError::Overflow(_) => {
                "could not parse \"beta.N\" because \"N\" was greater than 255"
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::convert::TryFrom;

    use super::{BetaNum, ParseBetaError};

    #[test]
    fn parse_format() {
        assert!(BetaNum::try_from(&b"beta"[..]).unwrap().num().is_none());
        assert_eq!(
            BetaNum::try_from(&b"bet"[..]),
            Err(ParseBetaError::Format(b"bet"))
        );
    }

    #[test]
    fn ambiguous_cmp() {
        assert_ne!(BetaNum::ambiguous(), BetaNum::ambiguous());
        assert!(
            BetaNum::ambiguous()
                .partial_cmp(&BetaNum::ambiguous())
                .is_none()
        );
    }

    #[test]
    fn parse_numbers() {
        assert_eq!(
            BetaNum::try_from(&b"beta."[..]),
            Err(ParseBetaError::Format(b"beta."))
        );
        assert_eq!(
            BetaNum::try_from(&b"beta.oops"[..]),
            Err(ParseBetaError::Number(b"oops"))
        );
        assert_eq!(
            BetaNum::try_from(&b"beta.-123"[..]),
            Err(ParseBetaError::Number(b"-123"))
        );
        assert_eq!(
            BetaNum::try_from(&b"beta.-500"[..]),
            Err(ParseBetaError::Number(b"-500"))
        );
        assert_eq!(
            BetaNum::try_from(&b"beta.0"[..]),
            Err(ParseBetaError::Number(b"0"))
        );
        assert_eq!(BetaNum::try_from(&b"beta.123"[..]), Ok(BetaNum::new(123)));
    }

    #[test]
    fn parse_overflow() {
        assert_eq!(BetaNum::try_from(&b"beta.255"[..]), Ok(BetaNum::new(255)));
        assert_eq!(
            BetaNum::try_from(&b"beta.500"[..]),
            Err(ParseBetaError::Overflow(b"500"))
        );
    }
}