derive_more icon indicating copy to clipboard operation
derive_more copied to clipboard

Better delegation detection in fmt derives

Open justDeeevin opened this issue 6 months ago • 2 comments

#322 added a behavior that automatically detects when actual printing behavior is being delegated to the formatter. However, I'm finding that this isn't applying in more complex cases.

Here's my situation: I've got a Value enum in my crate serde-beve which represents the self-describing values in the BEVE data format. In this enum, strings are stored as Vec<u8>s in order to more closely match how they're stored in the data format itself, and to allow me to just write the bytes directly during serialization. However, I'd like the debug implementation of Value to print the string itself instead of the bytes. Should be simple:

#[derive(derive_more::Debug)]
enum Value {
    // ...
    StringArray(
        #[debug("{:?}", _0.iter().map(|v| unsafe {std::str::from_utf8_unchecked(v)}))]
        Vec<Vec<u8>>
    ),
    // ...
}

However, as described in #321, this ends up never pretty-printing the vector

fn main() {
    let value = Value::from(vec!["hello", "world"]); // impl From<Vec<&str>> for Value is provided by my crate
    println!("{value:#?}");
}

Expected:

StringArray(
  [
    "hello",
    "world",
  ],
)

Got:

String(
  ["hello", "world"],
)

I'm not sure what the current implementation lacks that prevents it from successfully handling this case, but I feel like it should be possible.

justDeeevin avatar Sep 12 '25 22:09 justDeeevin

@justDeeevin

I'm not sure what the current implementation lacks that prevents it from successfully handling this case, but I feel like it should be possible.

Transparent delegation for fields in #[derive(Debug)] just hasn't been implemented yet. As for now, it's only supported for the top-level attribute only, as the doc specifies:

If the top-level #[debug("...", args...)] attribute (the one for a whole struct or variant) is specified and can be trivially substituted with a transparent delegation call to the inner type, then all the additional formatting parameters do work as expected

Would love to see a PR, if you need this.

tyranron avatar Sep 13 '25 00:09 tyranron

Ooohh sorry i didn't catch that.

I'll definitely look into contributing, but I make no promises. Proc macros make my head spin

justDeeevin avatar Sep 13 '25 00:09 justDeeevin