r6tracker/types/
platform.rs1use std::convert::TryFrom;
2
3#[derive(Debug)]
5pub struct InvalidPlatformCode(pub u32);
6
7impl std::error::Error for InvalidPlatformCode {}
8
9impl std::fmt::Display for InvalidPlatformCode {
10 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
11 write!(f, "the code {} is not a valid platform", self.0)
12 }
13}
14
15#[derive(Debug, Clone, Copy, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
17#[serde(try_from = "u32")]
18#[serde(into = "u32")]
19pub enum Platform {
20 Pc,
21 Xbox,
22 Ps4,
23}
24
25impl Platform {
26 pub fn as_u32(self) -> u32 {
28 match self {
29 Platform::Pc => 4,
30 Platform::Xbox => 1,
31 Platform::Ps4 => 2,
32 }
33 }
34
35 pub fn from_u32(n: u32) -> Result<Self, InvalidPlatformCode> {
37 match n {
38 4 => Ok(Platform::Pc),
39 1 => Ok(Platform::Xbox),
40 2 => Ok(Platform::Ps4),
41 n => Err(InvalidPlatformCode(n)),
42 }
43 }
44}
45
46impl TryFrom<u32> for Platform {
47 type Error = InvalidPlatformCode;
48
49 fn try_from(n: u32) -> Result<Self, Self::Error> {
50 Self::from_u32(n)
51 }
52}
53
54impl From<Platform> for u32 {
55 fn from(platform: Platform) -> Self {
56 platform.as_u32()
57 }
58}