use crate::Error;
use cfg_expr::targets::get_builtin_target_by_triple;
use custom_platforms::TargetInfo;
use std::{borrow::Cow, collections::BTreeSet, ops::Deref};
include!(concat!(env!("OUT_DIR"), "/current_platform.rs"));
pub mod custom_platforms {
#[doc(inline)]
pub use cfg_expr::targets::{Arch, Endian, Env, Family, Os, TargetInfo, Vendor};
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Platform<'a> {
target_info: &'a TargetInfo<'a>,
target_features: TargetFeatures,
flags: BTreeSet<Cow<'static, str>>,
is_custom: bool,
}
impl Platform<'static> {
pub fn new(triple: impl AsRef<str>, target_features: TargetFeatures) -> Result<Self, Error> {
let triple = triple.as_ref();
Ok(Self {
target_info: get_builtin_target_by_triple(triple)
.ok_or_else(|| Error::UnknownPlatformTriple(triple.to_string()))?,
target_features,
flags: BTreeSet::new(),
is_custom: false,
})
}
}
impl<'a> Platform<'a> {
pub fn custom(target_info: &'a TargetInfo<'a>, target_features: TargetFeatures) -> Self {
Self {
target_info,
target_features,
flags: BTreeSet::new(),
is_custom: true,
}
}
pub fn add_flags(&mut self, flags: impl IntoIterator<Item = impl Into<Cow<'static, str>>>) {
self.flags.extend(flags.into_iter().map(|s| s.into()));
}
pub fn triple(&self) -> &'a str {
self.target_info.triple
}
pub fn flags(&self) -> impl Iterator<Item = &str> {
self.flags.iter().map(|flag| flag.deref())
}
pub fn has_flag(&self, flag: impl AsRef<str>) -> bool {
self.flags.contains(flag.as_ref())
}
pub fn target_info(&self) -> &'a TargetInfo<'a> {
self.target_info
}
pub fn target_features(&self) -> &TargetFeatures {
&self.target_features
}
pub fn is_custom(&self) -> bool {
self.is_custom
}
}
impl Platform<'static> {
pub fn current() -> Option<Self> {
let target_info = get_builtin_target_by_triple(CURRENT_TARGET)?;
let target_features = TargetFeatures::features(CURRENT_TARGET_FEATURES.iter().copied());
Some(Self {
target_info,
target_features,
flags: BTreeSet::new(),
is_custom: false,
})
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum TargetFeatures {
Unknown,
Features(BTreeSet<Cow<'static, str>>),
All,
}
impl TargetFeatures {
pub fn features(features: impl IntoIterator<Item = impl Into<Cow<'static, str>>>) -> Self {
TargetFeatures::Features(features.into_iter().map(|s| s.into()).collect())
}
pub fn none() -> Self {
TargetFeatures::Features(BTreeSet::new())
}
pub fn matches(&self, feature: &str) -> Option<bool> {
match self {
TargetFeatures::Unknown => None,
TargetFeatures::Features(features) => Some(features.contains(feature)),
TargetFeatures::All => Some(true),
}
}
}