tilo_platform_caps/
lib.rs1use std::fmt;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum Availability {
10 Available,
11 Prompt,
13 Unsupported(&'static str),
15}
16
17pub const COLUMN: usize = if cfg!(target_family = "wasm") {
20 2
21} else if cfg!(target_os = "macos") {
22 1
23} else {
24 0
25};
26
27pub const WEB: bool = COLUMN == 2;
30
31pub trait Feature: Copy {
32 fn targets(self) -> [Availability; 3];
34
35 fn availability(self) -> Availability {
38 self.targets()[COLUMN]
39 }
40}
41
42#[must_use]
43pub fn availability<F: Feature>(feature: F) -> Availability {
44 feature.availability()
45}
46
47#[must_use]
48pub fn available<F: Feature>(feature: F) -> bool {
49 feature.availability() == Availability::Available
50}
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub struct Unsupported<F> {
54 pub feature: F,
55 pub reason: &'static str,
57}
58
59impl<F: Feature> Unsupported<F> {
60 #[must_use]
61 pub fn of(feature: F) -> Self {
62 let reason = match feature.availability() {
63 Availability::Unsupported(reason) => reason,
64 Availability::Available | Availability::Prompt => "This host cannot do this.",
65 };
66 Self { feature, reason }
67 }
68}
69
70impl<F> fmt::Display for Unsupported<F> {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str(self.reason)
73 }
74}
75
76impl<F: fmt::Debug> std::error::Error for Unsupported<F> {}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 #[derive(Clone, Copy, Debug, PartialEq)]
83 struct WebOnlyMissing;
84
85 impl Feature for WebOnlyMissing {
86 fn targets(self) -> [Availability; 3] {
87 [
88 Availability::Available,
89 Availability::Prompt,
90 Availability::Unsupported("web"),
91 ]
92 }
93 }
94
95 #[test]
96 fn a_feature_reads_this_targets_column() {
97 assert_eq!(
98 availability(WebOnlyMissing),
99 WebOnlyMissing.targets()[COLUMN]
100 );
101 }
102
103 #[test]
104 fn unsupported_carries_the_columns_reason() {
105 let reason = Unsupported::of(WebOnlyMissing).reason;
106 if COLUMN == 2 {
107 assert_eq!(reason, "web");
108 } else {
109 assert_eq!(reason, "This host cannot do this.");
110 }
111 }
112}