platform/lib.rs
1// Copyright 2018 Jacob Kiesel
2
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! This crate provides an easy way to inline selection of input parameters
16//! based on the platform being targeted. Can be used on any `Sized` type.
17//!
18//! This is guaranteed to be a zero cost abstraction, as all calls are inlined.
19//!
20//! ```
21//! extern crate platform;
22//!
23//! use platform::Platform;
24//!
25//! fn main() {
26//! println!("Hello from {}!",
27//! "unknown"
28//! .ios("ios")
29//! .android("android")
30//! .windows("windows")
31//! .macos("macos")
32//! .linux("linux")
33//! .wasm32("wasm32")
34//! .emscripten("emscripten")
35//! );
36//!
37//! // Alternatively, let's pretend the arguments are non-trivial to evaluate.
38//! // We can also use this on function pointers so long as all the variants can
39//! // coerce to the same function pointer type.
40//! println!("Hello from {}!",
41//! ((|| String::from("unknown")) as fn() -> String)
42//! .ios(|| String::from("ios"))
43//! .android(|| String::from("android"))
44//! .windows(|| String::from("windows"))
45//! .macos(|| String::from("macos"))
46//! .linux(|| String::from("linux"))
47//! .wasm32(|| String::from("wasm32"))
48//! .emscripten(|| String::from("emscripten"))
49//! ()
50//! );
51//! }
52//! ```
53
54macro_rules! define_platform {
55 ($platform:ident, $name:tt) => {
56 #[inline(always)]
57 fn $platform(self, _input: Self) -> Self {
58 #[cfg(target_os=$name)]
59 {
60 _input
61 }
62 #[cfg(not(target_os=$name))]
63 {
64 self
65 }
66 }
67 };
68}
69
70pub trait Platform: Sized {
71 #[inline(always)]
72 fn wasm32(self, _input: Self) -> Self {
73 #[cfg(target_arch = "wasm32")]
74 {
75 _input
76 }
77
78 #[cfg(not(target_arch = "wasm32"))]
79 {
80 self
81 }
82 }
83 define_platform!(ios, "ios");
84 define_platform!(android, "android");
85 define_platform!(windows, "windows");
86 define_platform!(macos, "macos");
87 define_platform!(linux, "linux");
88 define_platform!(emscripten, "emscripten");
89 define_platform!(freebsd, "freebsd");
90 define_platform!(openbsd, "openbsd");
91 define_platform!(dragonfly, "dragonfly");
92 define_platform!(netbsd, "netbsd");
93 define_platform!(redox, "redox");
94}
95
96impl<T> Platform for T {}