Cfg(feature = "dep:...")?

I have the following (in a program to verify files from the Linux system package manager):

[features]
# Include the Arch Linux (pacman/alpm) backend
arch_linux = ["dep:alpm", "dep:mtree", "dep:sha2", "dep:flate2"]

# Include support for the Debian (dpkg/apt) backend
debian = ["dep:md-5"]


[dependencies]
# ...
md-5 = { version = "0.10.6", optional = true }
sha2 = { version = "0.11.0-pre.3", optional = true }

(other distros are planned)

Now I need to use cfg expressions in some code. Eg. something like:

    match checksum {
        #[cfg(feature = "dep:md5")]
        Checksum::Md5(expected) => {
            use md5::Digest;
            let mut hasher = md5::Md5::new();
            loop {
                match reader.read(&mut buffer) {
                    Ok(0) => break,
                    Ok(n) => {
                        hasher.update(&buffer[..n]);
                    }
                    Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
                    Err(e) => Err(e)?,
                }
            }
            let mut actual = Default::default();
            hasher.finalize_into(&mut actual);

            if actual[..] != expected[..] {
                issues.push(IssueKind::ChecksumIncorrect);
            }
        }
       // Same for sha256 etc

Unfortunately this doesn't work. Nor does "md5" as a feature. How do I test for if this dependency is enabled inside my crate code? The whole point of using the dep: syntax is to not clutter the feature list with things the user shouldn't select directly. So hopefully I don't need to create a feature internal_do_not_select_directly_md5...

You have to use feature = "debian", and list multiple features if they all enable md5.

There’s no detection for enabled dependencies, only features.

There is a convention of using __ prefix for feature names that you don’t want users to set. docs.rs and lib.rs sites will hide them.

2 Likes

Thanks, I will use that. Multiple backends could indeed enable the same hash type (and I'd rather keep the relevant generic code as simple as possible).

Also the __ prefix seems very Python-esque. I would have expected a better solution from the Rust ecosystem.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.