readme_sync/
config.rs

1use std::borrow::Cow;
2use std::collections::HashSet;
3
4use crate::Package;
5
6/// A set of enabled named and key-value configuration options.
7#[allow(single_use_lifetimes)] // false positive in PartialEq, issue: rust-lang/rust/#69952
8#[derive(Clone, Debug, Default, Eq, PartialEq)]
9pub struct Config<'a> {
10    /// Enabled named configuration options.
11    pub idents: HashSet<Cow<'a, str>>,
12    /// Enabled key-value configuration options.
13    pub name_values: HashSet<(Cow<'a, str>, Cow<'a, str>)>,
14}
15
16impl<'a> Config<'a> {
17    /// Creates an empty `Config`.
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    /// Creates a `Config` with features defined in `[package.metadata.docs.rs]` table in crates' Cargo.toml.
23    pub fn from_package_docs_rs_features(package: &'a Package) -> Self {
24        Self::new().with_features(package.manifest().docs_rs_features())
25    }
26
27    /// Extend `Config` with the feature names from an iterator.
28    pub fn with_features<I, T>(mut self, features: I) -> Self
29    where
30        I: IntoIterator<Item = T>,
31        T: Into<Cow<'a, str>>,
32    {
33        self.name_values.extend(
34            features
35                .into_iter()
36                .map(|feature| (Cow::from("feature"), feature.into())),
37        );
38        self
39    }
40
41    /// Add target_arch, target_os and target_env `Config` options from the specified target.
42    ///
43    /// This method require non-default feature `platforms`.
44    pub fn with_target_arch_os_env(mut self, target: &str) -> Self {
45        if let Some(platform) = platforms::Platform::find(target) {
46            let _ = self.name_values.insert((
47                Cow::from("target_arch"),
48                Cow::from(platform.target_arch.as_str()),
49            ));
50            let _ = self.name_values.insert((
51                Cow::from("target_os"),
52                Cow::from(platform.target_os.as_str()),
53            ));
54            let _ = self.name_values.insert((
55                Cow::from("target_env"),
56                Cow::from(platform.target_env.as_str()),
57            ));
58        }
59        self
60    }
61}