rahti_native/platform.rs
1//! Which operating system the package is running on.
2//!
3//! Two named platforms and an "other", rather than a `cfg!` at every call
4//! site: the path rules, the secret store and the back-button behaviour all
5//! branch on this, and a value can be constructed in a test on a machine that
6//! is neither.
7
8use std::fmt;
9
10/// A platform a Rahti application can be packaged for.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum Platform {
13 Windows,
14 Android,
15 /// Anything else the host compiles for. Packaging is not supported, but
16 /// the embedded server and the paths still resolve, which is what lets
17 /// this crate's tests run on a Linux CI machine.
18 Other,
19}
20
21impl Platform {
22 /// The platform this binary was compiled for.
23 pub const fn current() -> Self {
24 if cfg!(target_os = "windows") {
25 Platform::Windows
26 } else if cfg!(target_os = "android") {
27 Platform::Android
28 } else {
29 Platform::Other
30 }
31 }
32
33 /// The name `pp.native.platform` reports to the browser.
34 pub const fn name(self) -> &'static str {
35 match self {
36 Platform::Windows => "windows",
37 Platform::Android => "android",
38 Platform::Other => "other",
39 }
40 }
41
42 /// The name `cargo rahti native --target` accepts, for the two that have
43 /// one.
44 pub fn parse_target(value: &str) -> Option<Self> {
45 match value.trim().to_ascii_lowercase().as_str() {
46 "windows" | "win" => Some(Platform::Windows),
47 "android" => Some(Platform::Android),
48 _ => None,
49 }
50 }
51
52 /// Whether the application is on a battery-powered platform whose OS may
53 /// stop and recreate the process at will.
54 ///
55 /// Android does; Windows does not. The difference decides whether a
56 /// long-lived task may assume it will be allowed to finish.
57 pub const fn is_mobile(self) -> bool {
58 matches!(self, Platform::Android)
59 }
60}
61
62impl fmt::Display for Platform {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 f.write_str(self.name())
65 }
66}