use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Availability {
Available,
Prompt,
Unsupported(&'static str),
}
pub const COLUMN: usize = if cfg!(target_family = "wasm") {
2
} else if cfg!(target_os = "macos") {
1
} else {
0
};
pub const WEB: bool = COLUMN == 2;
pub trait Feature: Copy {
fn targets(self) -> [Availability; 3];
fn availability(self) -> Availability {
self.targets()[COLUMN]
}
}
#[must_use]
pub fn availability<F: Feature>(feature: F) -> Availability {
feature.availability()
}
#[must_use]
pub fn available<F: Feature>(feature: F) -> bool {
feature.availability() == Availability::Available
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Unsupported<F> {
pub feature: F,
pub reason: &'static str,
}
impl<F: Feature> Unsupported<F> {
#[must_use]
pub fn of(feature: F) -> Self {
let reason = match feature.availability() {
Availability::Unsupported(reason) => reason,
Availability::Available | Availability::Prompt => "This host cannot do this.",
};
Self { feature, reason }
}
}
impl<F> fmt::Display for Unsupported<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.reason)
}
}
impl<F: fmt::Debug> std::error::Error for Unsupported<F> {}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Copy, Debug, PartialEq)]
struct WebOnlyMissing;
impl Feature for WebOnlyMissing {
fn targets(self) -> [Availability; 3] {
[
Availability::Available,
Availability::Prompt,
Availability::Unsupported("web"),
]
}
}
#[test]
fn a_feature_reads_this_targets_column() {
assert_eq!(
availability(WebOnlyMissing),
WebOnlyMissing.targets()[COLUMN]
);
}
#[test]
fn unsupported_carries_the_columns_reason() {
let reason = Unsupported::of(WebOnlyMissing).reason;
if COLUMN == 2 {
assert_eq!(reason, "web");
} else {
assert_eq!(reason, "This host cannot do this.");
}
}
}