gcd_rs/
version.rs

1//! Version represent some software version.
2//!
3//! Is composed of a major and minor values. It could be represented as
4//! u8 or u16.
5//!
6//! The minor value is know to be on the range 0..100
7//!
8//! The major value is know to be on the range 0..2 in u8 format, or 0..65334 in
9//! u16 format.
10//!
11//! The version is represented in decimal, the two least significant values
12//! represent the minor, the rest represent the major. Eg: 380 (0x17c) result in
13//! major 3 and minor 80, v3.80.
14//!
15//! The value 0xffff seems to be reserved. Possibly representing an Null for
16//! the version value, if forced to print, it will simply print "0.0".
17
18use serde::{Deserialize, Serialize};
19use std::fmt;
20
21/// Can be created from/to a u8 or u16 values.
22#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone, Serialize, Deserialize)]
23#[non_exhaustive]
24pub enum Version {
25    /// No version available
26    None,
27    /// Simple version format {major}.{minor}, eg: major = 3, minor = 80: v3.80
28    Simple { major: u16, minor: u8 },
29    // reserved for future version formats
30}
31
32impl Version {
33    pub const fn new_raw(value: u16) -> Self {
34        match value {
35            0xffff => Version::None,
36            x => Version::Simple {
37                major: x / 100,
38                minor: (x % 100) as u8,
39            },
40        }
41    }
42
43    pub const fn new(major: u16, minor: u8) -> Self {
44        Version::Simple { major, minor }
45    }
46
47    pub const fn value(&self) -> u16 {
48        match self {
49            Version::None => 0xffff,
50            Version::Simple { major, minor } => (*major * 100) + *minor as u16,
51        }
52    }
53}
54
55impl fmt::Display for Version {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            Version::None => write!(f, "0.0"),
59            Version::Simple { major, minor } => {
60                write!(f, "{}.{}", major, minor)
61            }
62        }
63    }
64}
65
66impl From<u16> for Version {
67    fn from(x: u16) -> Self {
68        Version::new_raw(x)
69    }
70}
71
72impl From<u8> for Version {
73    fn from(x: u8) -> Self {
74        Version::new_raw(x as u16)
75    }
76}
77
78impl From<Version> for u16 {
79    fn from(x: Version) -> u16 {
80        x.value()
81    }
82}