rustversion-detect 0.2.0

Detect rustc compiler version
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
//! Defines the rust version types.

use core::fmt::{self, Display, Formatter};
use core::num::ParseIntError;
use core::str::FromStr;

use crate::date::Date;

/// Specifies a specific stable version, like `1.48`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct StableVersionSpec {
    /// The major version
    pub major: u32,
    /// The minor version
    pub minor: u32,
    /// The patch version.
    ///
    /// If this is `None`, it will match any patch version.
    pub patch: Option<u32>,
}
impl StableVersionSpec {
    /// Specify a minor version like `1.32`.
    ///
    /// # Panics
    /// Panics if the major version is not `1`.
    #[inline]
    pub fn minor(major: u32, minor: u32) -> Self {
        check_major_version(major);
        StableVersionSpec {
            major,
            minor,
            patch: None,
        }
    }

    /// Specify a patch version like `1.32.4`.
    ///
    /// # Panics
    /// Panics if the major version is not `1`.
    #[inline]
    pub fn patch(major: u32, minor: u32, patch: u32) -> Self {
        check_major_version(major);
        StableVersionSpec {
            major,
            minor,
            patch: Some(patch),
        }
    }

    /// Convert this specification into a concrete [`RustVersion`].
    ///
    /// If the patch version is not specified,
    /// it is assumed to be zero.
    #[inline]
    pub fn to_version(&self) -> RustVersion {
        RustVersion::stable(self.major, self.minor, self.patch.unwrap_or(0))
    }
}
impl FromStr for StableVersionSpec {
    type Err = StableVersionParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut iter = s.split('.');
        let major = iter
            .next()
            .ok_or(StableVersionParseError::BadNumberParts)?
            .parse::<u32>()?;
        let minor = iter
            .next()
            .ok_or(StableVersionParseError::BadNumberParts)?
            .parse::<u32>()?;
        let patch = match iter.next() {
            Some(patch_text) => Some(patch_text.parse::<u32>()?),
            None => None,
        };
        if iter.next().is_some() {
            return Err(StableVersionParseError::BadNumberParts);
        }
        if major != 1 {
            return Err(StableVersionParseError::InvalidMajorVersion);
        }
        Ok(StableVersionSpec {
            major,
            minor,
            patch,
        })
    }
}

/// An error while parsing a [`StableVersionSpec`].
///
/// The specifics of this error are implementation-dependent.
#[derive(Clone, Debug)]
pub enum StableVersionParseError {
    #[doc(hidden)]
    InvalidNumber(ParseIntError),
    #[doc(hidden)]
    BadNumberParts,
    #[doc(hidden)]
    InvalidMajorVersion,
}
impl From<ParseIntError> for StableVersionParseError {
    #[inline]
    fn from(cause: ParseIntError) -> Self {
        StableVersionParseError::InvalidNumber(cause)
    }
}

/// Show the specification in a manner consistent with the `spec!` macro.
impl Display for StableVersionSpec {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}", self.major, self.minor)?;
        if let Some(patch) = self.patch {
            write!(f, ".{}", patch)?;
        }
        Ok(())
    }
}

/// Indicates the rust version.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct RustVersion {
    /// The major version.
    ///
    /// Should always be one.
    pub major: u32,
    /// The minor version of rust.
    pub minor: u32,
    /// The patch version of the rust compiler.
    pub patch: u32,
    /// The channel of the rust compiler.
    pub channel: Channel,
}
impl RustVersion {
    /// Create a stable version with the specified combination of major, minor, and patch.
    ///
    /// The major version must be 1.0.
    #[inline]
    pub fn stable(major: u32, minor: u32, patch: u32) -> RustVersion {
        check_major_version(major);
        RustVersion {
            major,
            minor,
            patch,
            channel: Channel::Stable,
        }
    }

    /// Check if this version is after the specified stable minor version.
    ///
    /// The patch version is unspecified and will be ignored.
    ///
    /// This is a shorthand for calling [`Self::is_since_stable`] with a minor version
    /// spec created with [`StableVersionSpec::minor`].
    ///
    /// The major version must always be one, or a panic could happen.
    ///
    /// ## Example
    /// ```
    /// # use rustversion_detect::RustVersion;
    ///
    /// assert!(RustVersion::stable(1, 32, 2).is_since_minor_version(1, 32));
    /// assert!(RustVersion::stable(1, 48, 0).is_since_minor_version(1, 40));
    /// ```
    #[inline]
    pub fn is_since_minor_version(&self, major: u32, minor: u32) -> bool {
        self.is_since_stable(StableVersionSpec::minor(major, minor))
    }

    /// Check if this version is after the specified stable patch version.
    ///
    /// This is a shorthand for calling [`Self::is_since_stable`] with a patch version
    /// spec created with [`StableVersionSpec::patch`].
    ///
    /// The major version must always be one, or a panic could happen.
    ///
    /// ## Example
    /// ```
    /// # use rustversion_detect::RustVersion;
    ///
    /// assert!(RustVersion::stable(1, 32, 2).is_since_patch_version(1, 32, 1));
    /// assert!(RustVersion::stable(1, 48, 0).is_since_patch_version(1, 40, 5));
    /// ```
    #[inline]
    pub fn is_since_patch_version(&self, major: u32, minor: u32, patch: u32) -> bool {
        self.is_since_stable(StableVersionSpec::patch(major, minor, patch))
    }

    /// Check if this version is after the given [stable version spec](StableVersionSpec).
    ///
    /// In general, the [`Self::is_since_minor_version`] and [`Self::is_since_patch_version`]
    /// helper methods are preferable.
    ///
    /// This ignores the channel.
    ///
    /// The negation of [`Self::is_before_stable`].
    ///
    /// Behavior is (mostly) equivalent to `#[rustversion::since($spec)]`
    ///
    /// ## Example
    /// ```
    /// # use rustversion_detect::{RustVersion, StableVersionSpec};
    ///
    /// assert!(RustVersion::stable(1, 32, 2).is_since_stable(StableVersionSpec::minor(1, 32)));
    /// assert!(RustVersion::stable(1, 48, 0).is_since_stable(StableVersionSpec::patch(1, 32, 7)))
    /// ```
    #[inline]
    pub fn is_since_stable(&self, spec: StableVersionSpec) -> bool {
        self.major > spec.major
            || (self.major == spec.major
                && (self.minor > spec.minor
                    || (self.minor == spec.minor
                        && match spec.patch {
                            None => true, // missing spec always matches
                            Some(patch_spec) => self.patch >= patch_spec,
                        })))
    }

    /// Check if the version is less than the given [stable version spec](StableVersionSpec).
    ///
    /// This ignores the channel.
    ///
    /// In general, the [`Self::is_before_minor_version`] and [`Self::is_before_patch_version`]
    /// helper methods are preferable.
    ///
    /// The negation of [`Self::is_since_stable`].
    ///
    /// Behavior is (mostly) equivalent to `#[rustversion::before($spec)]`
    #[inline]
    pub fn is_before_stable(&self, spec: StableVersionSpec) -> bool {
        !self.is_since_stable(spec)
    }

    /// Check if this version is before the specified stable minor version.
    ///
    /// The patch version is unspecified and will be ignored.
    ///
    /// This is a shorthand for calling [`Self::is_before_stable`] with a minor version
    /// spec created with [`StableVersionSpec::minor`].
    ///
    /// The major version must always be one, or a panic could happen.
    #[inline]
    pub fn is_before_minor_version(&self, major: u32, minor: u32) -> bool {
        self.is_before_stable(StableVersionSpec::minor(major, minor))
    }

    /// Check if this version is before the specified stable patch version.
    ///
    /// This is a shorthand for calling [`Self::is_before_stable`] with a patch version
    /// spec created with [`StableVersionSpec::patch`].
    ///
    /// The major version must always be one, or a panic could happen.
    #[inline]
    pub fn is_before_patch_version(&self, major: u32, minor: u32, patch: u32) -> bool {
        self.is_before_stable(StableVersionSpec::patch(major, minor, patch))
    }

    /// If this version is a nightly version after the specified start date.
    ///
    /// Stable and beta versions are always considered before every nightly versions.
    /// Development versions are considered after every nightly version.
    ///
    /// The negation of [`Self::is_before_nightly`].
    ///
    /// Behavior is (mostly) equivalent to `#[rustversion::since($date)]`
    ///
    /// See also [`Date::is_since`].
    #[inline]
    pub fn is_since_nightly(&self, start: Date) -> bool {
        match self.channel {
            Channel::Nightly { date } => date.is_since(start),
            Channel::Stable | Channel::Beta => false, // before every nightly
            Channel::Development => true,             // after every nightly version
            Channel::__NonExhaustive => unreachable!(),
        }
    }

    /// If this version comes before the nightly version with the specified start date.
    ///
    /// Stable and beta versions are always considered before every nightly versions.
    /// Development versions are considered after every nightly version.
    ///
    /// The negation of [`Self::is_since_nightly`].
    ///
    /// See also [`Date::is_before`].
    #[inline]
    pub fn is_before_nightly(&self, start: Date) -> bool {
        match self.channel {
            Channel::Nightly { date } => date <= start,
            Channel::Stable | Channel::Beta => false, // before every nightly
            Channel::Development => true,             // after every nightly version
            Channel::__NonExhaustive => unreachable!(),
        }
    }

    /// Check if this is a nightly compiler version.
    #[inline]
    pub fn is_nightly(&self) -> bool {
        self.channel.is_nightly()
    }

    /// Check if this is a stable compiler version.
    #[inline]
    pub fn is_stable(&self) -> bool {
        self.channel.is_stable()
    }

    /// Check if this is a beta compiler version.
    #[inline]
    pub fn is_beta(&self) -> bool {
        self.channel.is_beta()
    }

    /// Check if this is a development compiler version.
    #[inline]
    pub fn is_development(&self) -> bool {
        self.channel.is_development()
    }
}

impl From<StableVersionSpec> for RustVersion {
    #[inline]
    fn from(value: StableVersionSpec) -> Self {
        value.to_version()
    }
}

/// Displays the version in a manner similar to `rustc --version`.
///
/// The format here is not stable and may change in the future.
impl Display for RustVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
        match self.channel {
            Channel::Stable => Ok(()), // nothing
            Channel::Beta => f.write_str("-beta"),
            Channel::Nightly { ref date } => {
                write!(f, "-nightly ({})", date)
            }
            Channel::Development => f.write_str("-dev"),
            Channel::__NonExhaustive => unreachable!(),
        }
    }
}

/// The [channel] of the rust compiler release.
///
/// [channel]: https://rust-lang.github.io/rustup/concepts/channels.html
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Channel {
    /// A stable compiler version.
    Stable,
    /// A beta compiler version.
    Beta,
    /// A nightly compiler version.
    Nightly {
        /// The date that the compiler was released.
        date: Date,
    },
    /// A development compiler version.
    ///
    /// These are compiled directly instead of distributed through [rustup](https://rustup.rs).
    Development,
    #[doc(hidden)]
    __NonExhaustive,
}
impl Channel {
    /// Check if this is the nightly channel.
    #[inline]
    pub fn is_nightly(&self) -> bool {
        // NOTE: Can't use matches! because of minimum rust version
        match *self {
            Channel::Nightly { .. } => true,
            _ => false,
        }
    }

    /// Check if this is the stable channel.
    #[inline]
    pub fn is_stable(&self) -> bool {
        match *self {
            Channel::Stable => true,
            _ => false,
        }
    }

    /// Check if this is the beta channel.
    #[inline]
    pub fn is_beta(&self) -> bool {
        match *self {
            Channel::Beta => true,
            _ => false,
        }
    }

    /// Check if this is the development channel.
    #[inline]
    pub fn is_development(&self) -> bool {
        match *self {
            Channel::Development => true,
            _ => false,
        }
    }
}

#[inline]
fn check_major_version(major: u32) {
    assert_eq!(major, 1, "Major version must be 1.*");
}

#[cfg(test)]
mod test {
    use super::{RustVersion, StableVersionSpec};

    // (before, after)
    fn versions() -> Vec<(RustVersion, RustVersion)> {
        vec![
            (RustVersion::stable(1, 7, 8), RustVersion::stable(1, 89, 0)),
            (RustVersion::stable(1, 18, 0), RustVersion::stable(1, 80, 3)),
        ]
    }

    #[cfg(test)]
    impl RustVersion {
        #[inline]
        pub(crate) fn to_spec(&self) -> StableVersionSpec {
            StableVersionSpec::patch(self.major, self.minor, self.patch)
        }
    }

    #[test]
    fn test_before_after() {
        for (before, after) in versions() {
            assert!(
                before.is_before_stable(after.to_spec()),
                "{} & {}",
                before,
                after
            );
            assert!(
                after.is_since_stable(before.to_spec()),
                "{} & {}",
                before,
                after
            );
        }
    }
}