Skip to content

Conversation

@dtolnay
Copy link
Contributor

@dtolnay dtolnay commented Nov 21, 2025

derive(Decode) was incorrectly looking at whether the "std" feature is enabled in the host platform to decide on how to generate decoding code. This is not correct. When using the Cargo v2 feature resolver (edition 2021+), or when using the v1 feature resolver and cross-compiling, it can happen that "std" is enabled in the host platform and not enabled in the target platform, leading to generated code that does not compile.

The std- and alloc-related generated code needs to depend on whether "std" is enabled in the target platform.

Repro:

# Cargo.toml

[package]
name = "repro"
version = "0.0.0"
edition = "2024"
publish = false

[dependencies]
minicbor = { version = "2.1.2", default-features = false, features = ["alloc", "derive"] }

[build-dependencies]
minicbor = { version = "2.1.2", features = ["derive", "std"] }
// build.rs

use std::collections::HashSet;

#[derive(Default, minicbor::Encode)]
#[cbor(transparent)]
struct Thing {
    // Encode something that requires cfg(feature = "std") on the host platform
    set: HashSet<String>,
}

fn main() {
    let thing = Thing::default();
    let mut buffer = [0u8; 4];
    minicbor::encode(&thing, buffer.as_mut()).unwrap();
    println!("cargo:warning={:?}", buffer);
}
// src/lib.rs

#![no_std]

extern crate alloc;

use alloc::borrow::Cow;

#[derive(minicbor::Decode)]
#[cbor(transparent)]
pub struct Thing<'a>(#[cbor(borrow)] pub Cow<'a, str>);

cargo check --target x86_64-unknown-none previously failed like this, because the std feature on the host platform was being applied improperly against generated code built for the target platform.

error[E0433]: failed to resolve: use of unresolved module or unlinked crate `std`
 --> src/lib.rs:9:10
  |
9 | #[derive(minicbor::Decode)]
  |          ^^^^^^^^^^^^^^^^ use of unresolved module or unlinked crate `std`
  |
  = help: if you wanted to use a crate named `std`, use `cargo add std` to add it to your `Cargo.toml`
  = note: this error originates in the derive macro `minicbor::Decode` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider importing this enum
  |
7 + use alloc::borrow::Cow;
  |

Signed-off-by: David Tolnay <dtolnay@gmail.com>
@twittner twittner merged commit d353d08 into twittner:develop Nov 23, 2025
2 checks passed
@twittner
Copy link
Owner

Thanks again @dtolnay!

@dtolnay dtolnay deleted the cfg branch November 23, 2025 23:53
@twittner
Copy link
Owner

Published as 2.1.3 to crates.io.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants