1use std::fmt;
4
5#[derive(Debug, Clone, Copy, Hash, Ord, PartialOrd, Eq, PartialEq)]
7pub enum Platform {
8 Windows,
9 Mac,
10 Linux,
11 #[allow(non_camel_case_types)] iOS,
12 Android,
13 Unknown,
14}
15
16#[derive(Debug, Clone, Copy, Hash, Ord, PartialOrd, Eq, PartialEq)]
18pub enum PlatformVendor {
19 Microsoft,
20 Apple,
21 Google,
22 Unknown,
23}
24
25pub fn get_current_platform() -> Platform {
27 if cfg!(target_os = "windows") {
28 Platform::Windows
29 } else if cfg!(target_os = "macos") {
30 Platform::Mac
31 } else if cfg!(target_os = "linux") {
32 Platform::Linux
33 } else if cfg!(target_os = "ios") {
34 Platform::iOS
35 } else if cfg!(target_os = "android") {
36 Platform::Android
37 } else {
38 Platform::Unknown
39 }
40}
41
42pub fn get_current_platform_vendor() -> PlatformVendor {
44 get_current_platform().get_vendor()
45}
46
47impl Platform {
48 pub fn get_current() -> Platform {
50 get_current_platform()
51 }
52
53 pub fn get_vendor(&self) -> PlatformVendor {
55 match self {
56 Platform::Windows => PlatformVendor::Microsoft,
57 Platform::Mac => PlatformVendor::Apple,
58 Platform::iOS => PlatformVendor:: Apple,
59 Platform::Android => PlatformVendor::Google,
60 _ => PlatformVendor::Unknown,
61 }
62 }
63}
64
65impl Default for Platform {
66 fn default() -> Self {
67 get_current_platform()
68 }
69}
70
71impl fmt::Display for Platform {
72 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73 write!(f, "{:?}", self)
74 }
75}
76
77impl PlatformVendor {
78 pub fn get_current() -> PlatformVendor {
80 get_current_platform_vendor()
81 }
82}
83
84impl Default for PlatformVendor {
85 fn default() -> Self {
86 get_current_platform_vendor()
87 }
88}
89
90impl fmt::Display for PlatformVendor {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 write!(f, "{:?}", self)
93 }
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 #[test]
101 fn get_current_platform_works() {
102 let platform = get_current_platform();
103
104 if cfg!(target_os = "windows") {
105 assert_eq!(platform, Platform::Windows, "current platform on windows should be windows")
106 } else if cfg!(target_os = "macos") {
107 assert_eq!(platform, Platform::Mac, "current platform on macos should be macos")
108 } else if cfg!(target_os = "linux") {
109 assert_eq!(platform, Platform::Linux, "current platform on linux should be linux")
110 } else if cfg!(target_os = "ios") {
111 assert_eq!(platform, Platform::iOS, "current platform on ios should be ios")
112 } else if cfg!(target_os = "android") {
113 assert_eq!(platform, Platform::Android, "current platform on android should be android")
114 } else {
115 assert_eq!(platform, Platform::Unknown, "current platform on unknown platform should be unknown")
116 }
117 }
118}