Skip to content

add if_cfg! macro #1183

@BennoLossin

Description

@BennoLossin

The following code pattern is becoming more common:

impl ops::Div for Delta {
    type Output = Self;

    #[inline]
    fn div(self, rhs: Self) -> Self::Output {
        #[cfg(CONFIG_64BIT)]
        {
            Self {
                nanos: self.nanos / rhs.nanos,
            }
        }

        #[cfg(not(CONFIG_64BIT))]
        {
            Self {
                // SAFETY: This function is always safe to call regardless of the input values
                nanos: unsafe { bindings::div64_s64(self.nanos, rhs.nanos) },
            }
        }
    }
}

It would be great if we had a if_cfg! macro:

impl ops::Div for Delta {
    type Output = Self;

    #[inline]
    fn div(self, rhs: Self) -> Self::Output {
        Self {
            nanos: if_cfg!(if CONFIG_64BIT {
                self.nanos / rhs.nanos
            } else {
                // SAFETY: This function is always safe to call regardless of the input values
                nanos: unsafe { bindings::div64_s64(self.nanos, rhs.nanos) },
            })
        }
    }
}

Therefore implement a if_cfg! macro that expands into #[cfg(cond)] { ... } and #[cfg(not(cond))] { ... }. It should:

  • only contain valid rust syntax to be formattable by rustfmt & easily understood
  • be possible to use in both expression & statement position

This requires submitting a proper patch to the LKML and the Rust for Linux mailing list. Please recall to test your changes (including generating the documentation if changed, running the Rust doctests if changed, etc.), to use a proper title for the commit, to sign your commit under the Developer's Certificate of Origin and to add a Suggested-by: tag, and a Link: tag to this issue. Please see https://docs.kernel.org/process/submitting-patches.html and https://rust-for-linux.com/contributing for details.

Metadata

Metadata

Assignees

No one assigned

    Labels

    easyExpected to be an easy issue to resolve.good first issueGood for newcomers• libRelated to the `rust/` library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions