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
use {
snafu::prelude::*,
std::str::FromStr,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct DeviceId {
pub major: u32,
pub minor: u32,
}
#[derive(Debug, Snafu)]
#[snafu(display("Could not parse {string} as a device id"))]
pub struct ParseDeviceIdError {
string: String,
}
impl FromStr for DeviceId {
type Err = ParseDeviceIdError;
fn from_str(string: &str) -> Result<Self, Self::Err> {
(|| {
let mut parts = string.split(':').fuse();
match (parts.next(), parts.next(), parts.next()) {
(Some(major), Some(minor), None) => {
let major = major.parse().ok()?;
let minor = minor.parse().ok()?;
Some(Self { major, minor })
}
(Some(int), None, None) => {
let int: u64 = int.parse().ok()?;
Some( int.into() )
}
_ => None,
}
})().with_context(|| ParseDeviceIdSnafu { string })
}
}
impl From<u64> for DeviceId {
fn from(num: u64) -> Self {
Self {
major: (num >> 8) as u32,
minor: (num & 0xFF) as u32,
}
}
}
impl DeviceId {
pub fn new(major: u32, minor: u32) -> Self {
Self { major, minor }
}
}
#[test]
fn test_from_str() {
assert_eq!(DeviceId::new(8, 16), DeviceId::from_str("8:16").unwrap());
}
#[test]
fn test_from_u64() {
assert_eq!(DeviceId::new(8, 16), DeviceId::from(2064u64));
}