use core::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Version {
major: u16,
minor: u16,
}
impl Version {
pub const V5_6: Self = Self::new(5, 60);
pub const V5_8: Self = Self::new(5, 80);
pub const V6_1: Self = Self::new(6, 10);
pub const V6_32: Self = Self::new(6, 32);
pub const V7_0: Self = Self::new(7, 0);
pub const V7_51: Self = Self::new(7, 51);
pub const V7_64: Self = Self::new(7, 64);
pub const V7_84: Self = Self::new(7, 84);
pub const fn new(major: u16, minor: u16) -> Self {
Self { major, minor }
}
pub const fn from_raw(raw: u32) -> Self {
let major = (raw & 0xFFFF) as u16;
let minor = (raw >> 16) as u16;
match (major, minor) {
(0, 0..=3) => Self::new(6, minor),
(0, 8 | 9) => Self::new(5, minor * 10),
(0, _) => Self::new(5, minor),
(6, 1 | 2) => Self::new(6, minor * 10),
_ => Self::new(major, minor),
}
}
pub const fn to_raw(self) -> u32 {
(self.minor as u32) << 16 | self.major as u32
}
pub const fn major(self) -> u16 {
self.major
}
pub const fn minor(self) -> u16 {
self.minor
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.minor % 10 == 0 && self.minor < 100 {
write!(f, "{}.{}", self.major, self.minor / 10)
} else {
write!(f, "{}.{:02}", self.major, self.minor)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn raw(major: u32, minor: u32) -> u32 {
minor << 16 | major
}
#[test]
fn corrects_every_buggy_release() {
let cases = [
((0, 8), (5, 80)),
((0, 81), (5, 81)),
((0, 82), (5, 82)),
((0, 9), (5, 90)),
((0, 91), (5, 91)),
((0, 0), (6, 0)),
((0, 1), (6, 1)),
((0, 2), (6, 2)),
((0, 3), (6, 3)),
((6, 1), (6, 10)),
((6, 2), (6, 20)),
];
for ((maj, min), (want_maj, want_min)) in cases {
assert_eq!(
Version::from_raw(raw(maj, min)),
Version::new(want_maj, want_min),
"raw {maj}.{min}"
);
}
}
#[test]
fn leaves_correct_releases_alone() {
for (maj, min) in [
(6, 11),
(6, 17),
(6, 21),
(6, 35),
(7, 0),
(7, 1),
(7, 64),
(7, 85),
] {
assert_eq!(
Version::from_raw(raw(maj, min)),
Version::new(maj as u16, min as u16)
);
}
}
#[test]
fn corrected_versions_sort_in_release_order() {
let releases = [
(0, 8),
(0, 81),
(0, 82),
(0, 9),
(0, 91),
(0, 0),
(0, 1),
(0, 2),
(0, 3),
];
let releases =
releases
.into_iter()
.chain([(6, 1), (6, 11), (6, 17), (6, 2), (6, 21), (7, 0)]);
let versions: Vec<_> = releases
.map(|(a, b)| Version::from_raw(raw(a, b)))
.collect();
assert!(versions.is_sorted(), "{versions:?}");
}
#[test]
fn round_trips_raw() {
assert_eq!(
Version::from_raw(Version::new(7, 85).to_raw()),
Version::new(7, 85)
);
}
#[test]
fn displays_like_mirc() {
assert_eq!(Version::new(7, 85).to_string(), "7.85");
assert_eq!(Version::new(7, 1).to_string(), "7.01");
assert_eq!(Version::new(6, 20).to_string(), "6.2");
assert_eq!(Version::new(6, 0).to_string(), "6.0");
assert_eq!(Version::new(5, 91).to_string(), "5.91");
}
}