Skip to content

Commit

Permalink
refactor(manifest): Make env macro as minimal as possible
Browse files Browse the repository at this point in the history
Macros add a lot of code complexity.  This tries to reduce it by making
the macro do the bare minimum possible.

This does cause some extra branching (unless its compiled out) but that
shouldn't be prohibitive.
  • Loading branch information
epage committed Jan 2, 2025
1 parent b16514d commit 711d6be
Showing 1 changed file with 11 additions and 25 deletions.
36 changes: 11 additions & 25 deletions src/cargo/core/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,42 +156,25 @@ macro_rules! get_metadata_env {
};
}

struct MetadataEnvs;

macro_rules! metadata_envs {
(
$(
($field:ident, $key:literal$(, $to_var:expr)?),
)*
) => {
struct MetadataEnvs;
impl MetadataEnvs {
$(
fn $field(meta: &ManifestMetadata) -> Cow<'_, str> {
get_metadata_env!(meta, $field$(, $to_var)?)
}
)*

pub fn should_track(key: &str) -> bool {
let keys = [$($key),*];
keys.iter().any(|k| *k == key)
fn keys() -> &'static [&'static str] {
&[$($key),*]
}

pub fn var<'a>(meta: &'a ManifestMetadata, key: &str) -> Option<Cow<'a, str>> {
fn var<'a>(meta: &'a ManifestMetadata, key: &str) -> Option<Cow<'a, str>> {
match key {
$($key => Some(Self::$field(meta)),)*
$($key => Some(get_metadata_env!(meta, $field$(, $to_var)?)),)*
_ => None,
}
}

pub fn vars(meta: &ManifestMetadata) -> impl Iterator<Item = (&'static str, Cow<'_, str>)> {
[
$(
(
$key,
Self::$field(meta),
),
)*
].into_iter()
}
}
}
}
Expand All @@ -213,15 +196,18 @@ metadata_envs! {
impl ManifestMetadata {
/// Whether the given env var should be tracked by Cargo's dep-info.
pub fn should_track(env_key: &str) -> bool {
MetadataEnvs::should_track(env_key)
let keys = MetadataEnvs::keys();
keys.iter().any(|k| *k == env_key)
}

pub fn env_var<'a>(&'a self, env_key: &str) -> Option<Cow<'a, str>> {
MetadataEnvs::var(self, env_key)
}

pub fn env_vars(&self) -> impl Iterator<Item = (&'static str, Cow<'_, str>)> {
MetadataEnvs::vars(self)
MetadataEnvs::keys()
.iter()
.map(|k| (*k, MetadataEnvs::var(self, k).unwrap()))
}
}

Expand Down

0 comments on commit 711d6be

Please sign in to comment.